Initial commit
[yaffs-website] / node_modules / node-sass / node_modules / gaze / lib / gaze.js
1 /*
2  * gaze
3  * https://github.com/shama/gaze
4  *
5  * Copyright (c) 2016 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 != null) {
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       // It's possible that between `isDir` and `readdirSync()` calls the `filepath`
136       // gets removed, which will result in `ENOENT` exception
137
138       var files;
139
140       try {
141         files = fs.readdirSync(filepath);
142       } catch (e) {
143         // Rethrow the error if it's anything other than `ENOENT`
144         if (e.code !== 'ENOENT') {
145           throw e;
146         }
147
148         files = [];
149       }
150
151       files.map(function (file) {
152         return path.join(filepath, file);
153       }).filter(function (file) {
154         return globule.isMatch(self._patterns, file, self.options);
155       }).forEach(function (file) {
156         self.emit('added', file);
157       });
158     }
159   }
160
161   return this;
162 };
163
164 // Close watchers
165 Gaze.prototype.close = function (_reset) {
166   var self = this;
167   Object.keys(self._watchers).forEach(function (file) {
168     self._watchers[file].close();
169   });
170   self._watchers = Object.create(null);
171   Object.keys(this._watched).forEach(function (dir) {
172     self._unpollDir(dir);
173   });
174   if (_reset !== false) {
175     self._watched = Object.create(null);
176     setTimeout(function () {
177       self.emit('end');
178       self.removeAllListeners();
179       clearInterval(self._keepalive);
180     }, delay + 100);
181   }
182   return self;
183 };
184
185 // Add file patterns to be watched
186 Gaze.prototype.add = function (files, done) {
187   if (typeof files === 'string') { files = [files]; }
188   this._patterns = helper.unique.apply(null, [this._patterns, files]);
189   files = globule.find(this._patterns, this.options);
190   this._addToWatched(files);
191   this.close(false);
192   this._initWatched(done);
193 };
194
195 // Dont increment patterns and dont call done if nothing added
196 Gaze.prototype._internalAdd = function (file, done) {
197   var files = [];
198   if (helper.isDir(file)) {
199     files = [helper.markDir(file)].concat(globule.find(this._patterns, this.options));
200   } else {
201     if (globule.isMatch(this._patterns, file, this.options)) {
202       files = [file];
203     }
204   }
205   if (files.length > 0) {
206     this._addToWatched(files);
207     this.close(false);
208     this._initWatched(done);
209   }
210 };
211
212 // Remove file/dir from `watched`
213 Gaze.prototype.remove = function (file) {
214   var self = this;
215   if (this._watched[file]) {
216     // is dir, remove all files
217     this._unpollDir(file);
218     delete this._watched[file];
219   } else {
220     // is a file, find and remove
221     Object.keys(this._watched).forEach(function (dir) {
222       var index = self._watched[dir].indexOf(file);
223       if (index !== -1) {
224         self._unpollFile(file);
225         self._watched[dir].splice(index, 1);
226         return false;
227       }
228     });
229   }
230   if (this._watchers[file]) {
231     this._watchers[file].close();
232   }
233   return this;
234 };
235
236 // Return watched files
237 Gaze.prototype.watched = function () {
238   return this._watched;
239 };
240
241 // Returns `watched` files with relative paths to process.cwd()
242 Gaze.prototype.relative = function (dir, unixify) {
243   var self = this;
244   var relative = Object.create(null);
245   var relDir, relFile, unixRelDir;
246   var cwd = this.options.cwd || process.cwd();
247   if (dir === '') { dir = '.'; }
248   dir = helper.markDir(dir);
249   unixify = unixify || false;
250   Object.keys(this._watched).forEach(function (dir) {
251     relDir = path.relative(cwd, dir) + path.sep;
252     if (relDir === path.sep) { relDir = '.'; }
253     unixRelDir = unixify ? helper.unixifyPathSep(relDir) : relDir;
254     relative[unixRelDir] = self._watched[dir].map(function (file) {
255       relFile = path.relative(path.join(cwd, relDir) || '', file || '');
256       if (helper.isDir(file)) {
257         relFile = helper.markDir(relFile);
258       }
259       if (unixify) {
260         relFile = helper.unixifyPathSep(relFile);
261       }
262       return relFile;
263     });
264   });
265   if (dir && unixify) {
266     dir = helper.unixifyPathSep(dir);
267   }
268   return dir ? relative[dir] || [] : relative;
269 };
270
271 // Adds files and dirs to watched
272 Gaze.prototype._addToWatched = function (files) {
273   for (var i = 0; i < files.length; i++) {
274     var file = files[i];
275     var filepath = path.resolve(this.options.cwd, file);
276
277     var dirname = (helper.isDir(file)) ? filepath : path.dirname(filepath);
278     dirname = helper.markDir(dirname);
279
280     // If a new dir is added
281     if (helper.isDir(file) && !(dirname in this._watched)) {
282       helper.objectPush(this._watched, dirname, []);
283     }
284
285     if (file.slice(-1) === '/') { filepath += path.sep; }
286     helper.objectPush(this._watched, path.dirname(filepath) + path.sep, filepath);
287
288     // add folders into the mix
289     var readdir = fs.readdirSync(dirname);
290     for (var j = 0; j < readdir.length; j++) {
291       var dirfile = path.join(dirname, readdir[j]);
292       if (fs.lstatSync(dirfile).isDirectory()) {
293         helper.objectPush(this._watched, dirname, dirfile + path.sep);
294       }
295     }
296   }
297   return this;
298 };
299
300 Gaze.prototype._watchDir = function (dir, done) {
301   var self = this;
302   var timeoutId;
303   try {
304     this._watchers[dir] = fs.watch(dir, function (event) {
305       // race condition. Let's give the fs a little time to settle down. so we
306       // don't fire events on non existent files.
307       clearTimeout(timeoutId);
308       timeoutId = setTimeout(function () {
309         // race condition. Ensure that this directory is still being watched
310         // before continuing.
311         if ((dir in self._watchers) && fs.existsSync(dir)) {
312           done(null, dir);
313         }
314       }, delay + 100);
315     });
316
317     this._watchers[dir].on('error', function (err) {
318       self._handleError(err);
319     });
320   } catch (err) {
321     return this._handleError(err);
322   }
323   return this;
324 };
325
326 Gaze.prototype._unpollFile = function (file) {
327   if (this._pollers[file]) {
328     fs.unwatchFile(file, this._pollers[file]);
329     delete this._pollers[file];
330   }
331   return this;
332 };
333
334 Gaze.prototype._unpollDir = function (dir) {
335   this._unpollFile(dir);
336   for (var i = 0; i < this._watched[dir].length; i++) {
337     this._unpollFile(this._watched[dir][i]);
338   }
339 };
340
341 Gaze.prototype._pollFile = function (file, done) {
342   var opts = { persistent: true, interval: this.options.interval };
343   if (!this._pollers[file]) {
344     this._pollers[file] = function (curr, prev) {
345       done(null, file);
346     };
347     try {
348       fs.watchFile(file, opts, this._pollers[file]);
349     } catch (err) {
350       return this._handleError(err);
351     }
352   }
353   return this;
354 };
355
356 // Initialize the actual watch on `watched` files
357 Gaze.prototype._initWatched = function (done) {
358   var self = this;
359   var cwd = this.options.cwd || process.cwd();
360   var curWatched = Object.keys(self._watched);
361
362   // if no matching files
363   if (curWatched.length < 1) {
364     // Defer to emitting to give a chance to attach event handlers.
365     setImmediate(function () {
366       self.emit('ready', self);
367       if (done) { done.call(self, null, self); }
368       self.emit('nomatch');
369     });
370     return;
371   }
372
373   helper.forEachSeries(curWatched, function (dir, next) {
374     dir = dir || '';
375     var files = self._watched[dir];
376     // Triggered when a watched dir has an event
377     self._watchDir(dir, function (event, dirpath) {
378       var relDir = cwd === dir ? '.' : path.relative(cwd, dir);
379       relDir = relDir || '';
380
381       fs.readdir(dirpath, function (err, current) {
382         if (err) { return self.emit('error', err); }
383         if (!current) { return; }
384
385         try {
386           // append path.sep to directories so they match previous.
387           current = current.map(function (curPath) {
388             if (fs.existsSync(path.join(dir, curPath)) && fs.lstatSync(path.join(dir, curPath)).isDirectory()) {
389               return curPath + path.sep;
390             } else {
391               return curPath;
392             }
393           });
394         } catch (err) {
395           // race condition-- sometimes the file no longer exists
396         }
397
398         // Get watched files for this dir
399         var previous = self.relative(relDir);
400
401         // If file was deleted
402         previous.filter(function (file) {
403           return current.indexOf(file) < 0;
404         }).forEach(function (file) {
405           if (!helper.isDir(file)) {
406             var filepath = path.join(dir, file);
407             self.remove(filepath);
408             self.emit('deleted', filepath);
409           }
410         });
411
412         // If file was added
413         current.filter(function (file) {
414           return previous.indexOf(file) < 0;
415         }).forEach(function (file) {
416           // Is it a matching pattern?
417           var relFile = path.join(relDir, file);
418           // Add to watch then emit event
419           self._internalAdd(relFile, function () {
420             self.emit('added', path.join(dir, file));
421           });
422         });
423       });
424     });
425
426     // Watch for change/rename events on files
427     files.forEach(function (file) {
428       if (helper.isDir(file)) { return; }
429       self._pollFile(file, function (err, filepath) {
430         if (err) {
431           self.emit('error', err);
432           return;
433         }
434         // Only emit changed if the file still exists
435         // Prevents changed/deleted duplicate events
436         if (fs.existsSync(filepath)) {
437           self.emit('changed', filepath);
438         }
439       });
440     });
441
442     next();
443   }, function () {
444     // Return this instance of Gaze
445     // delay before ready solves a lot of issues
446     setTimeout(function () {
447       self.emit('ready', self);
448       if (done) { done.call(self, null, self); }
449     }, delay + 100);
450   });
451 };
452
453 // If an error, handle it here
454 Gaze.prototype._handleError = function (err) {
455   if (err.code === 'EMFILE') {
456     return this.emit('error', new Error('EMFILE: Too many opened files.'));
457   }
458   return this.emit('error', err);
459 };