update, text, response
This commit is contained in:
838
node_modules/chokidar/lib/nodefs-handler.js
generated
vendored
838
node_modules/chokidar/lib/nodefs-handler.js
generated
vendored
@@ -1,109 +1,28 @@
|
||||
'use strict';
|
||||
|
||||
const fs = require('fs');
|
||||
const sysPath = require('path');
|
||||
const { promisify } = require('util');
|
||||
const isBinaryPath = require('is-binary-path');
|
||||
const {
|
||||
isWindows,
|
||||
isLinux,
|
||||
EMPTY_FN,
|
||||
EMPTY_STR,
|
||||
KEY_LISTENERS,
|
||||
KEY_ERR,
|
||||
KEY_RAW,
|
||||
HANDLER_KEYS,
|
||||
EV_CHANGE,
|
||||
EV_ADD,
|
||||
EV_ADD_DIR,
|
||||
EV_ERROR,
|
||||
STR_DATA,
|
||||
STR_END,
|
||||
BRACE_START,
|
||||
STAR
|
||||
} = require('./constants');
|
||||
var fs = require('fs');
|
||||
var sysPath = require('path');
|
||||
var readdirp = require('readdirp');
|
||||
var isBinaryPath = require('is-binary-path');
|
||||
|
||||
const THROTTLE_MODE_WATCH = 'watch';
|
||||
// fs.watch helpers
|
||||
|
||||
const open = promisify(fs.open);
|
||||
const stat = promisify(fs.stat);
|
||||
const lstat = promisify(fs.lstat);
|
||||
const close = promisify(fs.close);
|
||||
const fsrealpath = promisify(fs.realpath);
|
||||
|
||||
const statMethods = { lstat, stat };
|
||||
|
||||
// TODO: emit errors properly. Example: EMFILE on Macos.
|
||||
const foreach = (val, fn) => {
|
||||
if (val instanceof Set) {
|
||||
val.forEach(fn);
|
||||
} else {
|
||||
fn(val);
|
||||
}
|
||||
};
|
||||
|
||||
const addAndConvert = (main, prop, item) => {
|
||||
let container = main[prop];
|
||||
if (!(container instanceof Set)) {
|
||||
main[prop] = container = new Set([container]);
|
||||
}
|
||||
container.add(item);
|
||||
};
|
||||
|
||||
const clearItem = cont => key => {
|
||||
const set = cont[key];
|
||||
if (set instanceof Set) {
|
||||
set.clear();
|
||||
} else {
|
||||
delete cont[key];
|
||||
}
|
||||
};
|
||||
|
||||
const delFromSet = (main, prop, item) => {
|
||||
const container = main[prop];
|
||||
if (container instanceof Set) {
|
||||
container.delete(item);
|
||||
} else if (container === item) {
|
||||
delete main[prop];
|
||||
}
|
||||
};
|
||||
|
||||
const isEmptySet = (val) => val instanceof Set ? val.size === 0 : !val;
|
||||
|
||||
/**
|
||||
* @typedef {String} Path
|
||||
*/
|
||||
|
||||
// fs_watch helpers
|
||||
|
||||
// object to hold per-process fs_watch instances
|
||||
// object to hold per-process fs.watch instances
|
||||
// (may be shared across chokidar FSWatcher instances)
|
||||
var FsWatchInstances = Object.create(null);
|
||||
|
||||
/**
|
||||
* @typedef {Object} FsWatchContainer
|
||||
* @property {Set} listeners
|
||||
* @property {Set} errHandlers
|
||||
* @property {Set} rawEmitters
|
||||
* @property {fs.FSWatcher=} watcher
|
||||
* @property {Boolean=} watcherUnusable
|
||||
*/
|
||||
|
||||
/**
|
||||
* @type {Map<String,FsWatchContainer>}
|
||||
*/
|
||||
const FsWatchInstances = new Map();
|
||||
// Private function: Instantiates the fs.watch interface
|
||||
|
||||
/**
|
||||
* Instantiates the fs_watch interface
|
||||
* @param {String} path to be watched
|
||||
* @param {Object} options to be passed to fs_watch
|
||||
* @param {Function} listener main event handler
|
||||
* @param {Function} errHandler emits info about errors
|
||||
* @param {Function} emitRaw emits raw event data
|
||||
* @returns {fs.FSWatcher} new fsevents instance
|
||||
*/
|
||||
// * path - string, path to be watched
|
||||
// * options - object, options to be passed to fs.watch
|
||||
// * listener - function, main event handler
|
||||
// * errHandler - function, handler which emits info about errors
|
||||
// * emitRaw - function, handler which emits raw event data
|
||||
|
||||
// Returns new fsevents instance
|
||||
function createFsWatchInstance(path, options, listener, errHandler, emitRaw) {
|
||||
const handleEvent = (rawEvent, evPath) => {
|
||||
var handleEvent = function(rawEvent, evPath) {
|
||||
listener(path);
|
||||
emitRaw(rawEvent, evPath, {watchedPath: path});
|
||||
|
||||
@@ -111,7 +30,7 @@ function createFsWatchInstance(path, options, listener, errHandler, emitRaw) {
|
||||
// case the file's watcher misses it (and rely on throttling to de-dupe)
|
||||
if (evPath && path !== evPath) {
|
||||
fsWatchBroadcast(
|
||||
sysPath.resolve(path, evPath), KEY_LISTENERS, sysPath.join(path, evPath)
|
||||
sysPath.resolve(path, evPath), 'listeners', sysPath.join(path, evPath)
|
||||
);
|
||||
}
|
||||
};
|
||||
@@ -122,533 +41,466 @@ function createFsWatchInstance(path, options, listener, errHandler, emitRaw) {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Helper for passing fs_watch event data to a collection of listeners
|
||||
* @param {Path} fullPath absolute path bound to fs_watch instance
|
||||
* @param {String} type listener type
|
||||
* @param {*=} val1 arguments to be passed to listeners
|
||||
* @param {*=} val2
|
||||
* @param {*=} val3
|
||||
*/
|
||||
const fsWatchBroadcast = (fullPath, type, val1, val2, val3) => {
|
||||
const cont = FsWatchInstances.get(fullPath);
|
||||
if (!cont) return;
|
||||
foreach(cont[type], (listener) => {
|
||||
// Private function: Helper for passing fs.watch event data to a
|
||||
// collection of listeners
|
||||
|
||||
// * fullPath - string, absolute path bound to the fs.watch instance
|
||||
// * type - string, listener type
|
||||
// * val[1..3] - arguments to be passed to listeners
|
||||
|
||||
// Returns nothing
|
||||
function fsWatchBroadcast(fullPath, type, val1, val2, val3) {
|
||||
if (!FsWatchInstances[fullPath]) return;
|
||||
FsWatchInstances[fullPath][type].forEach(function(listener) {
|
||||
listener(val1, val2, val3);
|
||||
});
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Instantiates the fs_watch interface or binds listeners
|
||||
* to an existing one covering the same file system entry
|
||||
* @param {String} path
|
||||
* @param {String} fullPath absolute path
|
||||
* @param {Object} options to be passed to fs_watch
|
||||
* @param {Object} handlers container for event listener functions
|
||||
*/
|
||||
const setFsWatchListener = (path, fullPath, options, handlers) => {
|
||||
const {listener, errHandler, rawEmitter} = handlers;
|
||||
let cont = FsWatchInstances.get(fullPath);
|
||||
// Private function: Instantiates the fs.watch interface or binds listeners
|
||||
// to an existing one covering the same file system entry
|
||||
|
||||
/** @type {fs.FSWatcher=} */
|
||||
let watcher;
|
||||
// * path - string, path to be watched
|
||||
// * fullPath - string, absolute path
|
||||
// * options - object, options to be passed to fs.watch
|
||||
// * handlers - object, container for event listener functions
|
||||
|
||||
// Returns close function
|
||||
function setFsWatchListener(path, fullPath, options, handlers) {
|
||||
var listener = handlers.listener;
|
||||
var errHandler = handlers.errHandler;
|
||||
var rawEmitter = handlers.rawEmitter;
|
||||
var container = FsWatchInstances[fullPath];
|
||||
var watcher;
|
||||
if (!options.persistent) {
|
||||
watcher = createFsWatchInstance(
|
||||
path, options, listener, errHandler, rawEmitter
|
||||
);
|
||||
return watcher.close.bind(watcher);
|
||||
}
|
||||
if (cont) {
|
||||
addAndConvert(cont, KEY_LISTENERS, listener);
|
||||
addAndConvert(cont, KEY_ERR, errHandler);
|
||||
addAndConvert(cont, KEY_RAW, rawEmitter);
|
||||
} else {
|
||||
if (!container) {
|
||||
watcher = createFsWatchInstance(
|
||||
path,
|
||||
options,
|
||||
fsWatchBroadcast.bind(null, fullPath, KEY_LISTENERS),
|
||||
fsWatchBroadcast.bind(null, fullPath, 'listeners'),
|
||||
errHandler, // no need to use broadcast here
|
||||
fsWatchBroadcast.bind(null, fullPath, KEY_RAW)
|
||||
fsWatchBroadcast.bind(null, fullPath, 'rawEmitters')
|
||||
);
|
||||
if (!watcher) return;
|
||||
watcher.on(EV_ERROR, async (error) => {
|
||||
const broadcastErr = fsWatchBroadcast.bind(null, fullPath, KEY_ERR);
|
||||
cont.watcherUnusable = true; // documented since Node 10.4.1
|
||||
var broadcastErr = fsWatchBroadcast.bind(null, fullPath, 'errHandlers');
|
||||
watcher.on('error', function(error) {
|
||||
container.watcherUnusable = true; // documented since Node 10.4.1
|
||||
// Workaround for https://github.com/joyent/node/issues/4337
|
||||
if (isWindows && error.code === 'EPERM') {
|
||||
try {
|
||||
const fd = await open(path, 'r');
|
||||
await close(fd);
|
||||
broadcastErr(error);
|
||||
} catch (err) {}
|
||||
if (process.platform === 'win32' && error.code === 'EPERM') {
|
||||
fs.open(path, 'r', function(err, fd) {
|
||||
if (!err) fs.close(fd, function(err) {
|
||||
if (!err) broadcastErr(error);
|
||||
});
|
||||
});
|
||||
} else {
|
||||
broadcastErr(error);
|
||||
}
|
||||
});
|
||||
cont = {
|
||||
listeners: listener,
|
||||
errHandlers: errHandler,
|
||||
rawEmitters: rawEmitter,
|
||||
watcher
|
||||
container = FsWatchInstances[fullPath] = {
|
||||
listeners: [listener],
|
||||
errHandlers: [errHandler],
|
||||
rawEmitters: [rawEmitter],
|
||||
watcher: watcher
|
||||
};
|
||||
FsWatchInstances.set(fullPath, cont);
|
||||
} else {
|
||||
container.listeners.push(listener);
|
||||
container.errHandlers.push(errHandler);
|
||||
container.rawEmitters.push(rawEmitter);
|
||||
}
|
||||
// const index = cont.listeners.indexOf(listener);
|
||||
var listenerIndex = container.listeners.length - 1;
|
||||
|
||||
// removes this instance's listeners and closes the underlying fs_watch
|
||||
// removes this instance's listeners and closes the underlying fs.watch
|
||||
// instance if there are no more listeners left
|
||||
return () => {
|
||||
delFromSet(cont, KEY_LISTENERS, listener);
|
||||
delFromSet(cont, KEY_ERR, errHandler);
|
||||
delFromSet(cont, KEY_RAW, rawEmitter);
|
||||
if (isEmptySet(cont.listeners)) {
|
||||
// Check to protect against issue gh-730.
|
||||
// if (cont.watcherUnusable) {
|
||||
cont.watcher.close();
|
||||
// }
|
||||
FsWatchInstances.delete(fullPath);
|
||||
HANDLER_KEYS.forEach(clearItem(cont));
|
||||
cont.watcher = undefined;
|
||||
Object.freeze(cont);
|
||||
return function close() {
|
||||
delete container.listeners[listenerIndex];
|
||||
delete container.errHandlers[listenerIndex];
|
||||
delete container.rawEmitters[listenerIndex];
|
||||
if (!Object.keys(container.listeners).length) {
|
||||
if (!container.watcherUnusable) { // check to protect against issue #730
|
||||
container.watcher.close();
|
||||
}
|
||||
delete FsWatchInstances[fullPath];
|
||||
}
|
||||
};
|
||||
};
|
||||
}
|
||||
|
||||
// fs_watchFile helpers
|
||||
// fs.watchFile helpers
|
||||
|
||||
// object to hold per-process fs_watchFile instances
|
||||
// object to hold per-process fs.watchFile instances
|
||||
// (may be shared across chokidar FSWatcher instances)
|
||||
const FsWatchFileInstances = new Map();
|
||||
var FsWatchFileInstances = Object.create(null);
|
||||
|
||||
/**
|
||||
* Instantiates the fs_watchFile interface or binds listeners
|
||||
* to an existing one covering the same file system entry
|
||||
* @param {String} path to be watched
|
||||
* @param {String} fullPath absolute path
|
||||
* @param {Object} options options to be passed to fs_watchFile
|
||||
* @param {Object} handlers container for event listener functions
|
||||
* @returns {Function} closer
|
||||
*/
|
||||
const setFsWatchFileListener = (path, fullPath, options, handlers) => {
|
||||
const {listener, rawEmitter} = handlers;
|
||||
let cont = FsWatchFileInstances.get(fullPath);
|
||||
// Private function: Instantiates the fs.watchFile interface or binds listeners
|
||||
// to an existing one covering the same file system entry
|
||||
|
||||
/* eslint-disable no-unused-vars, prefer-destructuring */
|
||||
let listeners = new Set();
|
||||
let rawEmitters = new Set();
|
||||
// * path - string, path to be watched
|
||||
// * fullPath - string, absolute path
|
||||
// * options - object, options to be passed to fs.watchFile
|
||||
// * handlers - object, container for event listener functions
|
||||
|
||||
const copts = cont && cont.options;
|
||||
if (copts && (copts.persistent < options.persistent || copts.interval > options.interval)) {
|
||||
// Returns close function
|
||||
function setFsWatchFileListener(path, fullPath, options, handlers) {
|
||||
var listener = handlers.listener;
|
||||
var rawEmitter = handlers.rawEmitter;
|
||||
var container = FsWatchFileInstances[fullPath];
|
||||
var listeners = [];
|
||||
var rawEmitters = [];
|
||||
if (
|
||||
container && (
|
||||
container.options.persistent < options.persistent ||
|
||||
container.options.interval > options.interval
|
||||
)
|
||||
) {
|
||||
// "Upgrade" the watcher to persistence or a quicker interval.
|
||||
// This creates some unlikely edge case issues if the user mixes
|
||||
// settings in a very weird way, but solving for those cases
|
||||
// doesn't seem worthwhile for the added complexity.
|
||||
listeners = cont.listeners;
|
||||
rawEmitters = cont.rawEmitters;
|
||||
listeners = container.listeners;
|
||||
rawEmitters = container.rawEmitters;
|
||||
fs.unwatchFile(fullPath);
|
||||
cont = undefined;
|
||||
container = false;
|
||||
}
|
||||
|
||||
/* eslint-enable no-unused-vars, prefer-destructuring */
|
||||
|
||||
if (cont) {
|
||||
addAndConvert(cont, KEY_LISTENERS, listener);
|
||||
addAndConvert(cont, KEY_RAW, rawEmitter);
|
||||
} else {
|
||||
// TODO
|
||||
// listeners.add(listener);
|
||||
// rawEmitters.add(rawEmitter);
|
||||
cont = {
|
||||
listeners: listener,
|
||||
rawEmitters: rawEmitter,
|
||||
options,
|
||||
watcher: fs.watchFile(fullPath, options, (curr, prev) => {
|
||||
foreach(cont.rawEmitters, (rawEmitter) => {
|
||||
rawEmitter(EV_CHANGE, fullPath, {curr, prev});
|
||||
if (!container) {
|
||||
listeners.push(listener);
|
||||
rawEmitters.push(rawEmitter);
|
||||
container = FsWatchFileInstances[fullPath] = {
|
||||
listeners: listeners,
|
||||
rawEmitters: rawEmitters,
|
||||
options: options,
|
||||
watcher: fs.watchFile(fullPath, options, function(curr, prev) {
|
||||
container.rawEmitters.forEach(function(rawEmitter) {
|
||||
rawEmitter('change', fullPath, {curr: curr, prev: prev});
|
||||
});
|
||||
const currmtime = curr.mtimeMs;
|
||||
if (curr.size !== prev.size || currmtime > prev.mtimeMs || currmtime === 0) {
|
||||
foreach(cont.listeners, (listener) => listener(path, curr));
|
||||
var currmtime = curr.mtime.getTime();
|
||||
if (curr.size !== prev.size || currmtime > prev.mtime.getTime() || currmtime === 0) {
|
||||
container.listeners.forEach(function(listener) {
|
||||
listener(path, curr);
|
||||
});
|
||||
}
|
||||
})
|
||||
};
|
||||
FsWatchFileInstances.set(fullPath, cont);
|
||||
} else {
|
||||
container.listeners.push(listener);
|
||||
container.rawEmitters.push(rawEmitter);
|
||||
}
|
||||
// const index = cont.listeners.indexOf(listener);
|
||||
var listenerIndex = container.listeners.length - 1;
|
||||
|
||||
// Removes this instance's listeners and closes the underlying fs_watchFile
|
||||
// instance if there are no more listeners left.
|
||||
return () => {
|
||||
delFromSet(cont, KEY_LISTENERS, listener);
|
||||
delFromSet(cont, KEY_RAW, rawEmitter);
|
||||
if (isEmptySet(cont.listeners)) {
|
||||
FsWatchFileInstances.delete(fullPath);
|
||||
// removes this instance's listeners and closes the underlying fs.watchFile
|
||||
// instance if there are no more listeners left
|
||||
return function close() {
|
||||
delete container.listeners[listenerIndex];
|
||||
delete container.rawEmitters[listenerIndex];
|
||||
if (!Object.keys(container.listeners).length) {
|
||||
fs.unwatchFile(fullPath);
|
||||
cont.options = cont.watcher = undefined;
|
||||
Object.freeze(cont);
|
||||
delete FsWatchFileInstances[fullPath];
|
||||
}
|
||||
};
|
||||
};
|
||||
|
||||
/**
|
||||
* @mixin
|
||||
*/
|
||||
class NodeFsHandler {
|
||||
|
||||
/**
|
||||
* @param {import("../index").FSWatcher} fsW
|
||||
*/
|
||||
constructor(fsW) {
|
||||
this.fsw = fsW;
|
||||
this._boundHandleError = (error) => fsW._handleError(error);
|
||||
}
|
||||
|
||||
/**
|
||||
* Watch file for changes with fs_watchFile or fs_watch.
|
||||
* @param {String} path to file or dir
|
||||
* @param {Function} listener on fs change
|
||||
* @returns {Function} closer for the watcher instance
|
||||
*/
|
||||
_watchWithNodeFs(path, listener) {
|
||||
const opts = this.fsw.options;
|
||||
const directory = sysPath.dirname(path);
|
||||
const basename = sysPath.basename(path);
|
||||
const parent = this.fsw._getWatchedDir(directory);
|
||||
parent.add(basename);
|
||||
const absolutePath = sysPath.resolve(path);
|
||||
const options = {persistent: opts.persistent};
|
||||
if (!listener) listener = EMPTY_FN;
|
||||
// fake constructor for attaching nodefs-specific prototype methods that
|
||||
// will be copied to FSWatcher's prototype
|
||||
function NodeFsHandler() {}
|
||||
|
||||
let closer;
|
||||
if (opts.usePolling) {
|
||||
options.interval = opts.enableBinaryInterval && isBinaryPath(basename) ?
|
||||
opts.binaryInterval : opts.interval;
|
||||
// Private method: Watch file for changes with fs.watchFile or fs.watch.
|
||||
|
||||
// * path - string, path to file or directory.
|
||||
// * listener - function, to be executed on fs change.
|
||||
|
||||
// Returns close function for the watcher instance
|
||||
NodeFsHandler.prototype._watchWithNodeFs =
|
||||
function(path, listener) {
|
||||
var directory = sysPath.dirname(path);
|
||||
var basename = sysPath.basename(path);
|
||||
var parent = this._getWatchedDir(directory);
|
||||
parent.add(basename);
|
||||
var absolutePath = sysPath.resolve(path);
|
||||
var options = {persistent: this.options.persistent};
|
||||
if (!listener) listener = Function.prototype; // empty function
|
||||
|
||||
var closer;
|
||||
if (this.options.usePolling) {
|
||||
options.interval = this.enableBinaryInterval && isBinaryPath(basename) ?
|
||||
this.options.binaryInterval : this.options.interval;
|
||||
closer = setFsWatchFileListener(path, absolutePath, options, {
|
||||
listener,
|
||||
rawEmitter: this.fsw._emitRaw
|
||||
listener: listener,
|
||||
rawEmitter: this.emit.bind(this, 'raw')
|
||||
});
|
||||
} else {
|
||||
closer = setFsWatchListener(path, absolutePath, options, {
|
||||
listener,
|
||||
errHandler: this._boundHandleError,
|
||||
rawEmitter: this.fsw._emitRaw
|
||||
listener: listener,
|
||||
errHandler: this._handleError.bind(this),
|
||||
rawEmitter: this.emit.bind(this, 'raw')
|
||||
});
|
||||
}
|
||||
return closer;
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Watch a file and emit add event if warranted.
|
||||
* @param {Path} file Path
|
||||
* @param {fs.Stats} stats result of fs_stat
|
||||
* @param {Boolean} initialAdd was the file added at watch instantiation?
|
||||
* @returns {Function} closer for the watcher instance
|
||||
*/
|
||||
_handleFile(file, stats, initialAdd) {
|
||||
if (this.fsw.closed) {
|
||||
return;
|
||||
}
|
||||
const dirname = sysPath.dirname(file);
|
||||
const basename = sysPath.basename(file);
|
||||
const parent = this.fsw._getWatchedDir(dirname);
|
||||
// Private method: Watch a file and emit add event if warranted
|
||||
|
||||
// * file - string, the file's path
|
||||
// * stats - object, result of fs.stat
|
||||
// * initialAdd - boolean, was the file added at watch instantiation?
|
||||
// * callback - function, called when done processing as a newly seen file
|
||||
|
||||
// Returns close function for the watcher instance
|
||||
NodeFsHandler.prototype._handleFile =
|
||||
function(file, stats, initialAdd, callback) {
|
||||
var dirname = sysPath.dirname(file);
|
||||
var basename = sysPath.basename(file);
|
||||
var parent = this._getWatchedDir(dirname);
|
||||
// stats is always present
|
||||
let prevStats = stats;
|
||||
var prevStats = stats;
|
||||
|
||||
// if the file is already being watched, do nothing
|
||||
if (parent.has(basename)) return;
|
||||
if (parent.has(basename)) return callback();
|
||||
|
||||
const listener = async (path, newStats) => {
|
||||
if (!this.fsw._throttle(THROTTLE_MODE_WATCH, file, 5)) return;
|
||||
if (!newStats || newStats.mtimeMs === 0) {
|
||||
try {
|
||||
const newStats = await stat(file);
|
||||
if (this.fsw.closed) return;
|
||||
// Check that change event was not fired because of changed only accessTime.
|
||||
const at = newStats.atimeMs;
|
||||
const mt = newStats.mtimeMs;
|
||||
if (!at || at <= mt || mt !== prevStats.mtimeMs) {
|
||||
this.fsw._emit(EV_CHANGE, file, newStats);
|
||||
}
|
||||
if (isLinux && prevStats.ino !== newStats.ino) {
|
||||
this.fsw._closeFile(path)
|
||||
prevStats = newStats;
|
||||
this.fsw._addPathCloser(path, this._watchWithNodeFs(file, listener));
|
||||
} else {
|
||||
prevStats = newStats;
|
||||
}
|
||||
} catch (error) {
|
||||
// kick off the watcher
|
||||
var closer = this._watchWithNodeFs(file, function(path, newStats) {
|
||||
if (!this._throttle('watch', file, 5)) return;
|
||||
if (!newStats || newStats && newStats.mtime.getTime() === 0) {
|
||||
fs.stat(file, function(error, newStats) {
|
||||
// Fix issues where mtime is null but file is still present
|
||||
this.fsw._remove(dirname, basename);
|
||||
}
|
||||
// add is about to be emitted if file not already tracked in parent
|
||||
if (error) {
|
||||
this._remove(dirname, basename);
|
||||
} else {
|
||||
// Check that change event was not fired because of changed only accessTime.
|
||||
var at = newStats.atime.getTime();
|
||||
var mt = newStats.mtime.getTime();
|
||||
if (!at || at <= mt || mt !== prevStats.mtime.getTime()) {
|
||||
this._emit('change', file, newStats);
|
||||
}
|
||||
prevStats = newStats;
|
||||
}
|
||||
}.bind(this));
|
||||
// add is about to be emitted if file not already tracked in parent
|
||||
} else if (parent.has(basename)) {
|
||||
// Check that change event was not fired because of changed only accessTime.
|
||||
const at = newStats.atimeMs;
|
||||
const mt = newStats.mtimeMs;
|
||||
if (!at || at <= mt || mt !== prevStats.mtimeMs) {
|
||||
this.fsw._emit(EV_CHANGE, file, newStats);
|
||||
var at = newStats.atime.getTime();
|
||||
var mt = newStats.mtime.getTime();
|
||||
if (!at || at <= mt || mt !== prevStats.mtime.getTime()) {
|
||||
this._emit('change', file, newStats);
|
||||
}
|
||||
prevStats = newStats;
|
||||
}
|
||||
}
|
||||
// kick off the watcher
|
||||
const closer = this._watchWithNodeFs(file, listener);
|
||||
}.bind(this));
|
||||
|
||||
// emit an add event if we're supposed to
|
||||
if (!(initialAdd && this.fsw.options.ignoreInitial) && this.fsw._isntIgnored(file)) {
|
||||
if (!this.fsw._throttle(EV_ADD, file, 0)) return;
|
||||
this.fsw._emit(EV_ADD, file, stats);
|
||||
if (!(initialAdd && this.options.ignoreInitial)) {
|
||||
if (!this._throttle('add', file, 0)) return;
|
||||
this._emit('add', file, stats);
|
||||
}
|
||||
|
||||
if (callback) callback();
|
||||
return closer;
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Handle symlinks encountered while reading a dir.
|
||||
* @param {Object} entry returned by readdirp
|
||||
* @param {String} directory path of dir being read
|
||||
* @param {String} path of this item
|
||||
* @param {String} item basename of this item
|
||||
* @returns {Promise<Boolean>} true if no more processing is needed for this entry.
|
||||
*/
|
||||
async _handleSymlink(entry, directory, path, item) {
|
||||
if (this.fsw.closed) {
|
||||
return;
|
||||
}
|
||||
const full = entry.fullPath;
|
||||
const dir = this.fsw._getWatchedDir(directory);
|
||||
// Private method: Handle symlinks encountered while reading a dir
|
||||
|
||||
if (!this.fsw.options.followSymlinks) {
|
||||
// * entry - object, entry object returned by readdirp
|
||||
// * directory - string, path of the directory being read
|
||||
// * path - string, path of this item
|
||||
// * item - string, basename of this item
|
||||
|
||||
// Returns true if no more processing is needed for this entry.
|
||||
NodeFsHandler.prototype._handleSymlink =
|
||||
function(entry, directory, path, item) {
|
||||
var full = entry.fullPath;
|
||||
var dir = this._getWatchedDir(directory);
|
||||
|
||||
if (!this.options.followSymlinks) {
|
||||
// watch symlink directly (don't follow) and detect changes
|
||||
this.fsw._incrReadyCount();
|
||||
|
||||
let linkPath;
|
||||
try {
|
||||
linkPath = await fsrealpath(path);
|
||||
} catch (e) {
|
||||
this.fsw._emitReady();
|
||||
return true;
|
||||
}
|
||||
|
||||
if (this.fsw.closed) return;
|
||||
if (dir.has(item)) {
|
||||
if (this.fsw._symlinkPaths.get(full) !== linkPath) {
|
||||
this.fsw._symlinkPaths.set(full, linkPath);
|
||||
this.fsw._emit(EV_CHANGE, path, entry.stats);
|
||||
this._readyCount++;
|
||||
fs.realpath(path, function(error, linkPath) {
|
||||
if (dir.has(item)) {
|
||||
if (this._symlinkPaths[full] !== linkPath) {
|
||||
this._symlinkPaths[full] = linkPath;
|
||||
this._emit('change', path, entry.stat);
|
||||
}
|
||||
} else {
|
||||
dir.add(item);
|
||||
this._symlinkPaths[full] = linkPath;
|
||||
this._emit('add', path, entry.stat);
|
||||
}
|
||||
} else {
|
||||
dir.add(item);
|
||||
this.fsw._symlinkPaths.set(full, linkPath);
|
||||
this.fsw._emit(EV_ADD, path, entry.stats);
|
||||
}
|
||||
this.fsw._emitReady();
|
||||
this._emitReady();
|
||||
}.bind(this));
|
||||
return true;
|
||||
}
|
||||
|
||||
// don't follow the same symlink more than once
|
||||
if (this.fsw._symlinkPaths.has(full)) {
|
||||
return true;
|
||||
if (this._symlinkPaths[full]) return true;
|
||||
else this._symlinkPaths[full] = true;
|
||||
};
|
||||
|
||||
// Private method: Read directory to add / remove files from `@watched` list
|
||||
// and re-read it on change.
|
||||
|
||||
// * dir - string, fs path.
|
||||
// * stats - object, result of fs.stat
|
||||
// * initialAdd - boolean, was the file added at watch instantiation?
|
||||
// * depth - int, depth relative to user-supplied path
|
||||
// * target - string, child path actually targeted for watch
|
||||
// * wh - object, common watch helpers for this path
|
||||
// * callback - function, called when dir scan is complete
|
||||
|
||||
// Returns close function for the watcher instance
|
||||
NodeFsHandler.prototype._handleDir =
|
||||
function(dir, stats, initialAdd, depth, target, wh, callback) {
|
||||
var parentDir = this._getWatchedDir(sysPath.dirname(dir));
|
||||
var tracked = parentDir.has(sysPath.basename(dir));
|
||||
if (!(initialAdd && this.options.ignoreInitial) && !target && !tracked) {
|
||||
if (!wh.hasGlob || wh.globFilter(dir)) this._emit('addDir', dir, stats);
|
||||
}
|
||||
|
||||
this.fsw._symlinkPaths.set(full, true);
|
||||
}
|
||||
// ensure dir is tracked (harmless if redundant)
|
||||
parentDir.add(sysPath.basename(dir));
|
||||
this._getWatchedDir(dir);
|
||||
|
||||
_handleRead(directory, initialAdd, wh, target, dir, depth, throttler) {
|
||||
// Normalize the directory name on Windows
|
||||
directory = sysPath.join(directory, EMPTY_STR);
|
||||
var read = function(directory, initialAdd, done) {
|
||||
// Normalize the directory name on Windows
|
||||
directory = sysPath.join(directory, '');
|
||||
|
||||
if (!wh.hasGlob) {
|
||||
throttler = this.fsw._throttle('readdir', directory, 1000);
|
||||
if (!throttler) return;
|
||||
}
|
||||
|
||||
const previous = this.fsw._getWatchedDir(wh.path);
|
||||
const current = new Set();
|
||||
|
||||
let stream = this.fsw._readdirp(directory, {
|
||||
fileFilter: entry => wh.filterPath(entry),
|
||||
directoryFilter: entry => wh.filterDir(entry),
|
||||
depth: 0
|
||||
}).on(STR_DATA, async (entry) => {
|
||||
if (this.fsw.closed) {
|
||||
stream = undefined;
|
||||
return;
|
||||
}
|
||||
const item = entry.path;
|
||||
let path = sysPath.join(directory, item);
|
||||
current.add(item);
|
||||
|
||||
if (entry.stats.isSymbolicLink() && await this._handleSymlink(entry, directory, path, item)) {
|
||||
return;
|
||||
if (!wh.hasGlob) {
|
||||
var throttler = this._throttle('readdir', directory, 1000);
|
||||
if (!throttler) return;
|
||||
}
|
||||
|
||||
if (this.fsw.closed) {
|
||||
stream = undefined;
|
||||
return;
|
||||
}
|
||||
// Files that present in current directory snapshot
|
||||
// but absent in previous are added to watch list and
|
||||
// emit `add` event.
|
||||
if (item === target || !target && !previous.has(item)) {
|
||||
this.fsw._incrReadyCount();
|
||||
var previous = this._getWatchedDir(wh.path);
|
||||
var current = [];
|
||||
|
||||
// ensure relativeness of path is preserved in case of watcher reuse
|
||||
path = sysPath.join(dir, sysPath.relative(dir, path));
|
||||
readdirp({
|
||||
root: directory,
|
||||
entryType: 'all',
|
||||
fileFilter: wh.filterPath,
|
||||
directoryFilter: wh.filterDir,
|
||||
depth: 0,
|
||||
lstat: true
|
||||
}).on('data', function(entry) {
|
||||
var item = entry.path;
|
||||
var path = sysPath.join(directory, item);
|
||||
current.push(item);
|
||||
|
||||
this._addToNodeFs(path, initialAdd, wh, depth + 1);
|
||||
}
|
||||
}).on(EV_ERROR, this._boundHandleError);
|
||||
if (entry.stat.isSymbolicLink() &&
|
||||
this._handleSymlink(entry, directory, path, item)) return;
|
||||
|
||||
return new Promise(resolve =>
|
||||
stream.once(STR_END, () => {
|
||||
if (this.fsw.closed) {
|
||||
stream = undefined;
|
||||
return;
|
||||
// Files that present in current directory snapshot
|
||||
// but absent in previous are added to watch list and
|
||||
// emit `add` event.
|
||||
if (item === target || !target && !previous.has(item)) {
|
||||
this._readyCount++;
|
||||
|
||||
// ensure relativeness of path is preserved in case of watcher reuse
|
||||
path = sysPath.join(dir, sysPath.relative(dir, path));
|
||||
|
||||
this._addToNodeFs(path, initialAdd, wh, depth + 1);
|
||||
}
|
||||
const wasThrottled = throttler ? throttler.clear() : false;
|
||||
|
||||
resolve();
|
||||
}.bind(this)).on('end', function() {
|
||||
var wasThrottled = throttler ? throttler.clear() : false;
|
||||
if (done) done();
|
||||
|
||||
// Files that absent in current directory snapshot
|
||||
// but present in previous emit `remove` event
|
||||
// and are removed from @watched[directory].
|
||||
previous.getChildren().filter((item) => {
|
||||
previous.children().filter(function(item) {
|
||||
return item !== directory &&
|
||||
!current.has(item) &&
|
||||
current.indexOf(item) === -1 &&
|
||||
// in case of intersecting globs;
|
||||
// a path may have been filtered out of this readdir, but
|
||||
// shouldn't be removed because it matches a different glob
|
||||
(!wh.hasGlob || wh.filterPath({
|
||||
fullPath: sysPath.resolve(directory, item)
|
||||
}));
|
||||
}).forEach((item) => {
|
||||
this.fsw._remove(directory, item);
|
||||
});
|
||||
|
||||
stream = undefined;
|
||||
}).forEach(function(item) {
|
||||
this._remove(directory, item);
|
||||
}, this);
|
||||
|
||||
// one more time for any missed in case changes came in extremely quickly
|
||||
if (wasThrottled) this._handleRead(directory, false, wh, target, dir, depth, throttler);
|
||||
})
|
||||
);
|
||||
}
|
||||
if (wasThrottled) read(directory, false);
|
||||
}.bind(this)).on('error', this._handleError.bind(this));
|
||||
}.bind(this);
|
||||
|
||||
/**
|
||||
* Read directory to add / remove files from `@watched` list and re-read it on change.
|
||||
* @param {String} dir fs path
|
||||
* @param {fs.Stats} stats
|
||||
* @param {Boolean} initialAdd
|
||||
* @param {Number} depth relative to user-supplied path
|
||||
* @param {String} target child path targeted for watch
|
||||
* @param {Object} wh Common watch helpers for this path
|
||||
* @param {String} realpath
|
||||
* @returns {Promise<Function>} closer for the watcher instance.
|
||||
*/
|
||||
async _handleDir(dir, stats, initialAdd, depth, target, wh, realpath) {
|
||||
const parentDir = this.fsw._getWatchedDir(sysPath.dirname(dir));
|
||||
const tracked = parentDir.has(sysPath.basename(dir));
|
||||
if (!(initialAdd && this.fsw.options.ignoreInitial) && !target && !tracked) {
|
||||
if (!wh.hasGlob || wh.globFilter(dir)) this.fsw._emit(EV_ADD_DIR, dir, stats);
|
||||
}
|
||||
var closer;
|
||||
|
||||
// ensure dir is tracked (harmless if redundant)
|
||||
parentDir.add(sysPath.basename(dir));
|
||||
this.fsw._getWatchedDir(dir);
|
||||
let throttler;
|
||||
let closer;
|
||||
|
||||
const oDepth = this.fsw.options.depth;
|
||||
if ((oDepth == null || depth <= oDepth) && !this.fsw._symlinkPaths.has(realpath)) {
|
||||
if (!target) {
|
||||
await this._handleRead(dir, initialAdd, wh, target, dir, depth, throttler);
|
||||
if (this.fsw.closed) return;
|
||||
}
|
||||
|
||||
closer = this._watchWithNodeFs(dir, (dirPath, stats) => {
|
||||
if (this.options.depth == null || depth <= this.options.depth) {
|
||||
if (!target) read(dir, initialAdd, callback);
|
||||
closer = this._watchWithNodeFs(dir, function(dirPath, stats) {
|
||||
// if current directory is removed, do nothing
|
||||
if (stats && stats.mtimeMs === 0) return;
|
||||
if (stats && stats.mtime.getTime() === 0) return;
|
||||
|
||||
this._handleRead(dirPath, false, wh, target, dir, depth, throttler);
|
||||
read(dirPath, false);
|
||||
});
|
||||
} else {
|
||||
callback();
|
||||
}
|
||||
return closer;
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Handle added file, directory, or glob pattern.
|
||||
* Delegates call to _handleFile / _handleDir after checks.
|
||||
* @param {String} path to file or ir
|
||||
* @param {Boolean} initialAdd was the file added at watch instantiation?
|
||||
* @param {Object} priorWh depth relative to user-supplied path
|
||||
* @param {Number} depth Child path actually targeted for watch
|
||||
* @param {String=} target Child path actually targeted for watch
|
||||
* @returns {Promise}
|
||||
*/
|
||||
async _addToNodeFs(path, initialAdd, priorWh, depth, target) {
|
||||
const ready = this.fsw._emitReady;
|
||||
if (this.fsw._isIgnored(path) || this.fsw.closed) {
|
||||
// Private method: Handle added file, directory, or glob pattern.
|
||||
// Delegates call to _handleFile / _handleDir after checks.
|
||||
|
||||
// * path - string, path to file or directory.
|
||||
// * initialAdd - boolean, was the file added at watch instantiation?
|
||||
// * depth - int, depth relative to user-supplied path
|
||||
// * target - string, child path actually targeted for watch
|
||||
// * callback - function, indicates whether the path was found or not
|
||||
|
||||
// Returns nothing
|
||||
NodeFsHandler.prototype._addToNodeFs =
|
||||
function(path, initialAdd, priorWh, depth, target, callback) {
|
||||
if (!callback) callback = Function.prototype;
|
||||
var ready = this._emitReady;
|
||||
if (this._isIgnored(path) || this.closed) {
|
||||
ready();
|
||||
return false;
|
||||
return callback(null, false);
|
||||
}
|
||||
|
||||
const wh = this.fsw._getWatchHelpers(path, depth);
|
||||
var wh = this._getWatchHelpers(path, depth);
|
||||
if (!wh.hasGlob && priorWh) {
|
||||
wh.hasGlob = priorWh.hasGlob;
|
||||
wh.globFilter = priorWh.globFilter;
|
||||
wh.filterPath = entry => priorWh.filterPath(entry);
|
||||
wh.filterDir = entry => priorWh.filterDir(entry);
|
||||
wh.filterPath = priorWh.filterPath;
|
||||
wh.filterDir = priorWh.filterDir;
|
||||
}
|
||||
|
||||
// evaluate what is at the path we're being asked to watch
|
||||
try {
|
||||
const stats = await statMethods[wh.statMethod](wh.watchPath);
|
||||
if (this.fsw.closed) return;
|
||||
if (this.fsw._isIgnored(wh.watchPath, stats)) {
|
||||
fs[wh.statMethod](wh.watchPath, function(error, stats) {
|
||||
if (this._handleError(error)) return callback(null, path);
|
||||
if (this._isIgnored(wh.watchPath, stats)) {
|
||||
ready();
|
||||
return false;
|
||||
return callback(null, false);
|
||||
}
|
||||
|
||||
const follow = this.fsw.options.followSymlinks && !path.includes(STAR) && !path.includes(BRACE_START);
|
||||
let closer;
|
||||
var initDir = function(dir, target) {
|
||||
return this._handleDir(dir, stats, initialAdd, depth, target, wh, ready);
|
||||
}.bind(this);
|
||||
|
||||
var closer;
|
||||
if (stats.isDirectory()) {
|
||||
const absPath = sysPath.resolve(path);
|
||||
const targetPath = follow ? await fsrealpath(path) : path;
|
||||
if (this.fsw.closed) return;
|
||||
closer = await this._handleDir(wh.watchPath, stats, initialAdd, depth, target, wh, targetPath);
|
||||
if (this.fsw.closed) return;
|
||||
// preserve this symlink's target path
|
||||
if (absPath !== targetPath && targetPath !== undefined) {
|
||||
this.fsw._symlinkPaths.set(absPath, targetPath);
|
||||
}
|
||||
closer = initDir(wh.watchPath, target);
|
||||
} else if (stats.isSymbolicLink()) {
|
||||
const targetPath = follow ? await fsrealpath(path) : path;
|
||||
if (this.fsw.closed) return;
|
||||
const parent = sysPath.dirname(wh.watchPath);
|
||||
this.fsw._getWatchedDir(parent).add(wh.watchPath);
|
||||
this.fsw._emit(EV_ADD, wh.watchPath, stats);
|
||||
closer = await this._handleDir(parent, stats, initialAdd, depth, path, wh, targetPath);
|
||||
if (this.fsw.closed) return;
|
||||
var parent = sysPath.dirname(wh.watchPath);
|
||||
this._getWatchedDir(parent).add(wh.watchPath);
|
||||
this._emit('add', wh.watchPath, stats);
|
||||
closer = initDir(parent, path);
|
||||
|
||||
// preserve this symlink's target path
|
||||
if (targetPath !== undefined) {
|
||||
this.fsw._symlinkPaths.set(sysPath.resolve(path), targetPath);
|
||||
}
|
||||
fs.realpath(path, function(error, targetPath) {
|
||||
this._symlinkPaths[sysPath.resolve(path)] = targetPath;
|
||||
ready();
|
||||
}.bind(this));
|
||||
} else {
|
||||
closer = this._handleFile(wh.watchPath, stats, initialAdd);
|
||||
closer = this._handleFile(wh.watchPath, stats, initialAdd, ready);
|
||||
}
|
||||
ready();
|
||||
|
||||
this.fsw._addPathCloser(path, closer);
|
||||
return false;
|
||||
|
||||
} catch (error) {
|
||||
if (this.fsw._handleError(error)) {
|
||||
ready();
|
||||
return path;
|
||||
if (closer) {
|
||||
this._closers[path] = this._closers[path] || [];
|
||||
this._closers[path].push(closer);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
callback(null, false);
|
||||
}.bind(this));
|
||||
};
|
||||
|
||||
module.exports = NodeFsHandler;
|
||||
|
||||
Reference in New Issue
Block a user