Initial pass
This commit is contained in:
+149
@@ -0,0 +1,149 @@
|
||||
[](https://circleci.com/gh/amasad/sane)
|
||||
|
||||
sane
|
||||
----
|
||||
|
||||
I've been driven to insanity by node filesystem watcher wrappers.
|
||||
Sane aims to be fast, small, and reliable file system watcher. It does that by:
|
||||
|
||||
* By default stays away from fs polling because it's very slow and cpu intensive
|
||||
* Uses `fs.watch` by default and sensibly works around the various issues
|
||||
* Maintains a consistent API across different platforms
|
||||
* Where `fs.watch` is not reliable you have the choice of using the following alternatives:
|
||||
* [the facebook watchman library](https://facebook.github.io/watchman/)
|
||||
* [the watchexec library](https://github.com/watchexec/watchexec)
|
||||
* polling
|
||||
|
||||
## Install
|
||||
|
||||
```
|
||||
$ npm install sane
|
||||
```
|
||||
|
||||
## How to choose a mode
|
||||
|
||||
Don't worry too much about choosing the correct mode upfront because sane
|
||||
maintains the same API across all modes and will be easy to switch.
|
||||
|
||||
* If you're only supporting Linux and OS X, `watchman` would be the most reliable mode
|
||||
* If you're using node > v0.10.0 use the default mode
|
||||
* If you're running OS X and you're watching a lot of directories and you're running into https://github.com/joyent/node/issues/5463, use `watchman`
|
||||
* If you're in an environment where native file system events aren't available (like Vagrant), you should use polling
|
||||
* Otherwise, the default mode should work well for you
|
||||
|
||||
## API
|
||||
|
||||
### sane(dir, options)
|
||||
|
||||
Watches a directory and all its descendant directories for changes, deletions, and additions on files and directories.
|
||||
|
||||
```js
|
||||
var watcher = sane('path/to/dir', {glob: ['**/*.js', '**/*.css']});
|
||||
watcher.on('ready', function () { console.log('ready') });
|
||||
watcher.on('change', function (filepath, root, stat) { console.log('file changed', filepath); });
|
||||
watcher.on('add', function (filepath, root, stat) { console.log('file added', filepath); });
|
||||
watcher.on('delete', function (filepath, root) { console.log('file deleted', filepath); });
|
||||
// close
|
||||
watcher.close();
|
||||
```
|
||||
|
||||
options:
|
||||
|
||||
* `glob`: a single string glob pattern or an array of them.
|
||||
* `poll`: puts the watcher in polling mode. Under the hood that means `fs.watchFile`.
|
||||
* `watchman`: makes the watcher use [watchman](https://facebook.github.io/watchman/).
|
||||
* `watchmanPath`: sets a custom path for `watchman` binary.
|
||||
* `watchexec`: makes the watcher use [watchexec](https://github.com/watchexec/watchexec).
|
||||
* `dot`: enables watching files/directories that start with a dot.
|
||||
* `ignored`: a glob, regex, function, or array of any combination.
|
||||
|
||||
For the glob pattern documentation, see [micromatch](https://github.com/micromatch/micromatch).
|
||||
If you choose to use `watchman` you'll have to [install watchman yourself](https://facebook.github.io/watchman/docs/install.html)).
|
||||
If you choose to use `watchexec` you'll have to [install watchexec yourself](https://github.com/watchexec/watchexec)).
|
||||
For the ignored options, see [anymatch](https://github.com/es128/anymatch).
|
||||
|
||||
### sane.NodeWatcher(dir, options)
|
||||
|
||||
The default watcher class. Uses `fs.watch` under the hood, and takes the same options as `sane(dir, options)`.
|
||||
|
||||
### sane.WatchmanWatcher(dir, options)
|
||||
|
||||
The watchman watcher class. Takes the same options as `sane(dir, options)`.
|
||||
|
||||
### sane.Watchexec(dir, options)
|
||||
|
||||
The watchexec watcher class. Takes the same options as `sane(dir, options)`.
|
||||
|
||||
### sane.PollWatcher(dir, options)
|
||||
|
||||
The polling watcher class. Takes the same options as `sane(dir, options)` with the addition of:
|
||||
|
||||
* interval: indicates how often the files should be polled. (passed to fs.watchFile)
|
||||
|
||||
### sane.{Node|Watchman|Watchexec|Poll}Watcher#close
|
||||
|
||||
Stops watching.
|
||||
|
||||
### sane.{Node|Watchman|Watchexec|Poll}Watcher events
|
||||
|
||||
Emits the following events:
|
||||
|
||||
All events are passed the file/dir path relative to the root directory
|
||||
* `ready` when the program is ready to detect events in the directory
|
||||
* `change` when a file changes
|
||||
* `add` when a file or directory has been added
|
||||
* `delete` when a file or directory has been deleted
|
||||
|
||||
## CLI
|
||||
|
||||
This module includes a simple command line interface, which you can install with `npm install sane -g`.
|
||||
|
||||
```
|
||||
Usage: sane <command> [...directory] [--glob=<filePattern>] [--poll] [--watchman] [--watchman-path=<watchmanBinaryPath>] [--dot] [--wait=<seconds>]
|
||||
|
||||
OPTIONS:
|
||||
--glob=<filePattern>
|
||||
A single string glob pattern or an array of them.
|
||||
|
||||
--ignored=<filePattern>
|
||||
A glob, regex, function, or array of any combination.
|
||||
|
||||
--poll, -p
|
||||
Use polling mode.
|
||||
|
||||
--watchman, -w
|
||||
Use watchman (if available).
|
||||
|
||||
--watchman-path=<watchmanBinaryPath>
|
||||
Sets a custom path for watchman binary (if using this mode).
|
||||
|
||||
--dot, -d
|
||||
Enables watching files/directories that start with a dot.
|
||||
|
||||
--wait=<seconds>
|
||||
Duration, in seconds, that watching will be disabled
|
||||
after running <command>. Setting this option will
|
||||
throttle calls to <command> for the specified duration.
|
||||
--quiet, -q
|
||||
Disables sane's console output
|
||||
|
||||
--changes-only, -o
|
||||
Runs <command> only when a change occur. Skips running <command> at startup
|
||||
```
|
||||
|
||||
It will watch the given `directory` and run the given <command> every time a file changes.
|
||||
|
||||
### CLI example usage
|
||||
- `sane 'echo "A command ran"'`
|
||||
- `sane 'echo "A command ran"' --glob='**/*.css'`
|
||||
- `sane 'echo "A command ran"' site/assets/css --glob='**/*.css'`
|
||||
- `sane 'echo "A command ran"' --glob='**/*.css' --ignored='**/ignore.css'`
|
||||
- `sane 'echo "A command ran"' --wait=3`
|
||||
- `sane 'echo "A command ran"' -p`
|
||||
|
||||
## License
|
||||
|
||||
MIT
|
||||
|
||||
## Credits
|
||||
The CLI was originally based on the [watch CLI](https://github.com/mikeal/watch). Watch is licensed under the Apache License Version 2.0.
|
||||
+40
@@ -0,0 +1,40 @@
|
||||
'use strict';
|
||||
|
||||
const NodeWatcher = require('./src/node_watcher');
|
||||
const PollWatcher = require('./src/poll_watcher');
|
||||
const WatchmanWatcher = require('./src/watchman_watcher');
|
||||
const WatchexecWatcher = require('./src/watchexec_watcher');
|
||||
|
||||
function throwNoFSEventsSupports() {
|
||||
throw new Error('Sane >= 4 no longer support the fsevents module.');
|
||||
}
|
||||
|
||||
function sane(dir, options) {
|
||||
options = options || {};
|
||||
if (options.watcher) {
|
||||
const WatcherClass = require(options.watcher);
|
||||
return new WatcherClass(dir, options);
|
||||
} else if (options.poll) {
|
||||
return new PollWatcher(dir, options);
|
||||
} else if (options.watchman) {
|
||||
return new WatchmanWatcher(dir, options);
|
||||
} else if (options.watchexec) {
|
||||
return new WatchexecWatcher(dir, options);
|
||||
} else if (options.fsevents) {
|
||||
throwNoFSEventsSupports();
|
||||
} else {
|
||||
return new NodeWatcher(dir, options);
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = sane;
|
||||
sane.NodeWatcher = NodeWatcher;
|
||||
sane.PollWatcher = PollWatcher;
|
||||
sane.WatchmanWatcher = WatchmanWatcher;
|
||||
sane.WatchexecWatcher = WatchexecWatcher;
|
||||
|
||||
Object.defineProperty(sane, 'FSEventsWatcher', {
|
||||
get() {
|
||||
return throwNoFSEventsSupports();
|
||||
},
|
||||
});
|
||||
+88
@@ -0,0 +1,88 @@
|
||||
{
|
||||
"_args": [
|
||||
[
|
||||
"[email protected]",
|
||||
"C:\\Users\\Administrator\\Documents\\setup-python"
|
||||
]
|
||||
],
|
||||
"_development": true,
|
||||
"_from": "[email protected]",
|
||||
"_id": "[email protected]",
|
||||
"_inBundle": false,
|
||||
"_integrity": "sha512-hhbzAgTIX8O7SHfp2c8/kREfEn4qO/9q8C9beyY6+tvZ87EpoZ3i1RIEvp27YBswnNbY9mWd6paKVmKbAgLfZA==",
|
||||
"_location": "/sane",
|
||||
"_phantomChildren": {},
|
||||
"_requested": {
|
||||
"type": "version",
|
||||
"registry": true,
|
||||
"raw": "[email protected]",
|
||||
"name": "sane",
|
||||
"escapedName": "sane",
|
||||
"rawSpec": "4.1.0",
|
||||
"saveSpec": null,
|
||||
"fetchSpec": "4.1.0"
|
||||
},
|
||||
"_requiredBy": [
|
||||
"/jest-haste-map"
|
||||
],
|
||||
"_resolved": "https://registry.npmjs.org/sane/-/sane-4.1.0.tgz",
|
||||
"_spec": "4.1.0",
|
||||
"_where": "C:\\Users\\Administrator\\Documents\\setup-python",
|
||||
"author": {
|
||||
"name": "amasad"
|
||||
},
|
||||
"bin": {
|
||||
"sane": "./src/cli.js"
|
||||
},
|
||||
"bugs": {
|
||||
"url": "https://github.com/amasad/sane/issues"
|
||||
},
|
||||
"dependencies": {
|
||||
"@cnakazawa/watch": "^1.0.3",
|
||||
"anymatch": "^2.0.0",
|
||||
"capture-exit": "^2.0.0",
|
||||
"exec-sh": "^0.3.2",
|
||||
"execa": "^1.0.0",
|
||||
"fb-watchman": "^2.0.0",
|
||||
"micromatch": "^3.1.4",
|
||||
"minimist": "^1.1.1",
|
||||
"walker": "~1.0.5"
|
||||
},
|
||||
"description": "Sane aims to be fast, small, and reliable file system watcher.",
|
||||
"devDependencies": {
|
||||
"eslint": "^5.15.1",
|
||||
"mocha": "^6.0.2",
|
||||
"prettier": "^1.16.4",
|
||||
"rimraf": "~2.6.3",
|
||||
"tmp": "0.0.33"
|
||||
},
|
||||
"engines": {
|
||||
"node": "6.* || 8.* || >= 10.*"
|
||||
},
|
||||
"files": [
|
||||
"src",
|
||||
"index.js"
|
||||
],
|
||||
"homepage": "https://github.com/amasad/sane",
|
||||
"keywords": [
|
||||
"watch",
|
||||
"file",
|
||||
"fswatcher",
|
||||
"watchfile",
|
||||
"fs",
|
||||
"watching"
|
||||
],
|
||||
"license": "MIT",
|
||||
"main": "index.js",
|
||||
"name": "sane",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/amasad/sane.git"
|
||||
},
|
||||
"scripts": {
|
||||
"format": "prettier --trailing-comma es5 --single-quote --write index.js 'src/**/*.js' 'test/**/*.js'",
|
||||
"test": "npm run format && eslint src/ test/ index.js && mocha --bail test/test.js && mocha --bail test/utils-test.js && mocha --bail 'test/watchexec_*-test.js'",
|
||||
"test:debug": "mocha debug --bail"
|
||||
},
|
||||
"version": "4.1.0"
|
||||
}
|
||||
+76
@@ -0,0 +1,76 @@
|
||||
#!/usr/bin/env node
|
||||
'use strict';
|
||||
|
||||
const sane = require('../');
|
||||
const argv = require('minimist')(process.argv.slice(2));
|
||||
const execshell = require('exec-sh');
|
||||
|
||||
if (argv._.length === 0) {
|
||||
const msg =
|
||||
'Usage: sane <command> [...directory] [--glob=<filePattern>] ' +
|
||||
'[--ignored=<filePattern>] [--poll] [--watchman] [--watchman-path=<watchmanBinaryPath>] [--dot] ' +
|
||||
'[--wait=<seconds>] [--only-changes] [--quiet]';
|
||||
console.error(msg);
|
||||
process.exit();
|
||||
}
|
||||
|
||||
const opts = {};
|
||||
const command = argv._[0];
|
||||
const dir = argv._[1] || process.cwd();
|
||||
const waitTime = Number(argv.wait || argv.w);
|
||||
const dot = argv.dot || argv.d;
|
||||
const glob = argv.glob || argv.g;
|
||||
const ignored = argv.ignored || argv.i;
|
||||
const poll = argv.poll || argv.p;
|
||||
const watchman = argv.watchman || argv.w;
|
||||
const watchmanPath = argv['watchman-path'];
|
||||
const onlyChanges = argv['only-changes'] | argv.o;
|
||||
const quiet = argv.quiet | argv.q;
|
||||
|
||||
if (dot) {
|
||||
opts.dot = true;
|
||||
}
|
||||
if (glob) {
|
||||
opts.glob = glob;
|
||||
}
|
||||
if (ignored) {
|
||||
opts.ignored = ignored;
|
||||
}
|
||||
if (poll) {
|
||||
opts.poll = true;
|
||||
}
|
||||
if (watchman) {
|
||||
opts.watchman = true;
|
||||
}
|
||||
if (watchmanPath) {
|
||||
opts.watchmanPath = watchmanPath;
|
||||
}
|
||||
|
||||
let wait = false;
|
||||
const watcher = sane(dir, opts);
|
||||
|
||||
watcher.on('ready', function() {
|
||||
if (!quiet) {
|
||||
console.log('Watching: ', dir + '/' + (opts.glob || ''));
|
||||
}
|
||||
if (!onlyChanges) {
|
||||
execshell(command);
|
||||
}
|
||||
});
|
||||
|
||||
watcher.on('change', function(filepath) {
|
||||
if (wait) {
|
||||
return;
|
||||
}
|
||||
if (!quiet) {
|
||||
console.log('Change detected in:', filepath);
|
||||
}
|
||||
execshell(command);
|
||||
|
||||
if (waitTime > 0) {
|
||||
wait = true;
|
||||
setTimeout(function() {
|
||||
wait = false;
|
||||
}, waitTime * 1000);
|
||||
}
|
||||
});
|
||||
+110
@@ -0,0 +1,110 @@
|
||||
'use strict';
|
||||
|
||||
const walker = require('walker');
|
||||
const anymatch = require('anymatch');
|
||||
const micromatch = require('micromatch');
|
||||
const path = require('path');
|
||||
const platform = require('os').platform();
|
||||
|
||||
/**
|
||||
* Constants
|
||||
*/
|
||||
|
||||
exports.DEFAULT_DELAY = 100;
|
||||
exports.CHANGE_EVENT = 'change';
|
||||
exports.DELETE_EVENT = 'delete';
|
||||
exports.ADD_EVENT = 'add';
|
||||
exports.ALL_EVENT = 'all';
|
||||
|
||||
/**
|
||||
* Assigns options to the watcher.
|
||||
*
|
||||
* @param {NodeWatcher|PollWatcher|WatchmanWatcher} watcher
|
||||
* @param {?object} opts
|
||||
* @return {boolean}
|
||||
* @public
|
||||
*/
|
||||
|
||||
exports.assignOptions = function(watcher, opts) {
|
||||
opts = opts || {};
|
||||
watcher.globs = opts.glob || [];
|
||||
watcher.dot = opts.dot || false;
|
||||
watcher.ignored = opts.ignored || false;
|
||||
|
||||
if (!Array.isArray(watcher.globs)) {
|
||||
watcher.globs = [watcher.globs];
|
||||
}
|
||||
watcher.hasIgnore =
|
||||
Boolean(opts.ignored) && !(Array.isArray(opts) && opts.length > 0);
|
||||
watcher.doIgnore = opts.ignored ? anymatch(opts.ignored) : () => false;
|
||||
|
||||
if (opts.watchman && opts.watchmanPath) {
|
||||
watcher.watchmanPath = opts.watchmanPath;
|
||||
}
|
||||
|
||||
return opts;
|
||||
};
|
||||
|
||||
/**
|
||||
* Checks a file relative path against the globs array.
|
||||
*
|
||||
* @param {array} globs
|
||||
* @param {string} relativePath
|
||||
* @return {boolean}
|
||||
* @public
|
||||
*/
|
||||
|
||||
exports.isFileIncluded = function(globs, dot, doIgnore, relativePath) {
|
||||
if (doIgnore(relativePath)) {
|
||||
return false;
|
||||
}
|
||||
return globs.length
|
||||
? micromatch.some(relativePath, globs, { dot: dot })
|
||||
: dot || micromatch.some(relativePath, '**/*');
|
||||
};
|
||||
|
||||
/**
|
||||
* Traverse a directory recursively calling `callback` on every directory.
|
||||
*
|
||||
* @param {string} dir
|
||||
* @param {function} dirCallback
|
||||
* @param {function} fileCallback
|
||||
* @param {function} endCallback
|
||||
* @param {*} ignored
|
||||
* @public
|
||||
*/
|
||||
|
||||
exports.recReaddir = function(
|
||||
dir,
|
||||
dirCallback,
|
||||
fileCallback,
|
||||
endCallback,
|
||||
errorCallback,
|
||||
ignored
|
||||
) {
|
||||
walker(dir)
|
||||
.filterDir(currentDir => !anymatch(ignored, currentDir))
|
||||
.on('dir', normalizeProxy(dirCallback))
|
||||
.on('file', normalizeProxy(fileCallback))
|
||||
.on('error', errorCallback)
|
||||
.on('end', () => {
|
||||
if (platform === 'win32') {
|
||||
setTimeout(endCallback, 1000);
|
||||
} else {
|
||||
endCallback();
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
/**
|
||||
* Returns a callback that when called will normalize a path and call the
|
||||
* original callback
|
||||
*
|
||||
* @param {function} callback
|
||||
* @return {function}
|
||||
* @private
|
||||
*/
|
||||
|
||||
function normalizeProxy(callback) {
|
||||
return (filepath, stats) => callback(path.normalize(filepath), stats);
|
||||
}
|
||||
+398
@@ -0,0 +1,398 @@
|
||||
'use strict';
|
||||
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
const common = require('./common');
|
||||
const platform = require('os').platform();
|
||||
const EventEmitter = require('events').EventEmitter;
|
||||
|
||||
/**
|
||||
* Constants
|
||||
*/
|
||||
|
||||
const DEFAULT_DELAY = common.DEFAULT_DELAY;
|
||||
const CHANGE_EVENT = common.CHANGE_EVENT;
|
||||
const DELETE_EVENT = common.DELETE_EVENT;
|
||||
const ADD_EVENT = common.ADD_EVENT;
|
||||
const ALL_EVENT = common.ALL_EVENT;
|
||||
|
||||
/**
|
||||
* Export `NodeWatcher` class.
|
||||
* Watches `dir`.
|
||||
*
|
||||
* @class NodeWatcher
|
||||
* @param {String} dir
|
||||
* @param {Object} opts
|
||||
* @public
|
||||
*/
|
||||
|
||||
module.exports = class NodeWatcher extends EventEmitter {
|
||||
constructor(dir, opts) {
|
||||
super();
|
||||
|
||||
common.assignOptions(this, opts);
|
||||
|
||||
this.watched = Object.create(null);
|
||||
this.changeTimers = Object.create(null);
|
||||
this.dirRegistery = Object.create(null);
|
||||
this.root = path.resolve(dir);
|
||||
this.watchdir = this.watchdir.bind(this);
|
||||
this.register = this.register.bind(this);
|
||||
this.checkedEmitError = this.checkedEmitError.bind(this);
|
||||
|
||||
this.watchdir(this.root);
|
||||
common.recReaddir(
|
||||
this.root,
|
||||
this.watchdir,
|
||||
this.register,
|
||||
this.emit.bind(this, 'ready'),
|
||||
this.checkedEmitError,
|
||||
this.ignored
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Register files that matches our globs to know what to type of event to
|
||||
* emit in the future.
|
||||
*
|
||||
* Registery looks like the following:
|
||||
*
|
||||
* dirRegister => Map {
|
||||
* dirpath => Map {
|
||||
* filename => true
|
||||
* }
|
||||
* }
|
||||
*
|
||||
* @param {string} filepath
|
||||
* @return {boolean} whether or not we have registered the file.
|
||||
* @private
|
||||
*/
|
||||
|
||||
register(filepath) {
|
||||
let relativePath = path.relative(this.root, filepath);
|
||||
if (
|
||||
!common.isFileIncluded(this.globs, this.dot, this.doIgnore, relativePath)
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
|
||||
let dir = path.dirname(filepath);
|
||||
if (!this.dirRegistery[dir]) {
|
||||
this.dirRegistery[dir] = Object.create(null);
|
||||
}
|
||||
|
||||
let filename = path.basename(filepath);
|
||||
this.dirRegistery[dir][filename] = true;
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Removes a file from the registery.
|
||||
*
|
||||
* @param {string} filepath
|
||||
* @private
|
||||
*/
|
||||
|
||||
unregister(filepath) {
|
||||
let dir = path.dirname(filepath);
|
||||
if (this.dirRegistery[dir]) {
|
||||
let filename = path.basename(filepath);
|
||||
delete this.dirRegistery[dir][filename];
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Removes a dir from the registery.
|
||||
*
|
||||
* @param {string} dirpath
|
||||
* @private
|
||||
*/
|
||||
|
||||
unregisterDir(dirpath) {
|
||||
if (this.dirRegistery[dirpath]) {
|
||||
delete this.dirRegistery[dirpath];
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if a file or directory exists in the registery.
|
||||
*
|
||||
* @param {string} fullpath
|
||||
* @return {boolean}
|
||||
* @private
|
||||
*/
|
||||
|
||||
registered(fullpath) {
|
||||
let dir = path.dirname(fullpath);
|
||||
return (
|
||||
this.dirRegistery[fullpath] ||
|
||||
(this.dirRegistery[dir] &&
|
||||
this.dirRegistery[dir][path.basename(fullpath)])
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Emit "error" event if it's not an ignorable event
|
||||
*
|
||||
* @param error
|
||||
* @private
|
||||
*/
|
||||
checkedEmitError(error) {
|
||||
if (!isIgnorableFileError(error)) {
|
||||
this.emit('error', error);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Watch a directory.
|
||||
*
|
||||
* @param {string} dir
|
||||
* @private
|
||||
*/
|
||||
|
||||
watchdir(dir) {
|
||||
if (this.watched[dir]) {
|
||||
return;
|
||||
}
|
||||
|
||||
let watcher = fs.watch(
|
||||
dir,
|
||||
{ persistent: true },
|
||||
this.normalizeChange.bind(this, dir)
|
||||
);
|
||||
this.watched[dir] = watcher;
|
||||
|
||||
watcher.on('error', this.checkedEmitError);
|
||||
|
||||
if (this.root !== dir) {
|
||||
this.register(dir);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Stop watching a directory.
|
||||
*
|
||||
* @param {string} dir
|
||||
* @private
|
||||
*/
|
||||
|
||||
stopWatching(dir) {
|
||||
if (this.watched[dir]) {
|
||||
this.watched[dir].close();
|
||||
delete this.watched[dir];
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* End watching.
|
||||
*
|
||||
* @public
|
||||
*/
|
||||
|
||||
close(callback) {
|
||||
Object.keys(this.watched).forEach(this.stopWatching, this);
|
||||
this.removeAllListeners();
|
||||
if (typeof callback === 'function') {
|
||||
setImmediate(callback.bind(null, null, true));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* On some platforms, as pointed out on the fs docs (most likely just win32)
|
||||
* the file argument might be missing from the fs event. Try to detect what
|
||||
* change by detecting if something was deleted or the most recent file change.
|
||||
*
|
||||
* @param {string} dir
|
||||
* @param {string} event
|
||||
* @param {string} file
|
||||
* @public
|
||||
*/
|
||||
|
||||
detectChangedFile(dir, event, callback) {
|
||||
if (!this.dirRegistery[dir]) {
|
||||
return;
|
||||
}
|
||||
|
||||
let found = false;
|
||||
let closest = { mtime: 0 };
|
||||
let c = 0;
|
||||
Object.keys(this.dirRegistery[dir]).forEach(function(file, i, arr) {
|
||||
fs.lstat(
|
||||
path.join(dir, file),
|
||||
function(error, stat) {
|
||||
if (found) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (error) {
|
||||
if (isIgnorableFileError(error)) {
|
||||
found = true;
|
||||
callback(file);
|
||||
} else {
|
||||
this.emit('error', error);
|
||||
}
|
||||
} else {
|
||||
if (stat.mtime > closest.mtime) {
|
||||
stat.file = file;
|
||||
closest = stat;
|
||||
}
|
||||
if (arr.length === ++c) {
|
||||
callback(closest.file);
|
||||
}
|
||||
}
|
||||
}.bind(this)
|
||||
);
|
||||
}, this);
|
||||
}
|
||||
|
||||
/**
|
||||
* Normalize fs events and pass it on to be processed.
|
||||
*
|
||||
* @param {string} dir
|
||||
* @param {string} event
|
||||
* @param {string} file
|
||||
* @public
|
||||
*/
|
||||
|
||||
normalizeChange(dir, event, file) {
|
||||
if (!file) {
|
||||
this.detectChangedFile(
|
||||
dir,
|
||||
event,
|
||||
function(actualFile) {
|
||||
if (actualFile) {
|
||||
this.processChange(dir, event, actualFile);
|
||||
}
|
||||
}.bind(this)
|
||||
);
|
||||
} else {
|
||||
this.processChange(dir, event, path.normalize(file));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Process changes.
|
||||
*
|
||||
* @param {string} dir
|
||||
* @param {string} event
|
||||
* @param {string} file
|
||||
* @public
|
||||
*/
|
||||
|
||||
processChange(dir, event, file) {
|
||||
let fullPath = path.join(dir, file);
|
||||
let relativePath = path.join(path.relative(this.root, dir), file);
|
||||
|
||||
fs.lstat(
|
||||
fullPath,
|
||||
function(error, stat) {
|
||||
if (error && error.code !== 'ENOENT') {
|
||||
this.emit('error', error);
|
||||
} else if (!error && stat.isDirectory()) {
|
||||
// win32 emits usless change events on dirs.
|
||||
if (event !== 'change') {
|
||||
this.watchdir(fullPath);
|
||||
if (
|
||||
common.isFileIncluded(
|
||||
this.globs,
|
||||
this.dot,
|
||||
this.doIgnore,
|
||||
relativePath
|
||||
)
|
||||
) {
|
||||
this.emitEvent(ADD_EVENT, relativePath, stat);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
let registered = this.registered(fullPath);
|
||||
if (error && error.code === 'ENOENT') {
|
||||
this.unregister(fullPath);
|
||||
this.stopWatching(fullPath);
|
||||
this.unregisterDir(fullPath);
|
||||
if (registered) {
|
||||
this.emitEvent(DELETE_EVENT, relativePath);
|
||||
}
|
||||
} else if (registered) {
|
||||
this.emitEvent(CHANGE_EVENT, relativePath, stat);
|
||||
} else {
|
||||
if (this.register(fullPath)) {
|
||||
this.emitEvent(ADD_EVENT, relativePath, stat);
|
||||
}
|
||||
}
|
||||
}
|
||||
}.bind(this)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Triggers a 'change' event after debounding it to take care of duplicate
|
||||
* events on os x.
|
||||
*
|
||||
* @private
|
||||
*/
|
||||
|
||||
emitEvent(type, file, stat) {
|
||||
let key = type + '-' + file;
|
||||
let addKey = ADD_EVENT + '-' + file;
|
||||
if (type === CHANGE_EVENT && this.changeTimers[addKey]) {
|
||||
// Ignore the change event that is immediately fired after an add event.
|
||||
// (This happens on Linux).
|
||||
return;
|
||||
}
|
||||
clearTimeout(this.changeTimers[key]);
|
||||
this.changeTimers[key] = setTimeout(
|
||||
function() {
|
||||
delete this.changeTimers[key];
|
||||
if (type === ADD_EVENT && stat.isDirectory()) {
|
||||
// Recursively emit add events and watch for sub-files/folders
|
||||
common.recReaddir(
|
||||
path.resolve(this.root, file),
|
||||
function emitAddDir(dir, stats) {
|
||||
this.watchdir(dir);
|
||||
this.rawEmitEvent(
|
||||
ADD_EVENT,
|
||||
path.relative(this.root, dir),
|
||||
stats
|
||||
);
|
||||
}.bind(this),
|
||||
function emitAddFile(file, stats) {
|
||||
this.register(file);
|
||||
this.rawEmitEvent(
|
||||
ADD_EVENT,
|
||||
path.relative(this.root, file),
|
||||
stats
|
||||
);
|
||||
}.bind(this),
|
||||
function endCallback() {},
|
||||
this.checkedEmitError,
|
||||
this.ignored
|
||||
);
|
||||
} else {
|
||||
this.rawEmitEvent(type, file, stat);
|
||||
}
|
||||
}.bind(this),
|
||||
DEFAULT_DELAY
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Actually emit the events
|
||||
*/
|
||||
rawEmitEvent(type, file, stat) {
|
||||
this.emit(type, file, this.root, stat);
|
||||
this.emit(ALL_EVENT, type, file, this.root, stat);
|
||||
}
|
||||
};
|
||||
/**
|
||||
* Determine if a given FS error can be ignored
|
||||
*
|
||||
* @private
|
||||
*/
|
||||
function isIgnorableFileError(error) {
|
||||
return (
|
||||
error.code === 'ENOENT' ||
|
||||
// Workaround Windows node issue #4337.
|
||||
(error.code === 'EPERM' && platform === 'win32')
|
||||
);
|
||||
}
|
||||
+117
@@ -0,0 +1,117 @@
|
||||
'use strict';
|
||||
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
const watch = require('@cnakazawa/watch');
|
||||
const common = require('./common');
|
||||
const EventEmitter = require('events').EventEmitter;
|
||||
|
||||
/**
|
||||
* Constants
|
||||
*/
|
||||
|
||||
const DEFAULT_DELAY = common.DEFAULT_DELAY;
|
||||
const CHANGE_EVENT = common.CHANGE_EVENT;
|
||||
const DELETE_EVENT = common.DELETE_EVENT;
|
||||
const ADD_EVENT = common.ADD_EVENT;
|
||||
const ALL_EVENT = common.ALL_EVENT;
|
||||
|
||||
/**
|
||||
* Export `PollWatcher` class.
|
||||
* Watches `dir`.
|
||||
*
|
||||
* @class PollWatcher
|
||||
* @param String dir
|
||||
* @param {Object} opts
|
||||
* @public
|
||||
*/
|
||||
|
||||
module.exports = class PollWatcher extends EventEmitter {
|
||||
constructor(dir, opts) {
|
||||
super();
|
||||
|
||||
opts = common.assignOptions(this, opts);
|
||||
|
||||
this.watched = Object.create(null);
|
||||
this.root = path.resolve(dir);
|
||||
|
||||
watch.createMonitor(
|
||||
this.root,
|
||||
{
|
||||
interval: (opts.interval || DEFAULT_DELAY) / 1000,
|
||||
filter: this.filter.bind(this),
|
||||
},
|
||||
this.init.bind(this)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Given a fullpath of a file or directory check if we need to watch it.
|
||||
*
|
||||
* @param {string} filepath
|
||||
* @param {object} stat
|
||||
* @private
|
||||
*/
|
||||
|
||||
filter(filepath, stat) {
|
||||
return (
|
||||
stat.isDirectory() ||
|
||||
common.isFileIncluded(
|
||||
this.globs,
|
||||
this.dot,
|
||||
this.doIgnore,
|
||||
path.relative(this.root, filepath)
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Initiate the polling file watcher with the event emitter passed from
|
||||
* `watch.watchTree`.
|
||||
*
|
||||
* @param {EventEmitter} monitor
|
||||
* @public
|
||||
*/
|
||||
|
||||
init(monitor) {
|
||||
this.watched = monitor.files;
|
||||
monitor.on('changed', this.emitEvent.bind(this, CHANGE_EVENT));
|
||||
monitor.on('removed', this.emitEvent.bind(this, DELETE_EVENT));
|
||||
monitor.on('created', this.emitEvent.bind(this, ADD_EVENT));
|
||||
// 1 second wait because mtime is second-based.
|
||||
setTimeout(this.emit.bind(this, 'ready'), 1000);
|
||||
}
|
||||
|
||||
/**
|
||||
* Transform and emit an event comming from the poller.
|
||||
*
|
||||
* @param {EventEmitter} monitor
|
||||
* @public
|
||||
*/
|
||||
|
||||
emitEvent(type, file, stat) {
|
||||
file = path.relative(this.root, file);
|
||||
|
||||
if (type === DELETE_EVENT) {
|
||||
// Matching the non-polling API
|
||||
stat = null;
|
||||
}
|
||||
|
||||
this.emit(type, file, this.root, stat);
|
||||
this.emit(ALL_EVENT, type, file, this.root, stat);
|
||||
}
|
||||
|
||||
/**
|
||||
* End watching.
|
||||
*
|
||||
* @public
|
||||
*/
|
||||
|
||||
close(callback) {
|
||||
Object.keys(this.watched).forEach(filepath => fs.unwatchFile(filepath));
|
||||
this.removeAllListeners();
|
||||
if (typeof callback === 'function') {
|
||||
setImmediate(callback.bind(null, null, true));
|
||||
}
|
||||
}
|
||||
};
|
||||
+51
@@ -0,0 +1,51 @@
|
||||
'use strict';
|
||||
|
||||
class RecrawlWarning {
|
||||
constructor(root, count) {
|
||||
this.root = root;
|
||||
this.count = count;
|
||||
}
|
||||
|
||||
static findByRoot(root) {
|
||||
for (let i = 0; i < this.RECRAWL_WARNINGS.length; i++) {
|
||||
let warning = this.RECRAWL_WARNINGS[i];
|
||||
if (warning.root === root) {
|
||||
return warning;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static isRecrawlWarningDupe(warningMessage) {
|
||||
if (typeof warningMessage !== 'string') {
|
||||
return false;
|
||||
}
|
||||
let match = warningMessage.match(this.REGEXP);
|
||||
if (!match) {
|
||||
return false;
|
||||
}
|
||||
let count = Number(match[1]);
|
||||
let root = match[2];
|
||||
|
||||
let warning = this.findByRoot(root);
|
||||
|
||||
if (warning) {
|
||||
// only keep the highest count, assume count to either stay the same or
|
||||
// increase.
|
||||
if (warning.count >= count) {
|
||||
return true;
|
||||
} else {
|
||||
// update the existing warning to the latest (highest) count
|
||||
warning.count = count;
|
||||
return false;
|
||||
}
|
||||
} else {
|
||||
this.RECRAWL_WARNINGS.push(new RecrawlWarning(root, count));
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
RecrawlWarning.RECRAWL_WARNINGS = [];
|
||||
RecrawlWarning.REGEXP = /Recrawled this watch (\d+) times, most recently because:\n([^:]+)/;
|
||||
|
||||
module.exports = RecrawlWarning;
|
||||
+63
@@ -0,0 +1,63 @@
|
||||
/*
|
||||
This file is the executable run by watchexec
|
||||
when a change is detected.
|
||||
|
||||
It will extract changes from the environment variables
|
||||
set by watchexec and write to stdout in a format
|
||||
readable by the file `../watchexec_watcher.js`.
|
||||
*/
|
||||
'use strict';
|
||||
|
||||
const { EOL } = require('os');
|
||||
|
||||
function withPrefixes(prefixes) {
|
||||
return function withPrefix(arr, i) {
|
||||
return arr.map(str => {
|
||||
return `${prefixes[i]} ${str}`;
|
||||
});
|
||||
};
|
||||
}
|
||||
|
||||
let allPrefixes = ['write', 'rename', 'remove', 'create'];
|
||||
|
||||
function extractChanges(context) {
|
||||
const {
|
||||
WATCHEXEC_COMMON_PATH,
|
||||
WATCHEXEC_WRITTEN_PATH,
|
||||
WATCHEXEC_RENAMED_PATH,
|
||||
WATCHEXEC_REMOVED_PATH,
|
||||
WATCHEXEC_CREATED_PATH,
|
||||
} = context;
|
||||
|
||||
let events = [
|
||||
WATCHEXEC_WRITTEN_PATH,
|
||||
WATCHEXEC_RENAMED_PATH,
|
||||
WATCHEXEC_REMOVED_PATH,
|
||||
WATCHEXEC_CREATED_PATH,
|
||||
];
|
||||
|
||||
let currentPrefixes = events
|
||||
.map((l, i) => l && allPrefixes[i])
|
||||
.filter(Boolean);
|
||||
|
||||
function toFullPath(arr) {
|
||||
return arr.map(path => (WATCHEXEC_COMMON_PATH || '') + path);
|
||||
}
|
||||
|
||||
let message = events
|
||||
.filter(Boolean)
|
||||
.map(str => str.split(':'))
|
||||
.map(toFullPath)
|
||||
.map(withPrefixes(currentPrefixes))
|
||||
.reduce((e, memo) => memo.concat(e), [])
|
||||
.join(EOL);
|
||||
|
||||
return message;
|
||||
}
|
||||
|
||||
if (require.main === module) {
|
||||
let message = extractChanges(process.env);
|
||||
console.log(message);
|
||||
}
|
||||
|
||||
module.exports = extractChanges;
|
||||
+116
@@ -0,0 +1,116 @@
|
||||
'use strict';
|
||||
|
||||
const execa = require('execa');
|
||||
|
||||
const { statSync } = require('fs');
|
||||
const path = require('path');
|
||||
const common = require('./common');
|
||||
const EventEmitter = require('events').EventEmitter;
|
||||
|
||||
const { EOL } = require('os');
|
||||
|
||||
/**
|
||||
* Constants
|
||||
*/
|
||||
|
||||
const CHANGE_EVENT = common.CHANGE_EVENT;
|
||||
const DELETE_EVENT = common.DELETE_EVENT;
|
||||
const ADD_EVENT = common.ADD_EVENT;
|
||||
const ALL_EVENT = common.ALL_EVENT;
|
||||
|
||||
const typeMap = {
|
||||
rename: CHANGE_EVENT,
|
||||
write: CHANGE_EVENT,
|
||||
remove: DELETE_EVENT,
|
||||
create: ADD_EVENT,
|
||||
};
|
||||
|
||||
const messageRegexp = /(rename|write|remove|create)\s(.+)/;
|
||||
|
||||
/**
|
||||
* Manages streams from subprocess and turns into sane events
|
||||
*
|
||||
* @param {Stream} data
|
||||
* @private
|
||||
*/
|
||||
function _messageHandler(data) {
|
||||
data
|
||||
.toString()
|
||||
.split(EOL)
|
||||
.filter(str => str.trim().length)
|
||||
.filter(str => messageRegexp.test(str))
|
||||
.map(line => {
|
||||
const [, command, path] = [...line.match(messageRegexp)];
|
||||
return [command, path];
|
||||
})
|
||||
.forEach(([command, file]) => {
|
||||
let stat;
|
||||
const type = typeMap[command];
|
||||
if (type === DELETE_EVENT) {
|
||||
stat = null;
|
||||
} else {
|
||||
try {
|
||||
stat = statSync(file);
|
||||
} catch (e) {
|
||||
// There is likely a delete coming down the pipe.
|
||||
if (e.code === 'ENOENT') {
|
||||
return;
|
||||
}
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
this.emitEvent(type, path.relative(this.root, file), stat);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Export `WatchexecWatcher` class.
|
||||
* Watches `dir`.
|
||||
*
|
||||
* @class WatchexecWatcher
|
||||
* @param String dir
|
||||
* @param {Object} opts
|
||||
* @public
|
||||
*/
|
||||
class WatchexecWatcher extends EventEmitter {
|
||||
constructor(dir, opts) {
|
||||
super();
|
||||
|
||||
common.assignOptions(this, opts);
|
||||
|
||||
this.root = path.resolve(dir);
|
||||
|
||||
this._process = execa(
|
||||
'watchexec',
|
||||
['-n', '--', 'node', __dirname + '/watchexec_client.js'],
|
||||
{ cwd: dir }
|
||||
);
|
||||
|
||||
this._process.stdout.on('data', _messageHandler.bind(this));
|
||||
this._readyTimer = setTimeout(this.emit.bind(this, 'ready'), 1000);
|
||||
}
|
||||
|
||||
close(callback) {
|
||||
clearTimeout(this._readyTimer);
|
||||
this.removeAllListeners();
|
||||
this._process && !this._process.killed && this._process.kill();
|
||||
if (typeof callback === 'function') {
|
||||
setImmediate(callback.bind(null, null, true));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Transform and emit an event comming from the poller.
|
||||
*
|
||||
* @param {EventEmitter} monitor
|
||||
* @public
|
||||
*/
|
||||
emitEvent(type, file, stat) {
|
||||
this.emit(type, file, this.root, stat);
|
||||
this.emit(ALL_EVENT, type, file, this.root, stat);
|
||||
}
|
||||
}
|
||||
|
||||
WatchexecWatcher._messageHandler = _messageHandler;
|
||||
|
||||
module.exports = WatchexecWatcher;
|
||||
+525
File diff suppressed because it is too large
Load Diff
+249
@@ -0,0 +1,249 @@
|
||||
'use strict';
|
||||
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
const common = require('./common');
|
||||
const watchmanClient = require('./watchman_client');
|
||||
const EventEmitter = require('events').EventEmitter;
|
||||
const RecrawlWarning = require('./utils/recrawl-warning-dedupe');
|
||||
|
||||
/**
|
||||
* Constants
|
||||
*/
|
||||
|
||||
const CHANGE_EVENT = common.CHANGE_EVENT;
|
||||
const DELETE_EVENT = common.DELETE_EVENT;
|
||||
const ADD_EVENT = common.ADD_EVENT;
|
||||
const ALL_EVENT = common.ALL_EVENT;
|
||||
|
||||
/**
|
||||
* Export `WatchmanWatcher` class.
|
||||
*/
|
||||
|
||||
module.exports = WatchmanWatcher;
|
||||
|
||||
/**
|
||||
* Watches `dir`.
|
||||
*
|
||||
* @class WatchmanWatcher
|
||||
* @param String dir
|
||||
* @param {Object} opts
|
||||
* @public
|
||||
*/
|
||||
|
||||
function WatchmanWatcher(dir, opts) {
|
||||
common.assignOptions(this, opts);
|
||||
this.root = path.resolve(dir);
|
||||
this._init();
|
||||
}
|
||||
|
||||
WatchmanWatcher.prototype.__proto__ = EventEmitter.prototype;
|
||||
|
||||
/**
|
||||
* Run the watchman `watch` command on the root and subscribe to changes.
|
||||
*
|
||||
* @private
|
||||
*/
|
||||
WatchmanWatcher.prototype._init = function() {
|
||||
if (this._client) {
|
||||
this._client = null;
|
||||
}
|
||||
|
||||
// Get the WatchmanClient instance corresponding to our watchmanPath (or nothing).
|
||||
// Then subscribe, which will do the appropriate setup so that we will receive
|
||||
// calls to handleChangeEvent when files change.
|
||||
this._client = watchmanClient.getInstance(this.watchmanPath);
|
||||
|
||||
return this._client.subscribe(this, this.root).then(
|
||||
resp => {
|
||||
this._handleWarning(resp);
|
||||
this.emit('ready');
|
||||
},
|
||||
error => {
|
||||
this._handleError(error);
|
||||
}
|
||||
);
|
||||
};
|
||||
|
||||
/**
|
||||
* Called by WatchmanClient to create the options, either during initial 'subscribe'
|
||||
* or to resubscribe after a disconnect+reconnect. Note that we are leaving out
|
||||
* the watchman 'since' and 'relative_root' options, which are handled inside the
|
||||
* WatchmanClient.
|
||||
*/
|
||||
WatchmanWatcher.prototype.createOptions = function() {
|
||||
let options = {
|
||||
fields: ['name', 'exists', 'new'],
|
||||
};
|
||||
|
||||
// If the server has the wildmatch capability available it supports
|
||||
// the recursive **/*.foo style match and we can offload our globs
|
||||
// to the watchman server. This saves both on data size to be
|
||||
// communicated back to us and compute for evaluating the globs
|
||||
// in our node process.
|
||||
if (this._client.wildmatch) {
|
||||
if (this.globs.length === 0) {
|
||||
if (!this.dot) {
|
||||
// Make sure we honor the dot option if even we're not using globs.
|
||||
options.expression = [
|
||||
'match',
|
||||
'**',
|
||||
'wholename',
|
||||
{
|
||||
includedotfiles: false,
|
||||
},
|
||||
];
|
||||
}
|
||||
} else {
|
||||
options.expression = ['anyof'];
|
||||
for (let i in this.globs) {
|
||||
options.expression.push([
|
||||
'match',
|
||||
this.globs[i],
|
||||
'wholename',
|
||||
{
|
||||
includedotfiles: this.dot,
|
||||
},
|
||||
]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return options;
|
||||
};
|
||||
|
||||
/**
|
||||
* Called by WatchmanClient when it receives an error from the watchman daemon.
|
||||
*
|
||||
* @param {Object} resp
|
||||
*/
|
||||
WatchmanWatcher.prototype.handleErrorEvent = function(error) {
|
||||
this.emit('error', error);
|
||||
};
|
||||
|
||||
/**
|
||||
* Called by the WatchmanClient when it is notified about a file change in
|
||||
* the tree for this particular watcher's root.
|
||||
*
|
||||
* @param {Object} resp
|
||||
* @private
|
||||
*/
|
||||
|
||||
WatchmanWatcher.prototype.handleChangeEvent = function(resp) {
|
||||
if (Array.isArray(resp.files)) {
|
||||
resp.files.forEach(this.handleFileChange, this);
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Handles a single change event record.
|
||||
*
|
||||
* @param {Object} changeDescriptor
|
||||
* @private
|
||||
*/
|
||||
|
||||
WatchmanWatcher.prototype.handleFileChange = function(changeDescriptor) {
|
||||
let absPath;
|
||||
let relativePath;
|
||||
|
||||
relativePath = changeDescriptor.name;
|
||||
absPath = path.join(this.root, relativePath);
|
||||
|
||||
if (
|
||||
!(this._client.wildmatch && !this.hasIgnore) &&
|
||||
!common.isFileIncluded(this.globs, this.dot, this.doIgnore, relativePath)
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (!changeDescriptor.exists) {
|
||||
this.emitEvent(DELETE_EVENT, relativePath, this.root);
|
||||
} else {
|
||||
fs.lstat(absPath, (error, stat) => {
|
||||
// Files can be deleted between the event and the lstat call
|
||||
// the most reliable thing to do here is to ignore the event.
|
||||
if (error && error.code === 'ENOENT') {
|
||||
return;
|
||||
}
|
||||
|
||||
if (this._handleError(error)) {
|
||||
return;
|
||||
}
|
||||
|
||||
let eventType = changeDescriptor.new ? ADD_EVENT : CHANGE_EVENT;
|
||||
|
||||
// Change event on dirs are mostly useless.
|
||||
if (!(eventType === CHANGE_EVENT && stat.isDirectory())) {
|
||||
this.emitEvent(eventType, relativePath, this.root, stat);
|
||||
}
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Dispatches an event.
|
||||
*
|
||||
* @param {string} eventType
|
||||
* @param {string} filepath
|
||||
* @param {string} root
|
||||
* @param {fs.Stat} stat
|
||||
* @private
|
||||
*/
|
||||
|
||||
WatchmanWatcher.prototype.emitEvent = function(
|
||||
eventType,
|
||||
filepath,
|
||||
root,
|
||||
stat
|
||||
) {
|
||||
this.emit(eventType, filepath, root, stat);
|
||||
this.emit(ALL_EVENT, eventType, filepath, root, stat);
|
||||
};
|
||||
|
||||
/**
|
||||
* Closes the watcher.
|
||||
*
|
||||
* @param {function} callback
|
||||
* @private
|
||||
*/
|
||||
|
||||
WatchmanWatcher.prototype.close = function(callback) {
|
||||
this._client.closeWatcher(this);
|
||||
callback && callback(null, true);
|
||||
};
|
||||
|
||||
/**
|
||||
* Handles an error and returns true if exists.
|
||||
*
|
||||
* @param {WatchmanWatcher} self
|
||||
* @param {Error} error
|
||||
* @private
|
||||
*/
|
||||
|
||||
WatchmanWatcher.prototype._handleError = function(error) {
|
||||
if (error != null) {
|
||||
this.emit('error', error);
|
||||
return true;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Handles a warning in the watchman resp object.
|
||||
*
|
||||
* @param {object} resp
|
||||
* @private
|
||||
*/
|
||||
|
||||
WatchmanWatcher.prototype._handleWarning = function(resp) {
|
||||
if ('warning' in resp) {
|
||||
if (RecrawlWarning.isRecrawlWarningDupe(resp.warning)) {
|
||||
return true;
|
||||
}
|
||||
console.warn(resp.warning);
|
||||
return true;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
};
|
||||
Reference in New Issue
Block a user