2 const arrayUnion = require('array-union');
3 const glob = require('glob');
4 const fastGlob = require('fast-glob');
5 const dirGlob = require('dir-glob');
6 const gitignore = require('./gitignore');
8 const DEFAULT_FILTER = () => false;
10 const isNegative = pattern => pattern[0] === '!';
12 const assertPatternsInput = patterns => {
13 if (!patterns.every(x => typeof x === 'string')) {
14 throw new TypeError('Patterns must be a string or an array of strings');
18 const generateGlobTasks = (patterns, taskOpts) => {
19 patterns = [].concat(patterns);
20 assertPatternsInput(patterns);
24 taskOpts = Object.assign({
26 expandDirectories: true
29 patterns.forEach((pattern, i) => {
30 if (isNegative(pattern)) {
34 const ignore = patterns
37 .map(pattern => pattern.slice(1));
39 const opts = Object.assign({}, taskOpts, {
40 ignore: taskOpts.ignore.concat(ignore)
43 globTasks.push({pattern, opts});
49 const globDirs = (task, fn) => {
50 let opts = {cwd: task.opts.cwd};
52 if (Array.isArray(task.opts.expandDirectories)) {
53 opts = Object.assign(opts, {files: task.opts.expandDirectories});
54 } else if (typeof task.opts.expandDirectories === 'object') {
55 opts = Object.assign(opts, task.opts.expandDirectories);
58 return fn(task.pattern, opts);
61 const getPattern = (task, fn) => task.opts.expandDirectories ? globDirs(task, fn) : [task.pattern];
63 module.exports = (patterns, opts) => {
67 globTasks = generateGlobTasks(patterns, opts);
69 return Promise.reject(err);
72 const getTasks = Promise.all(globTasks.map(task => Promise.resolve(getPattern(task, dirGlob))
73 .then(globs => Promise.all(globs.map(glob => ({
78 .then(tasks => arrayUnion.apply(null, tasks));
80 const getFilter = () => {
81 return Promise.resolve(
82 opts && opts.gitignore ?
83 gitignore({cwd: opts.cwd, ignore: opts.ignore}) :
91 .then(tasks => Promise.all(tasks.map(task => fastGlob(task.pattern, task.opts))))
92 .then(paths => arrayUnion.apply(null, paths))
93 .then(paths => paths.filter(p => !filter(p)));
97 module.exports.sync = (patterns, opts) => {
98 const globTasks = generateGlobTasks(patterns, opts);
100 const getFilter = () => {
101 return opts && opts.gitignore ?
102 gitignore.sync({cwd: opts.cwd, ignore: opts.ignore}) :
106 const tasks = globTasks.reduce((tasks, task) => {
107 const newTask = getPattern(task, dirGlob.sync).map(glob => ({
111 return tasks.concat(newTask);
114 const filter = getFilter();
117 (matches, task) => arrayUnion(matches, fastGlob.sync(task.pattern, task.opts)),
119 ).filter(p => !filter(p));
122 module.exports.generateGlobTasks = generateGlobTasks;
124 module.exports.hasMagic = (patterns, opts) => []
126 .some(pattern => glob.hasMagic(pattern, opts));
128 module.exports.gitignore = gitignore;