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.

index.js 2.3KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. 'use strict';
  2. var Combine = require('ordered-read-streams');
  3. var unique = require('unique-stream');
  4. var pumpify = require('pumpify');
  5. var isNegatedGlob = require('is-negated-glob');
  6. var extend = require('extend');
  7. var GlobStream = require('./readable');
  8. function globStream(globs, opt) {
  9. if (!opt) {
  10. opt = {};
  11. }
  12. var ourOpt = extend({}, opt);
  13. var ignore = ourOpt.ignore;
  14. ourOpt.cwd = typeof ourOpt.cwd === 'string' ? ourOpt.cwd : process.cwd();
  15. ourOpt.dot = typeof ourOpt.dot === 'boolean' ? ourOpt.dot : false;
  16. ourOpt.silent = typeof ourOpt.silent === 'boolean' ? ourOpt.silent : true;
  17. ourOpt.cwdbase = typeof ourOpt.cwdbase === 'boolean' ? ourOpt.cwdbase : false;
  18. ourOpt.uniqueBy = typeof ourOpt.uniqueBy === 'string' ||
  19. typeof ourOpt.uniqueBy === 'function' ? ourOpt.uniqueBy : 'path';
  20. if (ourOpt.cwdbase) {
  21. ourOpt.base = ourOpt.cwd;
  22. }
  23. // Normalize string `ignore` to array
  24. if (typeof ignore === 'string') {
  25. ignore = [ignore];
  26. }
  27. // Ensure `ignore` is an array
  28. if (!Array.isArray(ignore)) {
  29. ignore = [];
  30. }
  31. // Only one glob no need to aggregate
  32. if (!Array.isArray(globs)) {
  33. globs = [globs];
  34. }
  35. var positives = [];
  36. var negatives = [];
  37. globs.forEach(sortGlobs);
  38. function sortGlobs(globString, index) {
  39. if (typeof globString !== 'string') {
  40. throw new Error('Invalid glob at index ' + index);
  41. }
  42. var glob = isNegatedGlob(globString);
  43. var globArray = glob.negated ? negatives : positives;
  44. globArray.push({
  45. index: index,
  46. glob: glob.pattern,
  47. });
  48. }
  49. if (positives.length === 0) {
  50. throw new Error('Missing positive glob');
  51. }
  52. // Create all individual streams
  53. var streams = positives.map(streamFromPositive);
  54. // Then just pipe them to a single unique stream and return it
  55. var aggregate = new Combine(streams);
  56. var uniqueStream = unique(ourOpt.uniqueBy);
  57. return pumpify.obj(aggregate, uniqueStream);
  58. function streamFromPositive(positive) {
  59. var negativeGlobs = negatives
  60. .filter(indexGreaterThan(positive.index))
  61. .map(toGlob)
  62. .concat(ignore);
  63. return new GlobStream(positive.glob, negativeGlobs, ourOpt);
  64. }
  65. }
  66. function indexGreaterThan(index) {
  67. return function(obj) {
  68. return obj.index > index;
  69. };
  70. }
  71. function toGlob(obj) {
  72. return obj.glob;
  73. }
  74. module.exports = globStream;