index.js 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. 'use strict';
  2. const path = require('path');
  3. const pathType = require('path-type');
  4. const getExtensions = extensions => extensions.length > 1 ? `{${extensions.join(',')}}` : extensions[0];
  5. const getPath = (filepath, cwd) => {
  6. const pth = filepath[0] === '!' ? filepath.slice(1) : filepath;
  7. return path.isAbsolute(pth) ? pth : path.join(cwd, pth);
  8. };
  9. const addExtensions = (file, extensions) => {
  10. if (path.extname(file)) {
  11. return `**/${file}`;
  12. }
  13. return `**/${file}.${getExtensions(extensions)}`;
  14. };
  15. const getGlob = (dir, opts) => {
  16. if (opts.files && !Array.isArray(opts.files)) {
  17. throw new TypeError(`Expected \`files\` to be of type \`Array\` but received type \`${typeof opts.files}\``);
  18. }
  19. if (opts.extensions && !Array.isArray(opts.extensions)) {
  20. throw new TypeError(`Expected \`extensions\` to be of type \`Array\` but received type \`${typeof opts.extensions}\``);
  21. }
  22. if (opts.files && opts.extensions) {
  23. return opts.files.map(x => path.join(dir, addExtensions(x, opts.extensions)));
  24. }
  25. if (opts.files) {
  26. return opts.files.map(x => path.join(dir, `**/${x}`));
  27. }
  28. if (opts.extensions) {
  29. return [path.join(dir, `**/*.${getExtensions(opts.extensions)}`)];
  30. }
  31. return [path.join(dir, '**')];
  32. };
  33. module.exports = (input, opts) => {
  34. opts = Object.assign({cwd: process.cwd()}, opts);
  35. if (typeof opts.cwd !== 'string') {
  36. return Promise.reject(new TypeError(`Expected \`cwd\` to be of type \`string\` but received type \`${typeof opts.cwd}\``));
  37. }
  38. return Promise.all([].concat(input).map(x => pathType.dir(getPath(x, opts.cwd))
  39. .then(isDir => isDir ? getGlob(x, opts) : x)))
  40. .then(globs => [].concat.apply([], globs));
  41. };
  42. module.exports.sync = (input, opts) => {
  43. opts = Object.assign({cwd: process.cwd()}, opts);
  44. if (typeof opts.cwd !== 'string') {
  45. throw new TypeError(`Expected \`cwd\` to be of type \`string\` but received type \`${typeof opts.cwd}\``);
  46. }
  47. const globs = [].concat(input).map(x => pathType.dirSync(getPath(x, opts.cwd)) ? getGlob(x, opts) : x);
  48. return [].concat.apply([], globs);
  49. };