index.js 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  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 = (directory, options) => {
  16. if (options.files && !Array.isArray(options.files)) {
  17. throw new TypeError(`Expected \`files\` to be of type \`Array\` but received type \`${typeof options.files}\``);
  18. }
  19. if (options.extensions && !Array.isArray(options.extensions)) {
  20. throw new TypeError(`Expected \`extensions\` to be of type \`Array\` but received type \`${typeof options.extensions}\``);
  21. }
  22. if (options.files && options.extensions) {
  23. return options.files.map(x => path.posix.join(directory, addExtensions(x, options.extensions)));
  24. }
  25. if (options.files) {
  26. return options.files.map(x => path.posix.join(directory, `**/${x}`));
  27. }
  28. if (options.extensions) {
  29. return [path.posix.join(directory, `**/*.${getExtensions(options.extensions)}`)];
  30. }
  31. return [path.posix.join(directory, '**')];
  32. };
  33. module.exports = async (input, options) => {
  34. options = {
  35. cwd: process.cwd(),
  36. ...options
  37. };
  38. if (typeof options.cwd !== 'string') {
  39. throw new TypeError(`Expected \`cwd\` to be of type \`string\` but received type \`${typeof options.cwd}\``);
  40. }
  41. const globs = await Promise.all([].concat(input).map(async x => {
  42. const isDirectory = await pathType.isDirectory(getPath(x, options.cwd));
  43. return isDirectory ? getGlob(x, options) : x;
  44. }));
  45. return [].concat.apply([], globs); // eslint-disable-line prefer-spread
  46. };
  47. module.exports.sync = (input, options) => {
  48. options = {
  49. cwd: process.cwd(),
  50. ...options
  51. };
  52. if (typeof options.cwd !== 'string') {
  53. throw new TypeError(`Expected \`cwd\` to be of type \`string\` but received type \`${typeof options.cwd}\``);
  54. }
  55. const globs = [].concat(input).map(x => pathType.isDirectorySync(getPath(x, options.cwd)) ? getGlob(x, options) : x);
  56. return [].concat.apply([], globs); // eslint-disable-line prefer-spread
  57. };