[0c6b92a] | 1 | import { watchFile, unwatchFile, watch as fs_watch } from 'fs';
|
---|
| 2 | import { open, stat, lstat, realpath as fsrealpath } from 'fs/promises';
|
---|
| 3 | import * as sysPath from 'path';
|
---|
| 4 | import { type as osType } from 'os';
|
---|
| 5 | export const STR_DATA = 'data';
|
---|
| 6 | export const STR_END = 'end';
|
---|
| 7 | export const STR_CLOSE = 'close';
|
---|
| 8 | export const EMPTY_FN = () => { };
|
---|
| 9 | export const IDENTITY_FN = (val) => val;
|
---|
| 10 | const pl = process.platform;
|
---|
| 11 | export const isWindows = pl === 'win32';
|
---|
| 12 | export const isMacos = pl === 'darwin';
|
---|
| 13 | export const isLinux = pl === 'linux';
|
---|
| 14 | export const isIBMi = osType() === 'OS400';
|
---|
| 15 | export const EVENTS = {
|
---|
| 16 | ALL: 'all',
|
---|
| 17 | READY: 'ready',
|
---|
| 18 | ADD: 'add',
|
---|
| 19 | CHANGE: 'change',
|
---|
| 20 | ADD_DIR: 'addDir',
|
---|
| 21 | UNLINK: 'unlink',
|
---|
| 22 | UNLINK_DIR: 'unlinkDir',
|
---|
| 23 | RAW: 'raw',
|
---|
| 24 | ERROR: 'error',
|
---|
| 25 | };
|
---|
| 26 | const EV = EVENTS;
|
---|
| 27 | const THROTTLE_MODE_WATCH = 'watch';
|
---|
| 28 | const statMethods = { lstat, stat };
|
---|
| 29 | const KEY_LISTENERS = 'listeners';
|
---|
| 30 | const KEY_ERR = 'errHandlers';
|
---|
| 31 | const KEY_RAW = 'rawEmitters';
|
---|
| 32 | const HANDLER_KEYS = [KEY_LISTENERS, KEY_ERR, KEY_RAW];
|
---|
| 33 | // prettier-ignore
|
---|
| 34 | const binaryExtensions = new Set([
|
---|
| 35 | '3dm', '3ds', '3g2', '3gp', '7z', 'a', 'aac', 'adp', 'afdesign', 'afphoto', 'afpub', 'ai',
|
---|
| 36 | 'aif', 'aiff', 'alz', 'ape', 'apk', 'appimage', 'ar', 'arj', 'asf', 'au', 'avi',
|
---|
| 37 | 'bak', 'baml', 'bh', 'bin', 'bk', 'bmp', 'btif', 'bz2', 'bzip2',
|
---|
| 38 | 'cab', 'caf', 'cgm', 'class', 'cmx', 'cpio', 'cr2', 'cur', 'dat', 'dcm', 'deb', 'dex', 'djvu',
|
---|
| 39 | 'dll', 'dmg', 'dng', 'doc', 'docm', 'docx', 'dot', 'dotm', 'dra', 'DS_Store', 'dsk', 'dts',
|
---|
| 40 | 'dtshd', 'dvb', 'dwg', 'dxf',
|
---|
| 41 | 'ecelp4800', 'ecelp7470', 'ecelp9600', 'egg', 'eol', 'eot', 'epub', 'exe',
|
---|
| 42 | 'f4v', 'fbs', 'fh', 'fla', 'flac', 'flatpak', 'fli', 'flv', 'fpx', 'fst', 'fvt',
|
---|
| 43 | 'g3', 'gh', 'gif', 'graffle', 'gz', 'gzip',
|
---|
| 44 | 'h261', 'h263', 'h264', 'icns', 'ico', 'ief', 'img', 'ipa', 'iso',
|
---|
| 45 | 'jar', 'jpeg', 'jpg', 'jpgv', 'jpm', 'jxr', 'key', 'ktx',
|
---|
| 46 | 'lha', 'lib', 'lvp', 'lz', 'lzh', 'lzma', 'lzo',
|
---|
| 47 | 'm3u', 'm4a', 'm4v', 'mar', 'mdi', 'mht', 'mid', 'midi', 'mj2', 'mka', 'mkv', 'mmr', 'mng',
|
---|
| 48 | 'mobi', 'mov', 'movie', 'mp3',
|
---|
| 49 | 'mp4', 'mp4a', 'mpeg', 'mpg', 'mpga', 'mxu',
|
---|
| 50 | 'nef', 'npx', 'numbers', 'nupkg',
|
---|
| 51 | 'o', 'odp', 'ods', 'odt', 'oga', 'ogg', 'ogv', 'otf', 'ott',
|
---|
| 52 | 'pages', 'pbm', 'pcx', 'pdb', 'pdf', 'pea', 'pgm', 'pic', 'png', 'pnm', 'pot', 'potm',
|
---|
| 53 | 'potx', 'ppa', 'ppam',
|
---|
| 54 | 'ppm', 'pps', 'ppsm', 'ppsx', 'ppt', 'pptm', 'pptx', 'psd', 'pya', 'pyc', 'pyo', 'pyv',
|
---|
| 55 | 'qt',
|
---|
| 56 | 'rar', 'ras', 'raw', 'resources', 'rgb', 'rip', 'rlc', 'rmf', 'rmvb', 'rpm', 'rtf', 'rz',
|
---|
| 57 | 's3m', 's7z', 'scpt', 'sgi', 'shar', 'snap', 'sil', 'sketch', 'slk', 'smv', 'snk', 'so',
|
---|
| 58 | 'stl', 'suo', 'sub', 'swf',
|
---|
| 59 | 'tar', 'tbz', 'tbz2', 'tga', 'tgz', 'thmx', 'tif', 'tiff', 'tlz', 'ttc', 'ttf', 'txz',
|
---|
| 60 | 'udf', 'uvh', 'uvi', 'uvm', 'uvp', 'uvs', 'uvu',
|
---|
| 61 | 'viv', 'vob',
|
---|
| 62 | 'war', 'wav', 'wax', 'wbmp', 'wdp', 'weba', 'webm', 'webp', 'whl', 'wim', 'wm', 'wma',
|
---|
| 63 | 'wmv', 'wmx', 'woff', 'woff2', 'wrm', 'wvx',
|
---|
| 64 | 'xbm', 'xif', 'xla', 'xlam', 'xls', 'xlsb', 'xlsm', 'xlsx', 'xlt', 'xltm', 'xltx', 'xm',
|
---|
| 65 | 'xmind', 'xpi', 'xpm', 'xwd', 'xz',
|
---|
| 66 | 'z', 'zip', 'zipx',
|
---|
| 67 | ]);
|
---|
| 68 | const isBinaryPath = (filePath) => binaryExtensions.has(sysPath.extname(filePath).slice(1).toLowerCase());
|
---|
| 69 | // TODO: emit errors properly. Example: EMFILE on Macos.
|
---|
| 70 | const foreach = (val, fn) => {
|
---|
| 71 | if (val instanceof Set) {
|
---|
| 72 | val.forEach(fn);
|
---|
| 73 | }
|
---|
| 74 | else {
|
---|
| 75 | fn(val);
|
---|
| 76 | }
|
---|
| 77 | };
|
---|
| 78 | const addAndConvert = (main, prop, item) => {
|
---|
| 79 | let container = main[prop];
|
---|
| 80 | if (!(container instanceof Set)) {
|
---|
| 81 | main[prop] = container = new Set([container]);
|
---|
| 82 | }
|
---|
| 83 | container.add(item);
|
---|
| 84 | };
|
---|
| 85 | const clearItem = (cont) => (key) => {
|
---|
| 86 | const set = cont[key];
|
---|
| 87 | if (set instanceof Set) {
|
---|
| 88 | set.clear();
|
---|
| 89 | }
|
---|
| 90 | else {
|
---|
| 91 | delete cont[key];
|
---|
| 92 | }
|
---|
| 93 | };
|
---|
| 94 | const delFromSet = (main, prop, item) => {
|
---|
| 95 | const container = main[prop];
|
---|
| 96 | if (container instanceof Set) {
|
---|
| 97 | container.delete(item);
|
---|
| 98 | }
|
---|
| 99 | else if (container === item) {
|
---|
| 100 | delete main[prop];
|
---|
| 101 | }
|
---|
| 102 | };
|
---|
| 103 | const isEmptySet = (val) => (val instanceof Set ? val.size === 0 : !val);
|
---|
| 104 | const FsWatchInstances = new Map();
|
---|
| 105 | /**
|
---|
| 106 | * Instantiates the fs_watch interface
|
---|
| 107 | * @param path to be watched
|
---|
| 108 | * @param options to be passed to fs_watch
|
---|
| 109 | * @param listener main event handler
|
---|
| 110 | * @param errHandler emits info about errors
|
---|
| 111 | * @param emitRaw emits raw event data
|
---|
| 112 | * @returns {NativeFsWatcher}
|
---|
| 113 | */
|
---|
| 114 | function createFsWatchInstance(path, options, listener, errHandler, emitRaw) {
|
---|
| 115 | const handleEvent = (rawEvent, evPath) => {
|
---|
| 116 | listener(path);
|
---|
| 117 | emitRaw(rawEvent, evPath, { watchedPath: path });
|
---|
| 118 | // emit based on events occurring for files from a directory's watcher in
|
---|
| 119 | // case the file's watcher misses it (and rely on throttling to de-dupe)
|
---|
| 120 | if (evPath && path !== evPath) {
|
---|
| 121 | fsWatchBroadcast(sysPath.resolve(path, evPath), KEY_LISTENERS, sysPath.join(path, evPath));
|
---|
| 122 | }
|
---|
| 123 | };
|
---|
| 124 | try {
|
---|
| 125 | return fs_watch(path, {
|
---|
| 126 | persistent: options.persistent,
|
---|
| 127 | }, handleEvent);
|
---|
| 128 | }
|
---|
| 129 | catch (error) {
|
---|
| 130 | errHandler(error);
|
---|
| 131 | return undefined;
|
---|
| 132 | }
|
---|
| 133 | }
|
---|
| 134 | /**
|
---|
| 135 | * Helper for passing fs_watch event data to a collection of listeners
|
---|
| 136 | * @param fullPath absolute path bound to fs_watch instance
|
---|
| 137 | */
|
---|
| 138 | const fsWatchBroadcast = (fullPath, listenerType, val1, val2, val3) => {
|
---|
| 139 | const cont = FsWatchInstances.get(fullPath);
|
---|
| 140 | if (!cont)
|
---|
| 141 | return;
|
---|
| 142 | foreach(cont[listenerType], (listener) => {
|
---|
| 143 | listener(val1, val2, val3);
|
---|
| 144 | });
|
---|
| 145 | };
|
---|
| 146 | /**
|
---|
| 147 | * Instantiates the fs_watch interface or binds listeners
|
---|
| 148 | * to an existing one covering the same file system entry
|
---|
| 149 | * @param path
|
---|
| 150 | * @param fullPath absolute path
|
---|
| 151 | * @param options to be passed to fs_watch
|
---|
| 152 | * @param handlers container for event listener functions
|
---|
| 153 | */
|
---|
| 154 | const setFsWatchListener = (path, fullPath, options, handlers) => {
|
---|
| 155 | const { listener, errHandler, rawEmitter } = handlers;
|
---|
| 156 | let cont = FsWatchInstances.get(fullPath);
|
---|
| 157 | let watcher;
|
---|
| 158 | if (!options.persistent) {
|
---|
| 159 | watcher = createFsWatchInstance(path, options, listener, errHandler, rawEmitter);
|
---|
| 160 | if (!watcher)
|
---|
| 161 | return;
|
---|
| 162 | return watcher.close.bind(watcher);
|
---|
| 163 | }
|
---|
| 164 | if (cont) {
|
---|
| 165 | addAndConvert(cont, KEY_LISTENERS, listener);
|
---|
| 166 | addAndConvert(cont, KEY_ERR, errHandler);
|
---|
| 167 | addAndConvert(cont, KEY_RAW, rawEmitter);
|
---|
| 168 | }
|
---|
| 169 | else {
|
---|
| 170 | watcher = createFsWatchInstance(path, options, fsWatchBroadcast.bind(null, fullPath, KEY_LISTENERS), errHandler, // no need to use broadcast here
|
---|
| 171 | fsWatchBroadcast.bind(null, fullPath, KEY_RAW));
|
---|
| 172 | if (!watcher)
|
---|
| 173 | return;
|
---|
| 174 | watcher.on(EV.ERROR, async (error) => {
|
---|
| 175 | const broadcastErr = fsWatchBroadcast.bind(null, fullPath, KEY_ERR);
|
---|
| 176 | if (cont)
|
---|
| 177 | cont.watcherUnusable = true; // documented since Node 10.4.1
|
---|
| 178 | // Workaround for https://github.com/joyent/node/issues/4337
|
---|
| 179 | if (isWindows && error.code === 'EPERM') {
|
---|
| 180 | try {
|
---|
| 181 | const fd = await open(path, 'r');
|
---|
| 182 | await fd.close();
|
---|
| 183 | broadcastErr(error);
|
---|
| 184 | }
|
---|
| 185 | catch (err) {
|
---|
| 186 | // do nothing
|
---|
| 187 | }
|
---|
| 188 | }
|
---|
| 189 | else {
|
---|
| 190 | broadcastErr(error);
|
---|
| 191 | }
|
---|
| 192 | });
|
---|
| 193 | cont = {
|
---|
| 194 | listeners: listener,
|
---|
| 195 | errHandlers: errHandler,
|
---|
| 196 | rawEmitters: rawEmitter,
|
---|
| 197 | watcher,
|
---|
| 198 | };
|
---|
| 199 | FsWatchInstances.set(fullPath, cont);
|
---|
| 200 | }
|
---|
| 201 | // const index = cont.listeners.indexOf(listener);
|
---|
| 202 | // removes this instance's listeners and closes the underlying fs_watch
|
---|
| 203 | // instance if there are no more listeners left
|
---|
| 204 | return () => {
|
---|
| 205 | delFromSet(cont, KEY_LISTENERS, listener);
|
---|
| 206 | delFromSet(cont, KEY_ERR, errHandler);
|
---|
| 207 | delFromSet(cont, KEY_RAW, rawEmitter);
|
---|
| 208 | if (isEmptySet(cont.listeners)) {
|
---|
| 209 | // Check to protect against issue gh-730.
|
---|
| 210 | // if (cont.watcherUnusable) {
|
---|
| 211 | cont.watcher.close();
|
---|
| 212 | // }
|
---|
| 213 | FsWatchInstances.delete(fullPath);
|
---|
| 214 | HANDLER_KEYS.forEach(clearItem(cont));
|
---|
| 215 | // @ts-ignore
|
---|
| 216 | cont.watcher = undefined;
|
---|
| 217 | Object.freeze(cont);
|
---|
| 218 | }
|
---|
| 219 | };
|
---|
| 220 | };
|
---|
| 221 | // fs_watchFile helpers
|
---|
| 222 | // object to hold per-process fs_watchFile instances
|
---|
| 223 | // (may be shared across chokidar FSWatcher instances)
|
---|
| 224 | const FsWatchFileInstances = new Map();
|
---|
| 225 | /**
|
---|
| 226 | * Instantiates the fs_watchFile interface or binds listeners
|
---|
| 227 | * to an existing one covering the same file system entry
|
---|
| 228 | * @param path to be watched
|
---|
| 229 | * @param fullPath absolute path
|
---|
| 230 | * @param options options to be passed to fs_watchFile
|
---|
| 231 | * @param handlers container for event listener functions
|
---|
| 232 | * @returns closer
|
---|
| 233 | */
|
---|
| 234 | const setFsWatchFileListener = (path, fullPath, options, handlers) => {
|
---|
| 235 | const { listener, rawEmitter } = handlers;
|
---|
| 236 | let cont = FsWatchFileInstances.get(fullPath);
|
---|
| 237 | // let listeners = new Set();
|
---|
| 238 | // let rawEmitters = new Set();
|
---|
| 239 | const copts = cont && cont.options;
|
---|
| 240 | if (copts && (copts.persistent < options.persistent || copts.interval > options.interval)) {
|
---|
| 241 | // "Upgrade" the watcher to persistence or a quicker interval.
|
---|
| 242 | // This creates some unlikely edge case issues if the user mixes
|
---|
| 243 | // settings in a very weird way, but solving for those cases
|
---|
| 244 | // doesn't seem worthwhile for the added complexity.
|
---|
| 245 | // listeners = cont.listeners;
|
---|
| 246 | // rawEmitters = cont.rawEmitters;
|
---|
| 247 | unwatchFile(fullPath);
|
---|
| 248 | cont = undefined;
|
---|
| 249 | }
|
---|
| 250 | if (cont) {
|
---|
| 251 | addAndConvert(cont, KEY_LISTENERS, listener);
|
---|
| 252 | addAndConvert(cont, KEY_RAW, rawEmitter);
|
---|
| 253 | }
|
---|
| 254 | else {
|
---|
| 255 | // TODO
|
---|
| 256 | // listeners.add(listener);
|
---|
| 257 | // rawEmitters.add(rawEmitter);
|
---|
| 258 | cont = {
|
---|
| 259 | listeners: listener,
|
---|
| 260 | rawEmitters: rawEmitter,
|
---|
| 261 | options,
|
---|
| 262 | watcher: watchFile(fullPath, options, (curr, prev) => {
|
---|
| 263 | foreach(cont.rawEmitters, (rawEmitter) => {
|
---|
| 264 | rawEmitter(EV.CHANGE, fullPath, { curr, prev });
|
---|
| 265 | });
|
---|
| 266 | const currmtime = curr.mtimeMs;
|
---|
| 267 | if (curr.size !== prev.size || currmtime > prev.mtimeMs || currmtime === 0) {
|
---|
| 268 | foreach(cont.listeners, (listener) => listener(path, curr));
|
---|
| 269 | }
|
---|
| 270 | }),
|
---|
| 271 | };
|
---|
| 272 | FsWatchFileInstances.set(fullPath, cont);
|
---|
| 273 | }
|
---|
| 274 | // const index = cont.listeners.indexOf(listener);
|
---|
| 275 | // Removes this instance's listeners and closes the underlying fs_watchFile
|
---|
| 276 | // instance if there are no more listeners left.
|
---|
| 277 | return () => {
|
---|
| 278 | delFromSet(cont, KEY_LISTENERS, listener);
|
---|
| 279 | delFromSet(cont, KEY_RAW, rawEmitter);
|
---|
| 280 | if (isEmptySet(cont.listeners)) {
|
---|
| 281 | FsWatchFileInstances.delete(fullPath);
|
---|
| 282 | unwatchFile(fullPath);
|
---|
| 283 | cont.options = cont.watcher = undefined;
|
---|
| 284 | Object.freeze(cont);
|
---|
| 285 | }
|
---|
| 286 | };
|
---|
| 287 | };
|
---|
| 288 | /**
|
---|
| 289 | * @mixin
|
---|
| 290 | */
|
---|
| 291 | export class NodeFsHandler {
|
---|
| 292 | constructor(fsW) {
|
---|
| 293 | this.fsw = fsW;
|
---|
| 294 | this._boundHandleError = (error) => fsW._handleError(error);
|
---|
| 295 | }
|
---|
| 296 | /**
|
---|
| 297 | * Watch file for changes with fs_watchFile or fs_watch.
|
---|
| 298 | * @param path to file or dir
|
---|
| 299 | * @param listener on fs change
|
---|
| 300 | * @returns closer for the watcher instance
|
---|
| 301 | */
|
---|
| 302 | _watchWithNodeFs(path, listener) {
|
---|
| 303 | const opts = this.fsw.options;
|
---|
| 304 | const directory = sysPath.dirname(path);
|
---|
| 305 | const basename = sysPath.basename(path);
|
---|
| 306 | const parent = this.fsw._getWatchedDir(directory);
|
---|
| 307 | parent.add(basename);
|
---|
| 308 | const absolutePath = sysPath.resolve(path);
|
---|
| 309 | const options = {
|
---|
| 310 | persistent: opts.persistent,
|
---|
| 311 | };
|
---|
| 312 | if (!listener)
|
---|
| 313 | listener = EMPTY_FN;
|
---|
| 314 | let closer;
|
---|
| 315 | if (opts.usePolling) {
|
---|
| 316 | const enableBin = opts.interval !== opts.binaryInterval;
|
---|
| 317 | options.interval = enableBin && isBinaryPath(basename) ? opts.binaryInterval : opts.interval;
|
---|
| 318 | closer = setFsWatchFileListener(path, absolutePath, options, {
|
---|
| 319 | listener,
|
---|
| 320 | rawEmitter: this.fsw._emitRaw,
|
---|
| 321 | });
|
---|
| 322 | }
|
---|
| 323 | else {
|
---|
| 324 | closer = setFsWatchListener(path, absolutePath, options, {
|
---|
| 325 | listener,
|
---|
| 326 | errHandler: this._boundHandleError,
|
---|
| 327 | rawEmitter: this.fsw._emitRaw,
|
---|
| 328 | });
|
---|
| 329 | }
|
---|
| 330 | return closer;
|
---|
| 331 | }
|
---|
| 332 | /**
|
---|
| 333 | * Watch a file and emit add event if warranted.
|
---|
| 334 | * @returns closer for the watcher instance
|
---|
| 335 | */
|
---|
| 336 | _handleFile(file, stats, initialAdd) {
|
---|
| 337 | if (this.fsw.closed) {
|
---|
| 338 | return;
|
---|
| 339 | }
|
---|
| 340 | const dirname = sysPath.dirname(file);
|
---|
| 341 | const basename = sysPath.basename(file);
|
---|
| 342 | const parent = this.fsw._getWatchedDir(dirname);
|
---|
| 343 | // stats is always present
|
---|
| 344 | let prevStats = stats;
|
---|
| 345 | // if the file is already being watched, do nothing
|
---|
| 346 | if (parent.has(basename))
|
---|
| 347 | return;
|
---|
| 348 | const listener = async (path, newStats) => {
|
---|
| 349 | if (!this.fsw._throttle(THROTTLE_MODE_WATCH, file, 5))
|
---|
| 350 | return;
|
---|
| 351 | if (!newStats || newStats.mtimeMs === 0) {
|
---|
| 352 | try {
|
---|
| 353 | const newStats = await stat(file);
|
---|
| 354 | if (this.fsw.closed)
|
---|
| 355 | return;
|
---|
| 356 | // Check that change event was not fired because of changed only accessTime.
|
---|
| 357 | const at = newStats.atimeMs;
|
---|
| 358 | const mt = newStats.mtimeMs;
|
---|
| 359 | if (!at || at <= mt || mt !== prevStats.mtimeMs) {
|
---|
| 360 | this.fsw._emit(EV.CHANGE, file, newStats);
|
---|
| 361 | }
|
---|
| 362 | if ((isMacos || isLinux) && prevStats.ino !== newStats.ino) {
|
---|
| 363 | this.fsw._closeFile(path);
|
---|
| 364 | prevStats = newStats;
|
---|
| 365 | const closer = this._watchWithNodeFs(file, listener);
|
---|
| 366 | if (closer)
|
---|
| 367 | this.fsw._addPathCloser(path, closer);
|
---|
| 368 | }
|
---|
| 369 | else {
|
---|
| 370 | prevStats = newStats;
|
---|
| 371 | }
|
---|
| 372 | }
|
---|
| 373 | catch (error) {
|
---|
| 374 | // Fix issues where mtime is null but file is still present
|
---|
| 375 | this.fsw._remove(dirname, basename);
|
---|
| 376 | }
|
---|
| 377 | // add is about to be emitted if file not already tracked in parent
|
---|
| 378 | }
|
---|
| 379 | else if (parent.has(basename)) {
|
---|
| 380 | // Check that change event was not fired because of changed only accessTime.
|
---|
| 381 | const at = newStats.atimeMs;
|
---|
| 382 | const mt = newStats.mtimeMs;
|
---|
| 383 | if (!at || at <= mt || mt !== prevStats.mtimeMs) {
|
---|
| 384 | this.fsw._emit(EV.CHANGE, file, newStats);
|
---|
| 385 | }
|
---|
| 386 | prevStats = newStats;
|
---|
| 387 | }
|
---|
| 388 | };
|
---|
| 389 | // kick off the watcher
|
---|
| 390 | const closer = this._watchWithNodeFs(file, listener);
|
---|
| 391 | // emit an add event if we're supposed to
|
---|
| 392 | if (!(initialAdd && this.fsw.options.ignoreInitial) && this.fsw._isntIgnored(file)) {
|
---|
| 393 | if (!this.fsw._throttle(EV.ADD, file, 0))
|
---|
| 394 | return;
|
---|
| 395 | this.fsw._emit(EV.ADD, file, stats);
|
---|
| 396 | }
|
---|
| 397 | return closer;
|
---|
| 398 | }
|
---|
| 399 | /**
|
---|
| 400 | * Handle symlinks encountered while reading a dir.
|
---|
| 401 | * @param entry returned by readdirp
|
---|
| 402 | * @param directory path of dir being read
|
---|
| 403 | * @param path of this item
|
---|
| 404 | * @param item basename of this item
|
---|
| 405 | * @returns true if no more processing is needed for this entry.
|
---|
| 406 | */
|
---|
| 407 | async _handleSymlink(entry, directory, path, item) {
|
---|
| 408 | if (this.fsw.closed) {
|
---|
| 409 | return;
|
---|
| 410 | }
|
---|
| 411 | const full = entry.fullPath;
|
---|
| 412 | const dir = this.fsw._getWatchedDir(directory);
|
---|
| 413 | if (!this.fsw.options.followSymlinks) {
|
---|
| 414 | // watch symlink directly (don't follow) and detect changes
|
---|
| 415 | this.fsw._incrReadyCount();
|
---|
| 416 | let linkPath;
|
---|
| 417 | try {
|
---|
| 418 | linkPath = await fsrealpath(path);
|
---|
| 419 | }
|
---|
| 420 | catch (e) {
|
---|
| 421 | this.fsw._emitReady();
|
---|
| 422 | return true;
|
---|
| 423 | }
|
---|
| 424 | if (this.fsw.closed)
|
---|
| 425 | return;
|
---|
| 426 | if (dir.has(item)) {
|
---|
| 427 | if (this.fsw._symlinkPaths.get(full) !== linkPath) {
|
---|
| 428 | this.fsw._symlinkPaths.set(full, linkPath);
|
---|
| 429 | this.fsw._emit(EV.CHANGE, path, entry.stats);
|
---|
| 430 | }
|
---|
| 431 | }
|
---|
| 432 | else {
|
---|
| 433 | dir.add(item);
|
---|
| 434 | this.fsw._symlinkPaths.set(full, linkPath);
|
---|
| 435 | this.fsw._emit(EV.ADD, path, entry.stats);
|
---|
| 436 | }
|
---|
| 437 | this.fsw._emitReady();
|
---|
| 438 | return true;
|
---|
| 439 | }
|
---|
| 440 | // don't follow the same symlink more than once
|
---|
| 441 | if (this.fsw._symlinkPaths.has(full)) {
|
---|
| 442 | return true;
|
---|
| 443 | }
|
---|
| 444 | this.fsw._symlinkPaths.set(full, true);
|
---|
| 445 | }
|
---|
| 446 | _handleRead(directory, initialAdd, wh, target, dir, depth, throttler) {
|
---|
| 447 | // Normalize the directory name on Windows
|
---|
| 448 | directory = sysPath.join(directory, '');
|
---|
| 449 | throttler = this.fsw._throttle('readdir', directory, 1000);
|
---|
| 450 | if (!throttler)
|
---|
| 451 | return;
|
---|
| 452 | const previous = this.fsw._getWatchedDir(wh.path);
|
---|
| 453 | const current = new Set();
|
---|
| 454 | let stream = this.fsw._readdirp(directory, {
|
---|
| 455 | fileFilter: (entry) => wh.filterPath(entry),
|
---|
| 456 | directoryFilter: (entry) => wh.filterDir(entry),
|
---|
| 457 | });
|
---|
| 458 | if (!stream)
|
---|
| 459 | return;
|
---|
| 460 | stream
|
---|
| 461 | .on(STR_DATA, async (entry) => {
|
---|
| 462 | if (this.fsw.closed) {
|
---|
| 463 | stream = undefined;
|
---|
| 464 | return;
|
---|
| 465 | }
|
---|
| 466 | const item = entry.path;
|
---|
| 467 | let path = sysPath.join(directory, item);
|
---|
| 468 | current.add(item);
|
---|
| 469 | if (entry.stats.isSymbolicLink() &&
|
---|
| 470 | (await this._handleSymlink(entry, directory, path, item))) {
|
---|
| 471 | return;
|
---|
| 472 | }
|
---|
| 473 | if (this.fsw.closed) {
|
---|
| 474 | stream = undefined;
|
---|
| 475 | return;
|
---|
| 476 | }
|
---|
| 477 | // Files that present in current directory snapshot
|
---|
| 478 | // but absent in previous are added to watch list and
|
---|
| 479 | // emit `add` event.
|
---|
| 480 | if (item === target || (!target && !previous.has(item))) {
|
---|
| 481 | this.fsw._incrReadyCount();
|
---|
| 482 | // ensure relativeness of path is preserved in case of watcher reuse
|
---|
| 483 | path = sysPath.join(dir, sysPath.relative(dir, path));
|
---|
| 484 | this._addToNodeFs(path, initialAdd, wh, depth + 1);
|
---|
| 485 | }
|
---|
| 486 | })
|
---|
| 487 | .on(EV.ERROR, this._boundHandleError);
|
---|
| 488 | return new Promise((resolve, reject) => {
|
---|
| 489 | if (!stream)
|
---|
| 490 | return reject();
|
---|
| 491 | stream.once(STR_END, () => {
|
---|
| 492 | if (this.fsw.closed) {
|
---|
| 493 | stream = undefined;
|
---|
| 494 | return;
|
---|
| 495 | }
|
---|
| 496 | const wasThrottled = throttler ? throttler.clear() : false;
|
---|
| 497 | resolve(undefined);
|
---|
| 498 | // Files that absent in current directory snapshot
|
---|
| 499 | // but present in previous emit `remove` event
|
---|
| 500 | // and are removed from @watched[directory].
|
---|
| 501 | previous
|
---|
| 502 | .getChildren()
|
---|
| 503 | .filter((item) => {
|
---|
| 504 | return item !== directory && !current.has(item);
|
---|
| 505 | })
|
---|
| 506 | .forEach((item) => {
|
---|
| 507 | this.fsw._remove(directory, item);
|
---|
| 508 | });
|
---|
| 509 | stream = undefined;
|
---|
| 510 | // one more time for any missed in case changes came in extremely quickly
|
---|
| 511 | if (wasThrottled)
|
---|
| 512 | this._handleRead(directory, false, wh, target, dir, depth, throttler);
|
---|
| 513 | });
|
---|
| 514 | });
|
---|
| 515 | }
|
---|
| 516 | /**
|
---|
| 517 | * Read directory to add / remove files from `@watched` list and re-read it on change.
|
---|
| 518 | * @param dir fs path
|
---|
| 519 | * @param stats
|
---|
| 520 | * @param initialAdd
|
---|
| 521 | * @param depth relative to user-supplied path
|
---|
| 522 | * @param target child path targeted for watch
|
---|
| 523 | * @param wh Common watch helpers for this path
|
---|
| 524 | * @param realpath
|
---|
| 525 | * @returns closer for the watcher instance.
|
---|
| 526 | */
|
---|
| 527 | async _handleDir(dir, stats, initialAdd, depth, target, wh, realpath) {
|
---|
| 528 | const parentDir = this.fsw._getWatchedDir(sysPath.dirname(dir));
|
---|
| 529 | const tracked = parentDir.has(sysPath.basename(dir));
|
---|
| 530 | if (!(initialAdd && this.fsw.options.ignoreInitial) && !target && !tracked) {
|
---|
| 531 | this.fsw._emit(EV.ADD_DIR, dir, stats);
|
---|
| 532 | }
|
---|
| 533 | // ensure dir is tracked (harmless if redundant)
|
---|
| 534 | parentDir.add(sysPath.basename(dir));
|
---|
| 535 | this.fsw._getWatchedDir(dir);
|
---|
| 536 | let throttler;
|
---|
| 537 | let closer;
|
---|
| 538 | const oDepth = this.fsw.options.depth;
|
---|
| 539 | if ((oDepth == null || depth <= oDepth) && !this.fsw._symlinkPaths.has(realpath)) {
|
---|
| 540 | if (!target) {
|
---|
| 541 | await this._handleRead(dir, initialAdd, wh, target, dir, depth, throttler);
|
---|
| 542 | if (this.fsw.closed)
|
---|
| 543 | return;
|
---|
| 544 | }
|
---|
| 545 | closer = this._watchWithNodeFs(dir, (dirPath, stats) => {
|
---|
| 546 | // if current directory is removed, do nothing
|
---|
| 547 | if (stats && stats.mtimeMs === 0)
|
---|
| 548 | return;
|
---|
| 549 | this._handleRead(dirPath, false, wh, target, dir, depth, throttler);
|
---|
| 550 | });
|
---|
| 551 | }
|
---|
| 552 | return closer;
|
---|
| 553 | }
|
---|
| 554 | /**
|
---|
| 555 | * Handle added file, directory, or glob pattern.
|
---|
| 556 | * Delegates call to _handleFile / _handleDir after checks.
|
---|
| 557 | * @param path to file or ir
|
---|
| 558 | * @param initialAdd was the file added at watch instantiation?
|
---|
| 559 | * @param priorWh depth relative to user-supplied path
|
---|
| 560 | * @param depth Child path actually targeted for watch
|
---|
| 561 | * @param target Child path actually targeted for watch
|
---|
| 562 | */
|
---|
| 563 | async _addToNodeFs(path, initialAdd, priorWh, depth, target) {
|
---|
| 564 | const ready = this.fsw._emitReady;
|
---|
| 565 | if (this.fsw._isIgnored(path) || this.fsw.closed) {
|
---|
| 566 | ready();
|
---|
| 567 | return false;
|
---|
| 568 | }
|
---|
| 569 | const wh = this.fsw._getWatchHelpers(path);
|
---|
| 570 | if (priorWh) {
|
---|
| 571 | wh.filterPath = (entry) => priorWh.filterPath(entry);
|
---|
| 572 | wh.filterDir = (entry) => priorWh.filterDir(entry);
|
---|
| 573 | }
|
---|
| 574 | // evaluate what is at the path we're being asked to watch
|
---|
| 575 | try {
|
---|
| 576 | const stats = await statMethods[wh.statMethod](wh.watchPath);
|
---|
| 577 | if (this.fsw.closed)
|
---|
| 578 | return;
|
---|
| 579 | if (this.fsw._isIgnored(wh.watchPath, stats)) {
|
---|
| 580 | ready();
|
---|
| 581 | return false;
|
---|
| 582 | }
|
---|
| 583 | const follow = this.fsw.options.followSymlinks;
|
---|
| 584 | let closer;
|
---|
| 585 | if (stats.isDirectory()) {
|
---|
| 586 | const absPath = sysPath.resolve(path);
|
---|
| 587 | const targetPath = follow ? await fsrealpath(path) : path;
|
---|
| 588 | if (this.fsw.closed)
|
---|
| 589 | return;
|
---|
| 590 | closer = await this._handleDir(wh.watchPath, stats, initialAdd, depth, target, wh, targetPath);
|
---|
| 591 | if (this.fsw.closed)
|
---|
| 592 | return;
|
---|
| 593 | // preserve this symlink's target path
|
---|
| 594 | if (absPath !== targetPath && targetPath !== undefined) {
|
---|
| 595 | this.fsw._symlinkPaths.set(absPath, targetPath);
|
---|
| 596 | }
|
---|
| 597 | }
|
---|
| 598 | else if (stats.isSymbolicLink()) {
|
---|
| 599 | const targetPath = follow ? await fsrealpath(path) : path;
|
---|
| 600 | if (this.fsw.closed)
|
---|
| 601 | return;
|
---|
| 602 | const parent = sysPath.dirname(wh.watchPath);
|
---|
| 603 | this.fsw._getWatchedDir(parent).add(wh.watchPath);
|
---|
| 604 | this.fsw._emit(EV.ADD, wh.watchPath, stats);
|
---|
| 605 | closer = await this._handleDir(parent, stats, initialAdd, depth, path, wh, targetPath);
|
---|
| 606 | if (this.fsw.closed)
|
---|
| 607 | return;
|
---|
| 608 | // preserve this symlink's target path
|
---|
| 609 | if (targetPath !== undefined) {
|
---|
| 610 | this.fsw._symlinkPaths.set(sysPath.resolve(path), targetPath);
|
---|
| 611 | }
|
---|
| 612 | }
|
---|
| 613 | else {
|
---|
| 614 | closer = this._handleFile(wh.watchPath, stats, initialAdd);
|
---|
| 615 | }
|
---|
| 616 | ready();
|
---|
| 617 | if (closer)
|
---|
| 618 | this.fsw._addPathCloser(path, closer);
|
---|
| 619 | return false;
|
---|
| 620 | }
|
---|
| 621 | catch (error) {
|
---|
| 622 | if (this.fsw._handleError(error)) {
|
---|
| 623 | ready();
|
---|
| 624 | return path;
|
---|
| 625 | }
|
---|
| 626 | }
|
---|
| 627 | }
|
---|
| 628 | }
|
---|
| 629 | //# sourceMappingURL=handler.js.map |
---|