UNPKG

1.67 kBJavaScriptView Raw
1'use strict';
2
3const q = require('q');
4const qfs = require('q-io/fs');
5const _ = require('lodash');
6const glob = require('glob');
7const defaults = require('./defaults');
8const utils = require('./utils');
9
10const isMask = (pattern) => glob.hasMagic(pattern);
11
12const getFilesByMask = (pattern, options) => {
13 return q.nfcall(glob, pattern, options)
14 .then((paths) => {
15 return _.isEmpty(paths) && !isMask(pattern)
16 ? q.reject(new Error(`Cannot find files using path '${pattern}'`))
17 : paths;
18 });
19};
20
21const listFiles = (path) => {
22 return qfs.listTree(path)
23 .then((paths) => utils.asyncFilter(paths, utils.isFile));
24};
25
26const expandPath = (path, options) => {
27 if (!qfs.isAbsolute(path)) {
28 path = qfs.join(options.root, path);
29 }
30
31 return utils.isFile(path)
32 .then((isFile) => isFile ? [path] : listFiles(path))
33 .then((paths) => paths.filter((path) => utils.matchesFormats(path, options.formats)))
34 .then((paths) => paths.map((path) => qfs.absolute(path)));
35};
36
37const processPaths = (paths, cb) => {
38 return _(paths)
39 .map(cb)
40 .thru(q.all)
41 .value()
42 .then(_.flatten)
43 .then(_.uniq);
44};
45
46exports.expandPaths = (paths, expandOpts, globOpts) => {
47 expandOpts = defaults(expandOpts);
48
49 paths = [].concat(paths);
50
51 return processPaths(paths, (path) => getFilesByMask(path, globOpts))
52 .then((matchedPaths) => processPaths(matchedPaths, (path) => expandPath(path, expandOpts)));
53};
54
55exports.isMask = isMask;
56
57// :TODO: Backward compatibility
58exports.isMasks = (patterns) => [].concat(patterns).every(isMask);
59