1 | 'use strict';
|
2 |
|
3 | const q = require('q');
|
4 | const qfs = require('q-io/fs');
|
5 | const _ = require('lodash');
|
6 | const glob = require('glob');
|
7 | const defaults = require('./defaults');
|
8 | const utils = require('./utils');
|
9 |
|
10 | const isMask = (pattern) => glob.hasMagic(pattern);
|
11 |
|
12 | const 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 |
|
21 | const listFiles = (path) => {
|
22 | return qfs.listTree(path)
|
23 | .then((paths) => utils.asyncFilter(paths, utils.isFile));
|
24 | };
|
25 |
|
26 | const 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 |
|
37 | const processPaths = (paths, cb) => {
|
38 | return _(paths)
|
39 | .map(cb)
|
40 | .thru(q.all)
|
41 | .value()
|
42 | .then(_.flatten)
|
43 | .then(_.uniq);
|
44 | };
|
45 |
|
46 | exports.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 |
|
55 | exports.isMask = isMask;
|
56 |
|
57 |
|
58 | exports.isMasks = (patterns) => [].concat(patterns).every(isMask);
|
59 |
|