Debian Codegraph @

fs2/readdir.js

raw
1 /* eslint max-statements: off, max-lines: off */
2
3 "use strict";
4
5 var invoke = require("es5-ext/function/invoke")
6 , noop = require("es5-ext/function/noop")
7 , curry = require("es5-ext/function/#/curry")
8 , contains = curry.call(require("es5-ext/array/#/contains"))
9 , diff = require("es5-ext/array/#/diff")
10 , remove = require("es5-ext/array/#/remove")
11 , assign = require("es5-ext/object/assign")
12 , forEach = require("es5-ext/object/for-each")
13 , isCallable = require("es5-ext/object/is-callable")
14 , isCopy = require("es5-ext/object/is-copy")
15 , isValue = require("es5-ext/object/is-value")
16 , toPosInt = require("es5-ext/number/to-pos-integer")
17 , startsWith = require("es5-ext/string/#/starts-with")
18 , deferred = require("deferred")
19 , fs = require("fs")
20 , pathUtils = require("path")
21 , typeByStats = require("./type-by-stats")
22 , watchPath = require("./watch")
23 , isIgnored = require("./is-ignored");
24
25 var isArray = Array.isArray
26 , push = Array.prototype.push
27 , promisify = deferred.promisify
28 , resolve = pathUtils.resolve
29 , sep = pathUtils.sep
30 , original = fs.readdir
31 , lstat = fs.lstat
32 , pLstat = promisify(lstat)
33 , getIsIgnored = isIgnored.getIsIgnored
34 , applyGlobalRules = isIgnored.applyGlobalRules
35 , Readdir
36 , readdir
37 , enoentSurpass
38 , eolRe = /(?:\r\n|[\n\r\u2028\u2029])/
39 , passErrCodes = ["ENOENT", "DIFFTYPE"];
40
41 passErrCodes.contains = contains;
42 enoentSurpass = function (err) { return passErrCodes.contains(err.code) ? [] : err; };
43
44 // eslint-disable-next-line no-empty-function
45 Readdir = function () {};
46 Readdir.prototype = {
47 init: function () {
48 var data, result, promise, stream;
49 stream = this.stream;
50 data = this.read(this.path, this.depth);
51 if (!this.depth) {
52 promise = data.files;
53 if (this.stream) {
54 promise.aside(function (files) {
55 if (!files) return;
56 promise.emit("change", { data: files, added: files, removed: [] });
57 });
58 }
59 return promise;
60 }
61 this.readers = {};
62 result = [];
63 assign(this, deferred());
64 promise = this.promise;
65
66 data.files.done(null, this.reject);
67 if (this.watch) {
68 data.files.on(
69 "end",
70 function () {
71 delete this.readers;
72 if (!promise.resolved) {
73 this.reject(new Error("Directory was removed"));
74 return;
75 }
76 promise.emit("end", result);
77 }.bind(this)
78 );
79 promise.close = this.close.bind(this);
80 }
81
82 (function self(nuData, rootPath, depth) {
83 var getPath, files;
84 this.readers[rootPath] = { files: nuData.files };
85 if (nuData.dirs && nuData.dirs !== nuData.files) {
86 this.readers[rootPath].dirs = nuData.dirs;
87 }
88 if (rootPath) {
89 getPath = function (path) { return rootPath + path; };
90 files = nuData.files.aside(function (newFiles) {
91 if (newFiles.length) {
92 newFiles = newFiles.map(getPath);
93 push.apply(result, newFiles);
94 if (promise.resolved || stream) {
95 promise.emit("change", { data: result, removed: [], added: newFiles });
96 }
97 }
98 return newFiles;
99 });
100 } else {
101 files = nuData.files.aside(function (newFiles) {
102 if (newFiles && newFiles.length) {
103 push.apply(result, newFiles);
104 if (promise.resolved || stream) {
105 promise.emit("change", { data: result, removed: [], added: newFiles });
106 }
107 }
108 return newFiles;
109 });
110 }
111 if (this.watch) {
112 if (rootPath) {
113 nuData.files.on(
114 "end",
115 (nuData.files.onend = function (newFiles) {
116 delete this.readers[rootPath];
117 if (newFiles.length) {
118 newFiles = newFiles.map(getPath);
119 remove.apply(result, newFiles);
120 if (promise.resolved || stream) {
121 promise.emit("change", {
122 data: result,
123 removed: newFiles,
124 added: []
125 });
126 }
127 }
128 }.bind(this))
129 );
130 }
131 nuData.files.on("change", function (nextData) {
132 var removed, added;
133 removed = rootPath ? nextData.removed.map(getPath) : nextData.removed;
134 added = rootPath ? nextData.added.map(getPath) : nextData.added;
135 remove.apply(result, removed);
136 push.apply(result, added);
137 if (promise.resolved || stream) {
138 promise.emit("change", { data: result, removed: removed, added: added });
139 }
140 });
141 }
142
143 if (nuData.dirs) {
144 if (this.watch) {
145 nuData.dirs.on(
146 "change",
147 function (nextData) {
148 deferred
149 .map(
150 nextData.added,
151 function (dir) {
152 return self.call(
153 this,
154 this.read(this.path + sep + rootPath + dir, depth - 1),
155 rootPath + dir + sep, depth - 1
156 );
157 },
158 this
159 )
160 .done();
161 nextData.removed.forEach(
162 function (dir) {
163 var path = rootPath + dir + sep, reader = this.readers[path];
164 if (reader) {
165 reader.files.close();
166 if (reader.dirs) reader.dirs.close();
167 reader.files.onend(reader.files.value);
168 forEach(this.readers, function (newReader, key) {
169 if (startsWith.call(key, path)) {
170 newReader.files.close();
171 if (newReader.dirs) newReader.dirs.close();
172 newReader.files.onend(newReader.files.value);
173 }
174 });
175 }
176 }.bind(this)
177 );
178 }.bind(this)
179 );
180 }
181 return deferred(
182 files(null, enoentSurpass),
183 nuData
184 .dirs(null, enoentSurpass)
185 .map(function (dir) {
186 return self.call(
187 this, this.read(this.path + sep + rootPath + dir, depth - 1),
188 rootPath + dir + sep, depth - 1
189 );
190 }, this)
191 );
192 }
193 return files;
194 }
195 .call(this, data, "", this.depth)
196 .done(this.resolve.bind(this, result), this.reject));
197
198 return this.promise;
199 },
200 close: function () {
201 if (this.readers) {
202 forEach(this.readers, function (data) {
203 data.files.close();
204 if (data.dirs) data.dirs.close();
205 });
206 delete this.readers;
207 }
208 },
209 read: function (path, getDirs) {
210 var dirPaths, paths, data;
211
212 paths = this.readdir(path);
213
214 if (this.type || getDirs) {
215 data = this.filterByType(paths, getDirs);
216 paths = data.files;
217 dirPaths = data.dirs;
218 } else if (this.pattern || this.globalRules) {
219 paths = this.filterByPattern(paths);
220 }
221 if (this.isIgnored) {
222 if (dirPaths && dirPaths !== paths) {
223 dirPaths = this.filterIgnored(dirPaths);
224 paths = this.filterIgnored(paths);
225 } else {
226 paths = this.filterIgnored(paths);
227 if (dirPaths) dirPaths = paths;
228 }
229 }
230
231 return { files: paths, dirs: dirPaths };
232 },
233 filterByType: function (paths, getDirs) {
234 var result = {}
235 , test
236 , rootPath = paths.root
237 , files
238 , dirs
239 , resolveCb
240 , defFiles
241 , defDirs
242 , close
243 , resolved
244 , failed;
245
246 if (this.type || this.pattern || this.globalRules) {
247 files = [];
248 defFiles = deferred();
249 result.files = defFiles.promise;
250 result.files.root = rootPath;
251 } else {
252 result.files = paths;
253 }
254 if (getDirs) {
255 if (this.type && isCopy(this.type, { directory: true }) && !this.pattern) {
256 dirs = files;
257 result.dirs = result.files;
258 getDirs = false;
259 } else {
260 dirs = [];
261 defDirs = deferred();
262 result.dirs = defDirs.promise;
263 result.dirs.root = rootPath;
264 }
265 }
266
267 resolveCb = function (e) {
268 if (defFiles) {
269 if (e) defFiles.reject(e);
270 else defFiles.resolve(files);
271 }
272 if (defDirs) {
273 if (e) defDirs.reject(e);
274 else defDirs.resolve(dirs);
275 }
276 failed = Boolean(e);
277 resolved = true;
278 };
279
280 paths.done(
281 function (newPaths) {
282 if (!newPaths) {
283 files = null;
284 resolveCb();
285 return;
286 }
287 var waiting = newPaths.length;
288 if (!waiting) {
289 resolveCb();
290 return;
291 }
292 newPaths.forEach(function (path) {
293 var fullPath = rootPath + sep + path;
294 if (
295 (!getDirs && this.pattern && !this.pattern.test(fullPath)) ||
296 (this.globalRules && applyGlobalRules(fullPath, this.globalRules))
297 ) {
298 if (!--waiting) resolveCb();
299 return;
300 }
301 lstat(
302 fullPath,
303 function (err, stat) {
304 var type;
305 if (resolved) return;
306 if (!err) {
307 try {
308 type = typeByStats(stat);
309 } catch (e) {
310 resolveCb(e);
311 return;
312 }
313 if (
314 files &&
315 (!this.type || this.type[type]) &&
316 (!this.pattern || !getDirs || this.pattern.test(fullPath))
317 ) {
318 files.push(path);
319 }
320 if (getDirs && type === "directory") {
321 if (!this.dirFilter || this.dirFilter(fullPath)) {
322 dirs.push(path);
323 }
324 }
325 } else if (err.code !== "ENOENT") {
326 resolveCb(err);
327 return;
328 }
329 if (!--waiting) resolveCb();
330 }.bind(this)
331 );
332 }, this);
333 }.bind(this),
334 resolveCb
335 );
336
337 if (this.watch) {
338 test = function (path, newFiles, newDirs) {
339 var fullPath = rootPath + sep + path, promise;
340 if (
341 (!getDirs && this.pattern && !this.pattern.test(fullPath)) ||
342 (this.globalRules && applyGlobalRules(fullPath, this.globalRules))
343 ) {
344 return null;
345 }
346 promise = pLstat(fullPath).aside(
347 function (stat) {
348 var type = typeByStats(stat);
349 if (
350 newFiles &&
351 (!this.type || this.type[type]) &&
352 (!this.pattern || !getDirs || this.pattern.test(fullPath))
353 ) {
354 newFiles.push(path);
355 }
356 if (newDirs && type === "directory") newDirs.push(path);
357 }.bind(this)
358 );
359 return promise.catch(function (err) { if (err.code !== "ENOENT") throw err; });
360 }.bind(this);
361
362 paths.on("change", function (data) {
363 var removed, nFiles, nDirs;
364 if (data.added.length) {
365 nFiles = files && [];
366 nDirs = getDirs && [];
367 }
368 deferred
369 .map(data.added, function (path) { return test(path, nFiles, nDirs); })
370 .done(function () {
371 if (files) {
372 removed = data.removed.filter(contains, files);
373 if (removed.length || (nFiles && nFiles.length)) {
374 remove.apply(files, removed);
375 if (nFiles) push.apply(files, nFiles);
376 result.files.emit("change", {
377 data: files,
378 removed: removed,
379 added: nFiles || []
380 });
381 }
382 }
383 if (getDirs) {
384 removed = data.removed.filter(contains, dirs);
385 if (removed.length || (nDirs && nDirs.length)) {
386 remove.apply(dirs, removed);
387 if (nDirs) push.apply(dirs, nDirs);
388 result.dirs.emit("change", {
389 data: dirs,
390 removed: removed,
391 added: nDirs || []
392 });
393 }
394 }
395 });
396 });
397
398 paths.on("end", function (data, err) {
399 if (!resolved) {
400 if (defFiles) defFiles.reject(err);
401 if (defDirs) defDirs.reject(err);
402 return;
403 }
404 if (!failed) {
405 if (files) result.files.emit("end", files, err);
406 if (getDirs) result.dirs.emit("end", dirs, err);
407 }
408 });
409
410 close = function () {
411 if (defFiles && !defFiles.resolved) {
412 defFiles.reject(new Error("Readdir operation cancelled"));
413 }
414 if (defDirs && !defDirs.resolved) {
415 defDirs.reject(new Error("Readdir operation cancelled"));
416 }
417 if (paths.close) paths.close();
418 };
419
420 if (defFiles) {
421 result.files.close = close;
422 if (defDirs) result.dirs.close = noop;
423 } else {
424 result.dirs.close = close;
425 }
426 }
427 return result;
428 },
429 filterByPattern: function (paths) {
430 var promise
431 , result
432 , rootPath = paths.root
433 , pattern = this.pattern
434 , rules = this.globalRules
435 , filter;
436
437 filter = function (path) {
438 var fullPath = rootPath + sep + path;
439 return (
440 (!pattern || pattern.test(fullPath)) &&
441 (!rules || !applyGlobalRules(fullPath, rules))
442 );
443 };
444
445 promise = paths(function (data) { return (result = data.filter(filter)); });
446 promise.root = rootPath;
447 if (this.watch) {
448 paths.on("change", function (data) {
449 var removed, added;
450 removed = data.removed.filter(contains, result);
451 added = data.added.filter(filter);
452 if (removed.length || added.length) {
453 remove.apply(result, removed);
454 push.apply(result, added);
455 promise.emit("change", { data: result, removed: removed, added: added });
456 }
457 });
458 paths.on("end", function (data, err) { promise.emit("end", result, err); });
459 promise.close = function () { paths.close(); };
460 }
461 return promise;
462 },
463 filterIgnored: function (paths) {
464 var promise, result, test, rootPath = paths.root, promises, def = deferred();
465
466 promise = def.promise;
467 test = function (path, cb) {
468 var status = this.isIgnored(rootPath + sep + path);
469 if (this.watch) {
470 promises[path] = status;
471 status.on("change", function (value) {
472 if (value) {
473 remove.call(result, path);
474 promise.emit("change", { data: result, removed: [path], added: [] });
475 } else {
476 result.push(path);
477 promise.emit("change", { data: result, removed: [], added: [path] });
478 }
479 });
480 }
481 status.aside(cb);
482 }.bind(this);
483
484 if (this.watch) {
485 promises = {};
486
487 paths.on("change", function (data) {
488 var removed, added = [], waiting = data.added.length, onEnd;
489 data.removed.forEach(function (path) {
490 promises[path].close();
491 delete promises[path];
492 });
493 removed = data.removed.filter(contains, result);
494 onEnd = function () {
495 if (removed.length || added.length) {
496 remove.apply(result, removed);
497 push.apply(result, added);
498 promise.emit("change", { data: result, removed: removed, added: added });
499 }
500 };
501 if (!waiting) {
502 onEnd();
503 return;
504 }
505 data.added.forEach(function (path) {
506 test(path, function (lIsIgnored) {
507 if (!lIsIgnored) added.push(path);
508 if (!--waiting) onEnd();
509 });
510 });
511 });
512
513 paths.on("end", function (data, err) {
514 if (!promises) return;
515 forEach(promises, invoke("close"));
516 promises = null;
517 if (!def.resolved) {
518 def.reject(err);
519 return;
520 }
521 promise.emit("end", result, err);
522 });
523
524 promise.close = function () {
525 if (promises) {
526 if (!def.resolved) def.reject(new Error("Operation aborted"));
527 forEach(promises, invoke("close"));
528 promises = null;
529 paths.close();
530 }
531 };
532 }
533
534 paths.done(
535 function (newPaths) {
536 if (!newPaths) {
537 def.resolve(newPaths);
538 return;
539 }
540 var waiting = newPaths.length;
541 result = [];
542 if (!waiting) {
543 def.resolve(result);
544 return;
545 }
546 newPaths.forEach(function (path) {
547 test(path, function (lIsIgnored) {
548 if (!lIsIgnored) result.push(path);
549 if (!--waiting) def.resolve(result);
550 });
551 });
552 },
553 function (e) { def.reject(e); }
554 );
555 promise.root = rootPath;
556 return promise;
557 },
558 readdir: function (path) {
559 var def, promise, watcher, files;
560 def = deferred();
561 promise = def.promise;
562 promise.root = path;
563 if (this.watch) {
564 try { watcher = watchPath(path); }
565 catch (e) { return def.reject(e); }
566 watcher.on("end", function (err) {
567 if (!def.resolved) def.reject(err);
568 else if (files) promise.emit("end", files, err);
569 });
570 watcher.on("change", function () {
571 original(path, function (err, data) {
572 var removed, added;
573 if (err) {
574 promise.emit("end", files, err);
575 return;
576 }
577 removed = diff.call(files, data);
578 added = diff.call(data, files);
579 if (removed.length || added.length) {
580 remove.apply(files, removed);
581 push.apply(files, added);
582 promise.emit("change", { data: files, removed: removed, added: added });
583 }
584 });
585 });
586 promise.close = function () {
587 watcher.close();
588 if (!def.resolved) def.reject(new Error("Readdir action cancelled"));
589 };
590 }
591 original(
592 path,
593 function (err, data) {
594 if (err) {
595 if (this.loose && this.path === path && err.code === "ENOENT") {
596 def.resolve(null);
597 } else {
598 def.reject(err);
599 }
600 return;
601 }
602 def.resolve((files = data));
603 }.bind(this)
604 );
605 return promise;
606 }
607 };
608
609 readdir = function (path, options) {
610 var lReaddir, globalRules;
611
612 lReaddir = new Readdir();
613 lReaddir.path = path;
614 lReaddir.depth = isNaN(options.depth) ? 0 : toPosInt(options.depth);
615 lReaddir.type = isValue(options.type) ? Object(options.type) : null;
616 lReaddir.loose = Boolean(options.loose);
617 lReaddir.pattern = isValue(options.pattern) ? new RegExp(options.pattern) : null;
618 if (isValue(options.dirFilter)) {
619 if (typeof options.dirFilter === "function") lReaddir.dirFilter = options.dirFilter;
620 else lReaddir.dirFilter = RegExp.prototype.test.bind(new RegExp(options.dirFilter));
621 }
622 lReaddir.watch = options.watch;
623 lReaddir.stream = Boolean(options.stream);
624
625 if (options.globalRules) {
626 globalRules = isArray(options.globalRules)
627 ? options.globalRules
628 : String(options.globalRules).split(eolRe);
629 }
630 if (options.ignoreRules) {
631 assign(
632 lReaddir,
633 getIsIgnored(
634 isArray(options.ignoreRules) ? options.ignoreRules : [options.ignoreRules],
635 globalRules, options.watch
636 )
637 );
638 } else {
639 lReaddir.globalRules = globalRules;
640 }
641
642 return lReaddir.init();
643 };
644 readdir.returnsPromise = true;
645
646 module.exports = exports = function (path) {
647 var options, cb;
648 path = resolve(String(path));
649 options = Object(arguments[1]);
650 cb = arguments[2];
651 if (!isValue(cb) && isCallable(options)) {
652 cb = options;
653 options = {};
654 }
655
656 return readdir(path, options).cb(cb);
657 };
658 exports.returnsPromise = true;
659 exports.readdir = readdir;