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