UNPKG

2.62 kBJavaScriptView Raw
1// vendored from https://github.com/amasad/sane/blob/64ff3a870c42e84f744086884bf55a4f9c22d376/src/common.js
2'use strict';
3
4const platform = require('os').platform();
5
6const path = require('path');
7
8const anymatch = require('anymatch');
9
10const micromatch = require('micromatch');
11
12const walker = require('walker');
13/**
14 * Constants
15 */
16
17exports.DEFAULT_DELAY = 100;
18exports.CHANGE_EVENT = 'change';
19exports.DELETE_EVENT = 'delete';
20exports.ADD_EVENT = 'add';
21exports.ALL_EVENT = 'all';
22/**
23 * Assigns options to the watcher.
24 *
25 * @param {NodeWatcher|PollWatcher|WatchmanWatcher} watcher
26 * @param {?object} opts
27 * @return {boolean}
28 * @public
29 */
30
31exports.assignOptions = function (watcher, opts) {
32 opts = opts || {};
33 watcher.globs = opts.glob || [];
34 watcher.dot = opts.dot || false;
35 watcher.ignored = opts.ignored || false;
36
37 if (!Array.isArray(watcher.globs)) {
38 watcher.globs = [watcher.globs];
39 }
40
41 watcher.hasIgnore =
42 Boolean(opts.ignored) && !(Array.isArray(opts) && opts.length > 0);
43 watcher.doIgnore = opts.ignored ? anymatch(opts.ignored) : () => false;
44
45 if (opts.watchman && opts.watchmanPath) {
46 watcher.watchmanPath = opts.watchmanPath;
47 }
48
49 return opts;
50};
51/**
52 * Checks a file relative path against the globs array.
53 *
54 * @param {array} globs
55 * @param {string} relativePath
56 * @return {boolean}
57 * @public
58 */
59
60exports.isFileIncluded = function (globs, dot, doIgnore, relativePath) {
61 if (doIgnore(relativePath)) {
62 return false;
63 }
64
65 return globs.length
66 ? micromatch.some(relativePath, globs, {
67 dot
68 })
69 : dot || micromatch.some(relativePath, '**/*');
70};
71/**
72 * Traverse a directory recursively calling `callback` on every directory.
73 *
74 * @param {string} dir
75 * @param {function} dirCallback
76 * @param {function} fileCallback
77 * @param {function} endCallback
78 * @param {*} ignored
79 * @public
80 */
81
82exports.recReaddir = function (
83 dir,
84 dirCallback,
85 fileCallback,
86 endCallback,
87 errorCallback,
88 ignored
89) {
90 walker(dir)
91 .filterDir(currentDir => !anymatch(ignored, currentDir))
92 .on('dir', normalizeProxy(dirCallback))
93 .on('file', normalizeProxy(fileCallback))
94 .on('error', errorCallback)
95 .on('end', () => {
96 if (platform === 'win32') {
97 setTimeout(endCallback, 1000);
98 } else {
99 endCallback();
100 }
101 });
102};
103/**
104 * Returns a callback that when called will normalize a path and call the
105 * original callback
106 *
107 * @param {function} callback
108 * @return {function}
109 * @private
110 */
111
112function normalizeProxy(callback) {
113 return (filepath, stats) => callback(path.normalize(filepath), stats);
114}