index.js 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. 'use strict';
  2. var Promise = require('pinkie-promise');
  3. var arrayUnion = require('array-union');
  4. var objectAssign = require('object-assign');
  5. var glob = require('glob');
  6. var pify = require('pify');
  7. var globP = pify(glob, Promise).bind(glob);
  8. function isNegative(pattern) {
  9. return pattern[0] === '!';
  10. }
  11. function isString(value) {
  12. return typeof value === 'string';
  13. }
  14. function assertPatternsInput(patterns) {
  15. if (!patterns.every(isString)) {
  16. throw new TypeError('patterns must be a string or an array of strings');
  17. }
  18. }
  19. function generateGlobTasks(patterns, opts) {
  20. patterns = [].concat(patterns);
  21. assertPatternsInput(patterns);
  22. var globTasks = [];
  23. opts = objectAssign({
  24. cache: Object.create(null),
  25. statCache: Object.create(null),
  26. realpathCache: Object.create(null),
  27. symlinks: Object.create(null),
  28. ignore: []
  29. }, opts);
  30. patterns.forEach(function (pattern, i) {
  31. if (isNegative(pattern)) {
  32. return;
  33. }
  34. var ignore = patterns.slice(i).filter(isNegative).map(function (pattern) {
  35. return pattern.slice(1);
  36. });
  37. globTasks.push({
  38. pattern: pattern,
  39. opts: objectAssign({}, opts, {
  40. ignore: opts.ignore.concat(ignore)
  41. })
  42. });
  43. });
  44. return globTasks;
  45. }
  46. module.exports = function (patterns, opts) {
  47. var globTasks;
  48. try {
  49. globTasks = generateGlobTasks(patterns, opts);
  50. } catch (err) {
  51. return Promise.reject(err);
  52. }
  53. return Promise.all(globTasks.map(function (task) {
  54. return globP(task.pattern, task.opts);
  55. })).then(function (paths) {
  56. return arrayUnion.apply(null, paths);
  57. });
  58. };
  59. module.exports.sync = function (patterns, opts) {
  60. var globTasks = generateGlobTasks(patterns, opts);
  61. return globTasks.reduce(function (matches, task) {
  62. return arrayUnion(matches, glob.sync(task.pattern, task.opts));
  63. }, []);
  64. };
  65. module.exports.generateGlobTasks = generateGlobTasks;
  66. module.exports.hasMagic = function (patterns, opts) {
  67. return [].concat(patterns).some(function (pattern) {
  68. return glob.hasMagic(pattern, opts);
  69. });
  70. };