2 const arrayUnion = require('array-union');
3 const glob = require('glob');
4 const pify = require('pify');
5 const dirGlob = require('dir-glob');
6 const gitignore = require('./gitignore');
8 const globP = pify(glob);
9 const DEFAULT_FILTER = () => false;
11 const isNegative = pattern => pattern[0] === '!';
13 const assertPatternsInput = patterns => {
14 if (!patterns.every(x => typeof x === 'string')) {
15 throw new TypeError('Patterns must be a string or an array of strings');
19 const generateGlobTasks = (patterns, taskOpts) => {
20 patterns = [].concat(patterns);
21 assertPatternsInput(patterns);
25 taskOpts = Object.assign({
26 cache: Object.create(null),
27 statCache: Object.create(null),
28 realpathCache: Object.create(null),
29 symlinks: Object.create(null),
31 expandDirectories: true,
35 patterns.forEach((pattern, i) => {
36 if (isNegative(pattern)) {
40 const ignore = patterns
43 .map(pattern => pattern.slice(1));
45 const opts = Object.assign({}, taskOpts, {
46 ignore: taskOpts.ignore.concat(ignore)
49 globTasks.push({pattern, opts});
55 const globDirs = (task, fn) => {
56 if (Array.isArray(task.opts.expandDirectories)) {
57 return fn(task.pattern, {files: task.opts.expandDirectories});
60 if (typeof task.opts.expandDirectories === 'object') {
61 return fn(task.pattern, task.opts.expandDirectories);
64 return fn(task.pattern);
67 const getPattern = (task, fn) => task.opts.expandDirectories ? globDirs(task, fn) : [task.pattern];
69 module.exports = (patterns, opts) => {
73 globTasks = generateGlobTasks(patterns, opts);
75 return Promise.reject(err);
78 const getTasks = Promise.all(globTasks.map(task => Promise.resolve(getPattern(task, dirGlob))
79 .then(globs => Promise.all(globs.map(glob => ({
84 .then(tasks => arrayUnion.apply(null, tasks));
86 const getFilter = () => {
87 return Promise.resolve(
88 opts && opts.gitignore ?
89 gitignore({cwd: opts.cwd, ignore: opts.ignore}) :
97 .then(tasks => Promise.all(tasks.map(task => globP(task.pattern, task.opts))))
98 .then(paths => arrayUnion.apply(null, paths))
99 .then(paths => paths.filter(p => !filter(p)));
103 module.exports.sync = (patterns, opts) => {
104 const globTasks = generateGlobTasks(patterns, opts);
106 const getFilter = () => {
107 return opts && opts.gitignore ?
108 gitignore.sync({cwd: opts.cwd, ignore: opts.ignore}) :
112 const tasks = globTasks.reduce((tasks, task) => {
113 const newTask = getPattern(task, dirGlob.sync).map(glob => ({
117 return tasks.concat(newTask);
120 const filter = getFilter();
123 (matches, task) => arrayUnion(matches, glob.sync(task.pattern, task.opts)),
125 ).filter(p => !filter(p));
128 module.exports.generateGlobTasks = generateGlobTasks;
130 module.exports.hasMagic = (patterns, opts) => []
132 .some(pattern => glob.hasMagic(pattern, opts));
134 module.exports.gitignore = gitignore;