-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
480 lines (420 loc) · 13.1 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
'use strict';
var fs = require('fs');
var path = require('path');
var File = require('./lib/file');
var utils = require('./lib/utils');
var Emitter = require('component-emitter');
var cache = {dirs: {}, files: [], paths: null};
/**
* Iterates over [npm-paths][] and emits `file` for every resolved filepath, and `match`
* for files that match any specified [matchers][]. Paths are cached in memory using a few
* different objects:
*
* - `cache.paths`: array of absolute directory and file paths
* - `cache.names`: object of [vinyl][] files, where `file.name` is the object key. `file.name` is the basename of the filepath, but it's aliased as `name` so we can use it without touching the getters/setters on the vinyl file.
* - `cache.files`: array of [vinyl][] files
*
* ```js
* var resolver = new Resolver();
* resolver.resolve();
* console.log(resolver);
* ```
* @param {Object} `options` Specify a cache to use on `options.cache`.
* @api public
*/
function Resolver(options) {
this.options = options || {};
utils.define(this, '_callbacks', {});
utils.define(this, 'fns', []);
this.cwd = this.options.cwd || process.cwd();
this.initCache();
}
/**
* Mix in Emitter methods
*/
Object.setPrototypeOf(Resolver.prototype, Emitter.prototype);
/**
* Clear the cache
*/
Resolver.prototype.initCache = function() {
if (typeof this.options.paths !== 'undefined') {
this.paths = this.options.paths;
}
this.filters = [];
this.matchers = {};
this.cache = this.options.cache || {};
this.cache.dirs = null;
this.cache.files = [];
this.cache.paths = [];
this.cache.names = {};
this.cache.ignored = {};
this.cache.matches = {};
this.matches = [];
var ignored = utils.arrayify(this.options.ignore || utils.ignore);
if (ignored.length) {
var fn = utils.ignoreMatcher(ignored, this.options);
this.filters.push(function(name, file) {
return fn(name) || fn(file.path);
});
}
};
/**
* Clear the cache
*/
Resolver.prototype.clearCache = function() {
cache = {dirs: {}, files: [], paths: null};
this.initCache();
};
/**
* Iterates over [npm-paths][] and returns an array of [vinyl][] files that match any
* provided matchers. Also emits `file` for all files, and `match` for matches. Additionally,
* paths are cached on the first call to `.resolve` so that any subsequent calls during
* the same process will use the cached filepaths instead of hitting the file system again.
* You can force `.resolve` to hit the file system again by deleting or nulling
* `resolver.cache.dirs`.
*
* ```js
* resolver.match('verb', function(basename, file) {
* return basename === 'verb';
* });
*
* // matches
* console.log(resolver.resolve());
*
* // all cached paths
* console.log(resolver);
* ```
* @param {Function|String|Array|RegExp} `fn` Optionally specify a matcher value.
* @param {Object} `options`
* @return {Array} Returns an array of [vinyl][] files.
* @api public
*/
Resolver.prototype.resolve = function(fn, options) {
if (utils.isObject(fn)) {
options = fn;
fn = null;
}
if (fn) this.match.apply(this, arguments);
// pass options only, not filter function
this.resolveDirs(options);
return this.matches;
};
/**
* Find a filepath where `file.basename` exactly matches the given `name`. This method is standalone and
* does not require use of the `.resolve` method or matchers.
*
* ```js
* var filepath = resolver.find('foo');
* ```
* @param {String} `name` Basename of the file to match.
* @return {String|undefined} Returns the absolute filepath if a match is found, otherwise undefined.
* @api public
*/
Resolver.prototype.find = function(name) {
if (this.cache.names.hasOwnProperty(name)) {
return this.cache.names[name];
}
var paths = this.npmPaths();
for (var i = 0; i < paths.length; i++) {
var fp = path.resolve(paths[i], name);
if (utils.exists(fp)) {
this.cache.names[name] = fp;
return fp;
}
}
};
/**
* Define a matcher to use for matching files when the `resolve` method is called.
* If a string or array of strings is passed, strict equality is used for comparisons
* with `file.name`.
*
* ```js
* resolver.match('foo');
* ```
* @param {String|Function|Array|RegExp} `name` Optionally provide `name` to emit when a match is found, a matcher function, string to match, array of strings, or regex.
* @param {String|Function|Array|RegExp} `val` Matcher function, string to match, array of strings, or regex.
* @param {Object} `options` If a string is passed, options may be passed to [micromatch][] to convert the string to regex.
* @return {Object} Returns the instance for chaining.
* @api public
*/
Resolver.prototype.match = function(name, val, options) {
if (utils.typeOf(val) === 'undefined' || utils.typeOf(val) === 'object') {
options = val;
val = this.matcher(name, options);
if (typeof name !== 'string') {
this.fns.push(val);
return this;
}
} else {
val = this.matcher(val, options);
}
this.matchers[name] = this.matchers[name] || [];
this.matchers[name].push(val);
return this;
};
/**
* Define a filter function, glob, string or regex to use for excluding files before
* matchers are run.
*
* ```js
* resolver.filter('*.foo');
* ```
* @param {String|RegExp|Function} `val`
* @param {Object} `options`
* @return {Object}
* @api public
*/
Resolver.prototype.filter = function(val, options) {
this.filters.push(this.matcher(val, options));
return this;
};
/**
* Define a matcher to use for matching files when the `resolve` method is called. If a string or array of strings is passed, any `file.name` that contains the given string or strings will return true.
*
* ```js
* resolver.contains('foo');
* ```
* @param {String|Function|Array|RegExp} `name` Optionally provide `name` to emit when a match is found, a matcher function, string to match, array of strings, or regex.
* @param {String|Function|Array|RegExp} `val` Matcher function, string to match, array of strings, or regex.
* @param {Object} `options` If a string is passed, options may be passed to [micromatch][] to convert the string to regex.
* @return {Object} Returns the instance for chaining.
* @api public
*/
Resolver.prototype.contains = function(name, fn, options) {
var args = [].slice.call(arguments);
if (utils.typeOf(args[args.length - 1]) === 'object') {
options = args.pop();
}
options = utils.extend({}, options, {contains: true});
args.push(options);
return this.match.apply(this, args);
};
/**
* Private method that takes a value and returns a matcher function to use for matching files.
*
* @param {any} val
* @param {Object} options
* @return {Function}
*/
Resolver.prototype.matcher = function(val, options) {
if (utils.typeOf(val) === 'array') {
val = val.join('|');
}
if (utils.typeOf(val) === 'string') {
if (utils.isGlob(val)) {
this.options.recurse = true;
}
val = utils.mm.makeRe(val, options);
}
if (utils.typeOf(val) === 'regexp') {
return function(name, file) {
return val.test(name) || val.test(file.relative);
};
}
if (utils.typeOf(val) !== 'function') {
return function noop() {};
}
return val;
};
/**
* Resolve sub-directories from npm-paths. This method probably doesn't need to
* be used directly, but it's exposed in case you want to customize behavior. Also note that
* `options.recurse` must be defined as `true` to recurse into child directories. Alternative,
* if **any** matcher is a glob pattern with a globstar (double star: `**`), `options.recurse`
* will automatically be set to `true`.
*
* ```js
* resolver.resolveDirs(function(basename, file) {
* return !/foo/.test(file.path);
* });
* ```
* @emits `ignore` when a file is removed.
* @param {Function} `fn` Optionally specify a filter function to use on filepaths. If provided, the function will be called before any matchers are called. `basename` and `file` are exposed to the filter function as arguments, where `file` is an instance of [vinyl][].
* @return {Object} Returns the [cache](#cache).
* @api public
*/
Resolver.prototype.resolveDirs = function(fn, options) {
if (!this.cache.dirs) {
this.cache.dirs = {};
var paths = this.paths || this.npmPaths();
this.emit('paths', paths);
for (var i = 0; i < paths.length; i++) {
this.readdir(path.resolve(paths[i]), fn, options);
}
} else {
var files = this.cache.files;
for (var j = 0; j < files.length; j++) {
this.runMatchers(files[j]);
}
}
return this.cache;
};
/**
* Create a new vinyl file at the given `cwd`
*/
Resolver.prototype.readdir = function(dir, fn, options) {
if (typeof fn !== 'function') {
options = fn;
fn = null;
}
var opts = utils.extend({}, this.options, options);
// since the npm paths array is created dynamically, we need to make sure they actually exist
if (utils.exists(dir)) {
var stat = fs.lstatSync(dir);
var file;
if (!stat.isDirectory()) {
file = this.toFile(path.dirname(dir), path.dirname(dir));
file.stat = stat;
this.cacheFile(dir, file, fn);
return;
}
this.cache.paths.push(dir);
this.cache.dirs[dir] = [];
var files = cache.files[dir] || (cache.files[dir] = fs.readdirSync(dir));
var len = files.length;
var idx = -1;
this.emit('dir', dir, files);
while (++idx < len) {
file = this.toFile(dir, files[idx]);
file.stat = fs.lstatSync(file.path);
var cached = this.cacheFile(dir, file, fn);
if (cached === false) {
continue;
}
this.cache.dirs[dir].push(file);
if (opts.recurse === true && file.stat.isDirectory()) {
this.readdir(file.path, fn, options);
}
}
}
};
/**
* Create a new vinyl file at the given `cwd`
*/
Resolver.prototype.toFile = function(cwd, name) {
var obj = {};
obj.name = name;
obj.path = path.resolve(cwd, name);
obj.base = this.cwd;
// create a vinyl file
var file = new File(obj);
this.emit('file', name, file);
return file;
};
/**
* Create a new vinyl file at the given `cwd`
*/
Resolver.prototype.cacheFile = function(dir, file, fn) {
var filter = this.options.filter;
if (this.runFilters(file) === true) {
return false;
}
// run filter functions
if (typeof filter === 'function') {
if (filter.call(this, file.name, file) === true) {
this.emit('ignore', file);
return false;
}
}
if (typeof fn === 'function') {
if (fn.call(this, file.name, file) === true) {
this.emit('ignore', file);
return false;
}
}
// run matchers
this.runMatchers(file);
// cache files and paths
this.cache.names[file.name] = file;
this.cache.paths.push(file.path);
this.cache.files.push(file);
return file;
};
/**
* Create the array of npm paths to iterate over. This is only done once, as paths are cached after
* the first call. To force [npm-paths][] to be called again delete or null `resolver.paths`.
* @return {Array}
*/
Resolver.prototype.npmPaths = function() {
return cache.paths || this.paths || (cache.paths = this.paths = utils.npmPaths());
};
/**
* Run the array of un-named matcher functions over the given [vinyl][] `file` object, and
* emit `match` for each match.
*
* @param {Object} `file` Instance of [vinyl][].
* @return {undefined}
*/
Resolver.prototype.runFilters = function(file) {
if (this.cache.ignored.hasOwnProperty(file.path)) {
return true;
}
for (var i = 0; i < this.filters.length; i++) {
var filter = this.filters[i];
if (filter(file.name, file)) {
this.cache.ignored[file.path] = true;
this.emit('ignore', file);
return true;
}
}
};
/**
* Run all provided matchers, both named and un-named functions.
*
* @param {Object} file
* @return {undefined}
*/
Resolver.prototype.runMatchers = function(file) {
this.runFns(file);
this.runNamedMatchers(file);
};
/**
* Run the array of un-named matcher functions over the given [vinyl][] `file` object, and
* emit `match` for each match.
*
* @param {Object} `file` Instance of [vinyl][].
* @return {undefined}
*/
Resolver.prototype.runFns = function(file) {
for (var i = 0; i < this.fns.length; i++) {
var isMatch = this.fns[i];
if (isMatch(file.name, file)) {
if (!this.cache.matches.hasOwnProperty(file.path)) {
this.cache.matches[file.path] = true;
this.matches.push(file);
this.emit('match', file);
}
}
}
};
/**
* Run named matcher functions over the given [vinyl][] `file` object. Emits two events:
* `match` and the `name` of the matcher for each match.
*
* @param {Object} `file` Instance of [vinyl][].
* @return {undefined}
*/
Resolver.prototype.runNamedMatchers = function(file) {
for (var key in this.matchers) {
if (this.matchers.hasOwnProperty(key)) {
var fns = this.matchers[key];
var len = fns.length;
var idx = -1;
while (++idx < len) {
var isMatch = fns[idx];
if (isMatch(file.name, file)) {
if (!this.cache.matches.hasOwnProperty(file.path)) {
this.cache.matches[file.path] = true;
this.matches.push(file);
this.emit('match', file);
this.emit(key, file);
}
}
}
}
}
};
/**
* Expose `Resolver`
*/
module.exports = Resolver;