3 var fs = require('fs');
4 var sysPath = require('path');
5 var readdirp = require('readdirp');
7 try { fsevents = require('fsevents'); } catch (error) {}
9 // fsevents instance helper functions
11 // object to hold per-process fsevents instances
12 // (may be shared across chokidar FSWatcher instances)
13 var FSEventsWatchers = Object.create(null);
15 // Threshold of duplicate path prefixes at which to start
16 // consolidating going forward
17 var consolidateThreshhold = 10;
19 // Private function: Instantiates the fsevents interface
21 // * path - string, path to be watched
22 // * callback - function, called when fsevents is bound and ready
24 // Returns new fsevents instance
25 function createFSEventsInstance(path, callback) {
26 return (new fsevents(path)).on('fsevent', callback).start();
29 // Private function: Instantiates the fsevents interface or binds listeners
30 // to an existing one covering the same file tree
32 // * path - string, path to be watched
33 // * realPath - string, real path (in case of symlinks)
34 // * listener - function, called when fsevents emits events
35 // * rawEmitter - function, passes data to listeners of the 'raw' event
37 // Returns close function
38 function setFSEventsListener(path, realPath, listener, rawEmitter) {
39 var watchPath = sysPath.extname(path) ? sysPath.dirname(path) : path;
41 var parentPath = sysPath.dirname(watchPath);
43 // If we've accumulated a substantial number of paths that
44 // could have been consolidated by watching one directory
45 // above the current one, create a watcher on the parent
46 // path instead, so that we do consolidate going forward.
47 if (couldConsolidate(parentPath)) {
48 watchPath = parentPath;
51 var resolvedPath = sysPath.resolve(path);
52 var hasSymlink = resolvedPath !== realPath;
53 function filteredListener(fullPath, flags, info) {
54 if (hasSymlink) fullPath = fullPath.replace(realPath, resolvedPath);
56 fullPath === resolvedPath ||
57 !fullPath.indexOf(resolvedPath + sysPath.sep)
58 ) listener(fullPath, flags, info);
61 // check if there is already a watcher on a parent path
62 // modifies `watchPath` to the parent path when it finds a match
63 function watchedParent() {
64 return Object.keys(FSEventsWatchers).some(function(watchedPath) {
65 // condition is met when indexOf returns 0
66 if (!realPath.indexOf(sysPath.resolve(watchedPath) + sysPath.sep)) {
67 watchPath = watchedPath;
73 if (watchPath in FSEventsWatchers || watchedParent()) {
74 watchContainer = FSEventsWatchers[watchPath];
75 watchContainer.listeners.push(filteredListener);
77 watchContainer = FSEventsWatchers[watchPath] = {
78 listeners: [filteredListener],
79 rawEmitters: [rawEmitter],
80 watcher: createFSEventsInstance(watchPath, function(fullPath, flags) {
81 var info = fsevents.getInfo(fullPath, flags);
82 watchContainer.listeners.forEach(function(listener) {
83 listener(fullPath, flags, info);
85 watchContainer.rawEmitters.forEach(function(emitter) {
86 emitter(info.event, fullPath, info);
91 var listenerIndex = watchContainer.listeners.length - 1;
93 // removes this instance's listeners and closes the underlying fsevents
94 // instance if there are no more listeners left
95 return function close() {
96 delete watchContainer.listeners[listenerIndex];
97 delete watchContainer.rawEmitters[listenerIndex];
98 if (!Object.keys(watchContainer.listeners).length) {
99 watchContainer.watcher.stop();
100 delete FSEventsWatchers[watchPath];
105 // Decide whether or not we should start a new higher-level
107 function couldConsolidate(path) {
108 var keys = Object.keys(FSEventsWatchers);
111 for (var i = 0, len = keys.length; i < len; ++i) {
112 var watchPath = keys[i];
113 if (watchPath.indexOf(path) === 0) {
115 if (count >= consolidateThreshhold) {
124 // returns boolean indicating whether fsevents can be used
126 return fsevents && Object.keys(FSEventsWatchers).length < 128;
129 // determines subdirectory traversal levels from root to path
130 function depth(path, root) {
132 while (!path.indexOf(root) && (path = sysPath.dirname(path)) !== root) i++;
136 // fake constructor for attaching fsevents-specific prototype methods that
137 // will be copied to FSWatcher's prototype
138 function FsEventsHandler() {}
140 // Private method: Handle symlinks encountered during directory scan
142 // * watchPath - string, file/dir path to be watched with fsevents
143 // * realPath - string, real path (in case of symlinks)
144 // * transform - function, path transformer
145 // * globFilter - function, path filter in case a glob pattern was provided
147 // Returns close function for the watcher instance
148 FsEventsHandler.prototype._watchWithFsEvents =
149 function(watchPath, realPath, transform, globFilter) {
150 if (this._isIgnored(watchPath)) return;
151 var watchCallback = function(fullPath, flags, info) {
153 this.options.depth !== undefined &&
154 depth(fullPath, realPath) > this.options.depth
156 var path = transform(sysPath.join(
157 watchPath, sysPath.relative(watchPath, fullPath)
159 if (globFilter && !globFilter(path)) return;
160 // ensure directories are tracked
161 var parent = sysPath.dirname(path);
162 var item = sysPath.basename(path);
163 var watchedDir = this._getWatchedDir(
164 info.type === 'directory' ? path : parent
166 var checkIgnored = function(stats) {
167 if (this._isIgnored(path, stats)) {
168 this._ignoredPaths[path] = true;
169 if (stats && stats.isDirectory()) {
170 this._ignoredPaths[path + '/**/*'] = true;
174 delete this._ignoredPaths[path];
175 delete this._ignoredPaths[path + '/**/*'];
179 var handleEvent = function(event) {
180 if (checkIgnored()) return;
182 if (event === 'unlink') {
183 // suppress unlink events on never before seen files
184 if (info.type === 'directory' || watchedDir.has(item)) {
185 this._remove(parent, item);
188 if (event === 'add') {
189 // track new directories
190 if (info.type === 'directory') this._getWatchedDir(path);
192 if (info.type === 'symlink' && this.options.followSymlinks) {
193 // push symlinks back to the top of the stack to get handled
194 var curDepth = this.options.depth === undefined ?
195 undefined : depth(fullPath, realPath) + 1;
196 return this._addToFsEvents(path, false, true, curDepth);
199 // (other than symlinks being followed, which will be tracked soon)
200 this._getWatchedDir(parent).add(item);
203 var eventName = info.type === 'directory' ? event + 'Dir' : event;
204 this._emit(eventName, path);
205 if (eventName === 'addDir') this._addToFsEvents(path, false, true);
209 function addOrChange() {
210 handleEvent(watchedDir.has(item) ? 'change' : 'add');
213 fs.open(path, 'r', function(error, fd) {
214 if (fd) fs.close(fd);
215 error && error.code !== 'EACCES' ?
216 handleEvent('unlink') : addOrChange();
219 // correct for wrong events emitted
220 var wrongEventFlags = [
221 69888, 70400, 71424, 72704, 73472, 131328, 131840, 262912
223 if (wrongEventFlags.indexOf(flags) !== -1 || info.event === 'unknown') {
224 if (typeof this.options.ignored === 'function') {
225 fs.stat(path, function(error, stats) {
226 if (checkIgnored(stats)) return;
227 stats ? addOrChange() : handleEvent('unlink');
233 switch (info.event) {
236 return addOrChange();
244 var closer = setFSEventsListener(
248 this.emit.bind(this, 'raw')
255 // Private method: Handle symlinks encountered during directory scan
257 // * linkPath - string, path to symlink
258 // * fullPath - string, absolute path to the symlink
259 // * transform - function, pre-existing path transformer
260 // * curDepth - int, level of subdirectories traversed to where symlink is
263 FsEventsHandler.prototype._handleFsEventsSymlink =
264 function(linkPath, fullPath, transform, curDepth) {
265 // don't follow the same symlink more than once
266 if (this._symlinkPaths[fullPath]) return;
267 else this._symlinkPaths[fullPath] = true;
271 fs.realpath(linkPath, function(error, linkTarget) {
272 if (this._handleError(error) || this._isIgnored(linkTarget)) {
273 return this._emitReady();
278 // add the linkTarget for watching with a wrapper for transform
279 // that causes emitted paths to incorporate the link's path
280 this._addToFsEvents(linkTarget || linkPath, function(path) {
281 var dotSlash = '.' + sysPath.sep;
282 var aliasedPath = linkPath;
283 if (linkTarget && linkTarget !== dotSlash) {
284 aliasedPath = path.replace(linkTarget, linkPath);
285 } else if (path !== dotSlash) {
286 aliasedPath = sysPath.join(linkPath, path);
288 return transform(aliasedPath);
293 // Private method: Handle added path with fsevents
295 // * path - string, file/directory path or glob pattern
296 // * transform - function, converts working path to what the user expects
297 // * forceAdd - boolean, ensure add is emitted
298 // * priorDepth - int, level of subdirectories already traversed
301 FsEventsHandler.prototype._addToFsEvents =
302 function(path, transform, forceAdd, priorDepth) {
304 // applies transform if provided, otherwise returns same value
305 var processPath = typeof transform === 'function' ?
306 transform : function(val) { return val; };
308 var emitAdd = function(newPath, stats) {
309 var pp = processPath(newPath);
310 var isDir = stats.isDirectory();
311 var dirObj = this._getWatchedDir(sysPath.dirname(pp));
312 var base = sysPath.basename(pp);
314 // ensure empty dirs get tracked
315 if (isDir) this._getWatchedDir(pp);
317 if (dirObj.has(base)) return;
320 if (!this.options.ignoreInitial || forceAdd === true) {
321 this._emit(isDir ? 'addDir' : 'add', pp, stats);
325 var wh = this._getWatchHelpers(path);
327 // evaluate what is at the path we're being asked to watch
328 fs[wh.statMethod](wh.watchPath, function(error, stats) {
329 if (this._handleError(error) || this._isIgnored(wh.watchPath, stats)) {
331 return this._emitReady();
334 if (stats.isDirectory()) {
335 // emit addDir unless this is a glob parent
336 if (!wh.globFilter) emitAdd(processPath(path), stats);
338 // don't recurse further if it would exceed depth setting
339 if (priorDepth && priorDepth > this.options.depth) return;
341 // scan the contents of the dir
345 fileFilter: wh.filterPath,
346 directoryFilter: wh.filterDir,
348 depth: this.options.depth - (priorDepth || 0)
349 }).on('data', function(entry) {
350 // need to check filterPath on dirs b/c filterDir is less restrictive
351 if (entry.stat.isDirectory() && !wh.filterPath(entry)) return;
353 var joinedPath = sysPath.join(wh.watchPath, entry.path);
354 var fullPath = entry.fullPath;
356 if (wh.followSymlinks && entry.stat.isSymbolicLink()) {
357 // preserve the current depth here since it can't be derived from
358 // real paths past the symlink
359 var curDepth = this.options.depth === undefined ?
360 undefined : depth(joinedPath, sysPath.resolve(wh.watchPath)) + 1;
362 this._handleFsEventsSymlink(joinedPath, fullPath, processPath, curDepth);
364 emitAdd(joinedPath, entry.stat);
366 }.bind(this)).on('error', function() {
367 // Ignore readdirp errors
368 }).on('end', this._emitReady);
370 emitAdd(wh.watchPath, stats);
375 if (this.options.persistent && forceAdd !== true) {
376 var initWatch = function(error, realPath) {
377 var closer = this._watchWithFsEvents(
379 sysPath.resolve(realPath || wh.watchPath),
383 if (closer) this._closers[path] = closer;
386 if (typeof transform === 'function') {
387 // realpath has already been resolved
390 fs.realpath(wh.watchPath, initWatch);
395 module.exports = FsEventsHandler;
396 module.exports.canUse = canUse;