You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

48 lines
1.5 KiB

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