Initial commit
[yaffs-website] / node_modules / gaze / lib / gaze.js
1 /*
2  * gaze
3  * https://github.com/shama/gaze
4  *
5  * Copyright (c) 2013 Kyle Robinson Young
6  * Licensed under the MIT license.
7  */
8
9 'use strict';
10
11 // libs
12 var util = require('util');
13 var EE = require('events').EventEmitter;
14 var fs = require('fs');
15 var path = require('path');
16 var globule = require('globule');
17 var helper = require('./helper');
18
19 // shim setImmediate for node v0.8
20 var setImmediate = require('timers').setImmediate;
21 if (typeof setImmediate !== 'function') {
22   setImmediate = process.nextTick;
23 }
24
25 // globals
26 var delay = 10;
27
28 // `Gaze` EventEmitter object to return in the callback
29 function Gaze(patterns, opts, done) {
30   var self = this;
31   EE.call(self);
32
33   // If second arg is the callback
34   if (typeof opts === 'function') {
35     done = opts;
36     opts = {};
37   }
38
39   // Default options
40   opts = opts || {};
41   opts.mark = true;
42   opts.interval = opts.interval || 100;
43   opts.debounceDelay = opts.debounceDelay || 500;
44   opts.cwd = opts.cwd || process.cwd();
45   this.options = opts;
46
47   // Default done callback
48   done = done || function() {};
49
50   // Remember our watched dir:files
51   this._watched = Object.create(null);
52
53   // Store watchers
54   this._watchers = Object.create(null);
55
56   // Store watchFile listeners
57   this._pollers = Object.create(null);
58
59   // Store patterns
60   this._patterns = [];
61
62   // Cached events for debouncing
63   this._cached = Object.create(null);
64
65   // Set maxListeners
66   if (this.options.maxListeners) {
67     this.setMaxListeners(this.options.maxListeners);
68     Gaze.super_.prototype.setMaxListeners(this.options.maxListeners);
69     delete this.options.maxListeners;
70   }
71
72   // Initialize the watch on files
73   if (patterns) {
74     this.add(patterns, done);
75   }
76
77   // keep the process alive
78   this._keepalive = setInterval(function() {}, 200);
79
80   return this;
81 }
82 util.inherits(Gaze, EE);
83
84 // Main entry point. Start watching and call done when setup
85 module.exports = function gaze(patterns, opts, done) {
86   return new Gaze(patterns, opts, done);
87 };
88 module.exports.Gaze = Gaze;
89
90 // Override the emit function to emit `all` events
91 // and debounce on duplicate events per file
92 Gaze.prototype.emit = function() {
93   var self = this;
94   var args = arguments;
95
96   var e = args[0];
97   var filepath = args[1];
98   var timeoutId;
99
100   // If not added/deleted/changed/renamed then just emit the event
101   if (e.slice(-2) !== 'ed') {
102     Gaze.super_.prototype.emit.apply(self, args);
103     return this;
104   }
105
106   // Detect rename event, if added and previous deleted is in the cache
107   if (e === 'added') {
108     Object.keys(this._cached).forEach(function(oldFile) {
109       if (self._cached[oldFile].indexOf('deleted') !== -1) {
110         args[0] = e = 'renamed';
111         [].push.call(args, oldFile);
112         delete self._cached[oldFile];
113         return false;
114       }
115     });
116   }
117
118   // If cached doesnt exist, create a delay before running the next
119   // then emit the event
120   var cache = this._cached[filepath] || [];
121   if (cache.indexOf(e) === -1) {
122     helper.objectPush(self._cached, filepath, e);
123     clearTimeout(timeoutId);
124     timeoutId = setTimeout(function() {
125       delete self._cached[filepath];
126     }, this.options.debounceDelay);
127     // Emit the event and `all` event
128     Gaze.super_.prototype.emit.apply(self, args);
129     Gaze.super_.prototype.emit.apply(self, ['all', e].concat([].slice.call(args, 1)));
130   }
131
132   // Detect if new folder added to trigger for matching files within folder
133   if (e === 'added') {
134     if (helper.isDir(filepath)) {
135       fs.readdirSync(filepath).map(function(file) {
136         return path.join(filepath, file);
137       }).filter(function(file) {
138         return globule.isMatch(self._patterns, file, self.options);
139       }).forEach(function(file) {
140         self.emit('added', file);
141       });
142     }
143   }
144
145   return this;
146 };
147
148 // Close watchers
149 Gaze.prototype.close = function(_reset) {
150   var self = this;
151   _reset = _reset === false ? false : true;
152   Object.keys(self._watchers).forEach(function(file) {
153     self._watchers[file].close();
154   });
155   self._watchers = Object.create(null);
156   Object.keys(this._watched).forEach(function(dir) {
157     self._unpollDir(dir);
158   });
159   if (_reset) {
160     self._watched = Object.create(null);
161     setTimeout(function() {
162       self.emit('end');
163       self.removeAllListeners();
164       clearInterval(self._keepalive);
165     }, delay + 100);
166   }
167   return self;
168 };
169
170 // Add file patterns to be watched
171 Gaze.prototype.add = function(files, done) {
172   if (typeof files === 'string') { files = [files]; }
173   this._patterns = helper.unique.apply(null, [this._patterns, files]);
174   files = globule.find(this._patterns, this.options);
175   this._addToWatched(files);
176   this.close(false);
177   this._initWatched(done);
178 };
179
180 // Dont increment patterns and dont call done if nothing added
181 Gaze.prototype._internalAdd = function(file, done) {
182   var files = [];
183   if (helper.isDir(file)) {
184     files = [helper.markDir(file)].concat(globule.find(this._patterns, this.options));
185   } else {
186     if (globule.isMatch(this._patterns, file, this.options)) {
187       files = [file];
188     }
189   }
190   if (files.length > 0) {
191     this._addToWatched(files);
192     this.close(false);
193     this._initWatched(done);
194   }
195 };
196
197 // Remove file/dir from `watched`
198 Gaze.prototype.remove = function(file) {
199   var self = this;
200   if (this._watched[file]) {
201     // is dir, remove all files
202     this._unpollDir(file);
203     delete this._watched[file];
204   } else {
205     // is a file, find and remove
206     Object.keys(this._watched).forEach(function(dir) {
207       var index = self._watched[dir].indexOf(file);
208       if (index !== -1) {
209         self._unpollFile(file);
210         self._watched[dir].splice(index, 1);
211         return false;
212       }
213     });
214   }
215   if (this._watchers[file]) {
216     this._watchers[file].close();
217   }
218   return this;
219 };
220
221 // Return watched files
222 Gaze.prototype.watched = function() {
223   return this._watched;
224 };
225
226 // Returns `watched` files with relative paths to process.cwd()
227 Gaze.prototype.relative = function(dir, unixify) {
228   var self = this;
229   var relative = Object.create(null);
230   var relDir, relFile, unixRelDir;
231   var cwd = this.options.cwd || process.cwd();
232   if (dir === '') { dir = '.'; }
233   dir = helper.markDir(dir);
234   unixify = unixify || false;
235   Object.keys(this._watched).forEach(function(dir) {
236     relDir = path.relative(cwd, dir) + path.sep;
237     if (relDir === path.sep) { relDir = '.'; }
238     unixRelDir = unixify ? helper.unixifyPathSep(relDir) : relDir;
239     relative[unixRelDir] = self._watched[dir].map(function(file) {
240       relFile = path.relative(path.join(cwd, relDir) || '', file || '');
241       if (helper.isDir(file)) {
242         relFile = helper.markDir(relFile);
243       }
244       if (unixify) {
245         relFile = helper.unixifyPathSep(relFile);
246       }
247       return relFile;
248     });
249   });
250   if (dir && unixify) {
251     dir = helper.unixifyPathSep(dir);
252   }
253   return dir ? relative[dir] || [] : relative;
254 };
255
256 // Adds files and dirs to watched
257 Gaze.prototype._addToWatched = function(files) {
258   for (var i = 0; i < files.length; i++) {
259     var file = files[i];
260     var filepath = path.resolve(this.options.cwd, file);
261
262     var dirname = (helper.isDir(file)) ? filepath : path.dirname(filepath);
263     dirname = helper.markDir(dirname);
264
265     // If a new dir is added
266     if (helper.isDir(file) && !(filepath in this._watched)) {
267       helper.objectPush(this._watched, filepath, []);
268     }
269
270     if (file.slice(-1) === '/') { filepath += path.sep; }
271     helper.objectPush(this._watched, path.dirname(filepath) + path.sep, filepath);
272
273     // add folders into the mix
274     var readdir = fs.readdirSync(dirname);
275     for (var j = 0; j < readdir.length; j++) {
276       var dirfile = path.join(dirname, readdir[j]);
277       if (fs.lstatSync(dirfile).isDirectory()) {
278         helper.objectPush(this._watched, dirname, dirfile + path.sep);
279       }
280     }
281   }
282   return this;
283 };
284
285 Gaze.prototype._watchDir = function(dir, done) {
286   var self = this;
287   var timeoutId;
288   try {
289     this._watchers[dir] = fs.watch(dir, function(event) {
290       // race condition. Let's give the fs a little time to settle down. so we
291       // don't fire events on non existent files.
292       clearTimeout(timeoutId);
293       timeoutId = setTimeout(function() {
294         // race condition. Ensure that this directory is still being watched
295         // before continuing.
296         if ((dir in self._watchers) && fs.existsSync(dir)) {
297           done(null, dir);
298         }
299       }, delay + 100);
300     });
301   } catch (err) {
302     return this._handleError(err);
303   }
304   return this;
305 };
306
307 Gaze.prototype._unpollFile = function(file) {
308   if (this._pollers[file]) {
309     fs.unwatchFile(file, this._pollers[file] );
310     delete this._pollers[file];
311   }
312   return this;
313 };
314
315 Gaze.prototype._unpollDir = function(dir) {
316   this._unpollFile(dir);
317   for (var i = 0; i < this._watched[dir].length; i++) {
318     this._unpollFile(this._watched[dir][i]);
319   }
320 };
321
322 Gaze.prototype._pollFile = function(file, done) {
323   var opts = { persistent: true, interval: this.options.interval };
324   if (!this._pollers[file]) {
325     this._pollers[file] = function(curr, prev) {
326       done(null, file);
327     };
328     try {
329       fs.watchFile(file, opts, this._pollers[file]);
330     } catch (err) {
331       return this._handleError(err);
332     }
333   }
334   return this;
335 };
336
337 // Initialize the actual watch on `watched` files
338 Gaze.prototype._initWatched = function(done) {
339   var self = this;
340   var cwd = this.options.cwd || process.cwd();
341   var curWatched = Object.keys(self._watched);
342
343   // if no matching files
344   if (curWatched.length < 1) {
345     // Defer to emitting to give a chance to attach event handlers.
346     setImmediate(function () {
347       self.emit('ready', self);
348       if (done) { done.call(self, null, self); }
349       self.emit('nomatch');
350     });
351     return;
352   }
353
354   helper.forEachSeries(curWatched, function(dir, next) {
355     dir = dir || '';
356     var files = self._watched[dir];
357     // Triggered when a watched dir has an event
358     self._watchDir(dir, function(event, dirpath) {
359       var relDir = cwd === dir ? '.' : path.relative(cwd, dir);
360       relDir = relDir || '';
361
362       fs.readdir(dirpath, function(err, current) {
363         if (err) { return self.emit('error', err); }
364         if (!current) { return; }
365
366         try {
367           // append path.sep to directories so they match previous.
368           current = current.map(function(curPath) {
369             if (fs.existsSync(path.join(dir, curPath)) && fs.lstatSync(path.join(dir, curPath)).isDirectory()) {
370               return curPath + path.sep;
371             } else {
372               return curPath;
373             }
374           });
375         } catch (err) {
376           // race condition-- sometimes the file no longer exists
377         }
378
379         // Get watched files for this dir
380         var previous = self.relative(relDir);
381
382         // If file was deleted
383         previous.filter(function(file) {
384           return current.indexOf(file) < 0;
385         }).forEach(function(file) {
386           if (!helper.isDir(file)) {
387             var filepath = path.join(dir, file);
388             self.remove(filepath);
389             self.emit('deleted', filepath);
390           }
391         });
392
393         // If file was added
394         current.filter(function(file) {
395           return previous.indexOf(file) < 0;
396         }).forEach(function(file) {
397           // Is it a matching pattern?
398           var relFile = path.join(relDir, file);
399           // Add to watch then emit event
400           self._internalAdd(relFile, function() {
401             self.emit('added', path.join(dir, file));
402           });
403         });
404
405       });
406     });
407
408     // Watch for change/rename events on files
409     files.forEach(function(file) {
410       if (helper.isDir(file)) { return; }
411       self._pollFile(file, function(err, filepath) {
412         // Only emit changed if the file still exists
413         // Prevents changed/deleted duplicate events
414         if (fs.existsSync(filepath)) {
415           self.emit('changed', filepath);
416         }
417       });
418     });
419
420     next();
421   }, function() {
422
423     // Return this instance of Gaze
424     // delay before ready solves a lot of issues
425     setTimeout(function() {
426       self.emit('ready', self);
427       if (done) { done.call(self, null, self); }
428     }, delay + 100);
429
430   });
431 };
432
433 // If an error, handle it here
434 Gaze.prototype._handleError = function(err) {
435   if (err.code === 'EMFILE') {
436     return this.emit('error', new Error('EMFILE: Too many opened files.'));
437   }
438   return this.emit('error', err);
439 };