| Leo Repp | 58b9f11 | 2021-11-22 11:57:47 +0100 | [diff] [blame^] | 1 | 'use strict'; |
| 2 | const path = require('path'); |
| 3 | const arrify = require('arrify'); |
| 4 | const pathType = require('path-type'); |
| 5 | |
| 6 | const getExtensions = extensions => extensions.length > 1 ? `{${extensions.join(',')}}` : extensions[0]; |
| 7 | const getPath = filepath => filepath[0] === '!' ? filepath.slice(1) : filepath; |
| 8 | |
| 9 | const addExtensions = (file, extensions) => { |
| 10 | if (path.extname(file)) { |
| 11 | return `**/${file}`; |
| 12 | } |
| 13 | |
| 14 | return `**/${file}.${getExtensions(extensions)}`; |
| 15 | }; |
| 16 | |
| 17 | const getGlob = (dir, opts) => { |
| 18 | opts = Object.assign({}, opts); |
| 19 | |
| 20 | if (opts.files && !Array.isArray(opts.files)) { |
| 21 | throw new TypeError(`\`options.files\` must be an \`Array\`, not \`${typeof opts.files}\``); |
| 22 | } |
| 23 | |
| 24 | if (opts.extensions && !Array.isArray(opts.extensions)) { |
| 25 | throw new TypeError(`\`options.extensions\` must be an \`Array\`, not \`${typeof opts.extensions}\``); |
| 26 | } |
| 27 | |
| 28 | if (opts.files && opts.extensions) { |
| 29 | return opts.files.map(x => path.join(dir, addExtensions(x, opts.extensions))); |
| 30 | } else if (opts.files) { |
| 31 | return opts.files.map(x => path.join(dir, `**/${x}`)); |
| 32 | } else if (opts.extensions) { |
| 33 | return [path.join(dir, `**/*.${getExtensions(opts.extensions)}`)]; |
| 34 | } |
| 35 | |
| 36 | return [path.join(dir, '**')]; |
| 37 | }; |
| 38 | |
| 39 | module.exports = (input, opts) => { |
| 40 | return Promise.all(arrify(input).map(x => pathType.dir(getPath(x)) |
| 41 | .then(isDir => isDir ? getGlob(x, opts) : x))) |
| 42 | .then(globs => [].concat.apply([], globs)); |
| 43 | }; |
| 44 | |
| 45 | module.exports.sync = (input, opts) => { |
| 46 | const globs = arrify(input).map(x => pathType.dirSync(getPath(x)) ? getGlob(x, opts) : x); |
| 47 | return [].concat.apply([], globs); |
| 48 | }; |