UNPKG

2.26 kBJavaScriptView Raw
1const fs = require('fs');
2const globrex = require('globrex');
3const { promisify } = require('util');
4const globalyzer = require('globalyzer');
5const { join, resolve, relative } = require('path');
6const isHidden = /(^|[\\\/])\.[^\\\/\.]/g;
7const readdir = promisify(fs.readdir);
8let CACHE = {};
9
10async function walk(output, prefix, lexer, opts, dirname='', level=0) {
11 const rgx = lexer.segments[level];
12 const dir = join(opts.cwd, prefix, dirname);
13 const files = await readdir(dir);
14 const { dot, filesOnly } = opts;
15
16 let i=0, len=files.length, file;
17 let fullpath, relpath, stats, isMatch;
18
19 for (; i < len; i++) {
20 fullpath = join(dir, file=files[i]);
21 relpath = dirname ? join(dirname, file) : file;
22 if (!dot && isHidden.test(relpath)) continue;
23 isMatch = lexer.regex.test(relpath);
24
25 if ((stats=CACHE[relpath]) === void 0) {
26 CACHE[relpath] = stats = fs.lstatSync(fullpath);
27 }
28
29 if (!stats.isDirectory()) {
30 isMatch && output.push(relative(opts.cwd, fullpath));
31 continue;
32 }
33
34 if (rgx && !rgx.test(file)) continue;
35 !filesOnly && isMatch && output.push(join(prefix, relpath));
36
37 await walk(output, prefix, lexer, opts, relpath, rgx && rgx.toString() !== lexer.globstar && ++level);
38 }
39}
40
41/**
42 * Find files using bash-like globbing.
43 * All paths are normalized compared to node-glob.
44 * @param {String} str Glob string
45 * @param {String} [options.cwd='.'] Current working directory
46 * @param {Boolean} [options.dot=false] Include dotfile matches
47 * @param {Boolean} [options.absolute=false] Return absolute paths
48 * @param {Boolean} [options.filesOnly=false] Do not include folders if true
49 * @param {Boolean} [options.flush=false] Reset cache object
50 * @returns {Array} array containing matching files
51 */
52module.exports = async function (str, opts={}) {
53 let glob = globalyzer(str);
54
55 if (!glob.isGlob) return fs.existsSync(str) ? [str] : [];
56 if (opts.flush) CACHE = {};
57
58 let matches = [];
59 opts.cwd = opts.cwd || '.';
60 const { path } = globrex(glob.glob, { filepath:true, globstar:true, extended:true });
61
62 path.globstar = path.globstar.toString();
63 await walk(matches, glob.base, path, opts, '.', 0);
64
65 return opts.absolute ? matches.map(x => resolve(opts.cwd, x)) : matches;
66};