Initial commit
[yaffs-website] / node_modules / glob / glob.js
1 // Approach:
2 //
3 // 1. Get the minimatch set
4 // 2. For each pattern in the set, PROCESS(pattern, false)
5 // 3. Store matches per-set, then uniq them
6 //
7 // PROCESS(pattern, inGlobStar)
8 // Get the first [n] items from pattern that are all strings
9 // Join these together.  This is PREFIX.
10 //   If there is no more remaining, then stat(PREFIX) and
11 //   add to matches if it succeeds.  END.
12 //
13 // If inGlobStar and PREFIX is symlink and points to dir
14 //   set ENTRIES = []
15 // else readdir(PREFIX) as ENTRIES
16 //   If fail, END
17 //
18 // with ENTRIES
19 //   If pattern[n] is GLOBSTAR
20 //     // handle the case where the globstar match is empty
21 //     // by pruning it out, and testing the resulting pattern
22 //     PROCESS(pattern[0..n] + pattern[n+1 .. $], false)
23 //     // handle other cases.
24 //     for ENTRY in ENTRIES (not dotfiles)
25 //       // attach globstar + tail onto the entry
26 //       // Mark that this entry is a globstar match
27 //       PROCESS(pattern[0..n] + ENTRY + pattern[n .. $], true)
28 //
29 //   else // not globstar
30 //     for ENTRY in ENTRIES (not dotfiles, unless pattern[n] is dot)
31 //       Test ENTRY against pattern[n]
32 //       If fails, continue
33 //       If passes, PROCESS(pattern[0..n] + item + pattern[n+1 .. $])
34 //
35 // Caveat:
36 //   Cache all stats and readdirs results to minimize syscall.  Since all
37 //   we ever care about is existence and directory-ness, we can just keep
38 //   `true` for files, and [children,...] for directories, or `false` for
39 //   things that don't exist.
40
41 module.exports = glob
42
43 var fs = require('fs')
44 var rp = require('fs.realpath')
45 var minimatch = require('minimatch')
46 var Minimatch = minimatch.Minimatch
47 var inherits = require('inherits')
48 var EE = require('events').EventEmitter
49 var path = require('path')
50 var assert = require('assert')
51 var isAbsolute = require('path-is-absolute')
52 var globSync = require('./sync.js')
53 var common = require('./common.js')
54 var alphasort = common.alphasort
55 var alphasorti = common.alphasorti
56 var setopts = common.setopts
57 var ownProp = common.ownProp
58 var inflight = require('inflight')
59 var util = require('util')
60 var childrenIgnored = common.childrenIgnored
61 var isIgnored = common.isIgnored
62
63 var once = require('once')
64
65 function glob (pattern, options, cb) {
66   if (typeof options === 'function') cb = options, options = {}
67   if (!options) options = {}
68
69   if (options.sync) {
70     if (cb)
71       throw new TypeError('callback provided to sync glob')
72     return globSync(pattern, options)
73   }
74
75   return new Glob(pattern, options, cb)
76 }
77
78 glob.sync = globSync
79 var GlobSync = glob.GlobSync = globSync.GlobSync
80
81 // old api surface
82 glob.glob = glob
83
84 function extend (origin, add) {
85   if (add === null || typeof add !== 'object') {
86     return origin
87   }
88
89   var keys = Object.keys(add)
90   var i = keys.length
91   while (i--) {
92     origin[keys[i]] = add[keys[i]]
93   }
94   return origin
95 }
96
97 glob.hasMagic = function (pattern, options_) {
98   var options = extend({}, options_)
99   options.noprocess = true
100
101   var g = new Glob(pattern, options)
102   var set = g.minimatch.set
103
104   if (!pattern)
105     return false
106
107   if (set.length > 1)
108     return true
109
110   for (var j = 0; j < set[0].length; j++) {
111     if (typeof set[0][j] !== 'string')
112       return true
113   }
114
115   return false
116 }
117
118 glob.Glob = Glob
119 inherits(Glob, EE)
120 function Glob (pattern, options, cb) {
121   if (typeof options === 'function') {
122     cb = options
123     options = null
124   }
125
126   if (options && options.sync) {
127     if (cb)
128       throw new TypeError('callback provided to sync glob')
129     return new GlobSync(pattern, options)
130   }
131
132   if (!(this instanceof Glob))
133     return new Glob(pattern, options, cb)
134
135   setopts(this, pattern, options)
136   this._didRealPath = false
137
138   // process each pattern in the minimatch set
139   var n = this.minimatch.set.length
140
141   // The matches are stored as {<filename>: true,...} so that
142   // duplicates are automagically pruned.
143   // Later, we do an Object.keys() on these.
144   // Keep them as a list so we can fill in when nonull is set.
145   this.matches = new Array(n)
146
147   if (typeof cb === 'function') {
148     cb = once(cb)
149     this.on('error', cb)
150     this.on('end', function (matches) {
151       cb(null, matches)
152     })
153   }
154
155   var self = this
156   var n = this.minimatch.set.length
157   this._processing = 0
158   this.matches = new Array(n)
159
160   this._emitQueue = []
161   this._processQueue = []
162   this.paused = false
163
164   if (this.noprocess)
165     return this
166
167   if (n === 0)
168     return done()
169
170   var sync = true
171   for (var i = 0; i < n; i ++) {
172     this._process(this.minimatch.set[i], i, false, done)
173   }
174   sync = false
175
176   function done () {
177     --self._processing
178     if (self._processing <= 0) {
179       if (sync) {
180         process.nextTick(function () {
181           self._finish()
182         })
183       } else {
184         self._finish()
185       }
186     }
187   }
188 }
189
190 Glob.prototype._finish = function () {
191   assert(this instanceof Glob)
192   if (this.aborted)
193     return
194
195   if (this.realpath && !this._didRealpath)
196     return this._realpath()
197
198   common.finish(this)
199   this.emit('end', this.found)
200 }
201
202 Glob.prototype._realpath = function () {
203   if (this._didRealpath)
204     return
205
206   this._didRealpath = true
207
208   var n = this.matches.length
209   if (n === 0)
210     return this._finish()
211
212   var self = this
213   for (var i = 0; i < this.matches.length; i++)
214     this._realpathSet(i, next)
215
216   function next () {
217     if (--n === 0)
218       self._finish()
219   }
220 }
221
222 Glob.prototype._realpathSet = function (index, cb) {
223   var matchset = this.matches[index]
224   if (!matchset)
225     return cb()
226
227   var found = Object.keys(matchset)
228   var self = this
229   var n = found.length
230
231   if (n === 0)
232     return cb()
233
234   var set = this.matches[index] = Object.create(null)
235   found.forEach(function (p, i) {
236     // If there's a problem with the stat, then it means that
237     // one or more of the links in the realpath couldn't be
238     // resolved.  just return the abs value in that case.
239     p = self._makeAbs(p)
240     rp.realpath(p, self.realpathCache, function (er, real) {
241       if (!er)
242         set[real] = true
243       else if (er.syscall === 'stat')
244         set[p] = true
245       else
246         self.emit('error', er) // srsly wtf right here
247
248       if (--n === 0) {
249         self.matches[index] = set
250         cb()
251       }
252     })
253   })
254 }
255
256 Glob.prototype._mark = function (p) {
257   return common.mark(this, p)
258 }
259
260 Glob.prototype._makeAbs = function (f) {
261   return common.makeAbs(this, f)
262 }
263
264 Glob.prototype.abort = function () {
265   this.aborted = true
266   this.emit('abort')
267 }
268
269 Glob.prototype.pause = function () {
270   if (!this.paused) {
271     this.paused = true
272     this.emit('pause')
273   }
274 }
275
276 Glob.prototype.resume = function () {
277   if (this.paused) {
278     this.emit('resume')
279     this.paused = false
280     if (this._emitQueue.length) {
281       var eq = this._emitQueue.slice(0)
282       this._emitQueue.length = 0
283       for (var i = 0; i < eq.length; i ++) {
284         var e = eq[i]
285         this._emitMatch(e[0], e[1])
286       }
287     }
288     if (this._processQueue.length) {
289       var pq = this._processQueue.slice(0)
290       this._processQueue.length = 0
291       for (var i = 0; i < pq.length; i ++) {
292         var p = pq[i]
293         this._processing--
294         this._process(p[0], p[1], p[2], p[3])
295       }
296     }
297   }
298 }
299
300 Glob.prototype._process = function (pattern, index, inGlobStar, cb) {
301   assert(this instanceof Glob)
302   assert(typeof cb === 'function')
303
304   if (this.aborted)
305     return
306
307   this._processing++
308   if (this.paused) {
309     this._processQueue.push([pattern, index, inGlobStar, cb])
310     return
311   }
312
313   //console.error('PROCESS %d', this._processing, pattern)
314
315   // Get the first [n] parts of pattern that are all strings.
316   var n = 0
317   while (typeof pattern[n] === 'string') {
318     n ++
319   }
320   // now n is the index of the first one that is *not* a string.
321
322   // see if there's anything else
323   var prefix
324   switch (n) {
325     // if not, then this is rather simple
326     case pattern.length:
327       this._processSimple(pattern.join('/'), index, cb)
328       return
329
330     case 0:
331       // pattern *starts* with some non-trivial item.
332       // going to readdir(cwd), but not include the prefix in matches.
333       prefix = null
334       break
335
336     default:
337       // pattern has some string bits in the front.
338       // whatever it starts with, whether that's 'absolute' like /foo/bar,
339       // or 'relative' like '../baz'
340       prefix = pattern.slice(0, n).join('/')
341       break
342   }
343
344   var remain = pattern.slice(n)
345
346   // get the list of entries.
347   var read
348   if (prefix === null)
349     read = '.'
350   else if (isAbsolute(prefix) || isAbsolute(pattern.join('/'))) {
351     if (!prefix || !isAbsolute(prefix))
352       prefix = '/' + prefix
353     read = prefix
354   } else
355     read = prefix
356
357   var abs = this._makeAbs(read)
358
359   //if ignored, skip _processing
360   if (childrenIgnored(this, read))
361     return cb()
362
363   var isGlobStar = remain[0] === minimatch.GLOBSTAR
364   if (isGlobStar)
365     this._processGlobStar(prefix, read, abs, remain, index, inGlobStar, cb)
366   else
367     this._processReaddir(prefix, read, abs, remain, index, inGlobStar, cb)
368 }
369
370 Glob.prototype._processReaddir = function (prefix, read, abs, remain, index, inGlobStar, cb) {
371   var self = this
372   this._readdir(abs, inGlobStar, function (er, entries) {
373     return self._processReaddir2(prefix, read, abs, remain, index, inGlobStar, entries, cb)
374   })
375 }
376
377 Glob.prototype._processReaddir2 = function (prefix, read, abs, remain, index, inGlobStar, entries, cb) {
378
379   // if the abs isn't a dir, then nothing can match!
380   if (!entries)
381     return cb()
382
383   // It will only match dot entries if it starts with a dot, or if
384   // dot is set.  Stuff like @(.foo|.bar) isn't allowed.
385   var pn = remain[0]
386   var negate = !!this.minimatch.negate
387   var rawGlob = pn._glob
388   var dotOk = this.dot || rawGlob.charAt(0) === '.'
389
390   var matchedEntries = []
391   for (var i = 0; i < entries.length; i++) {
392     var e = entries[i]
393     if (e.charAt(0) !== '.' || dotOk) {
394       var m
395       if (negate && !prefix) {
396         m = !e.match(pn)
397       } else {
398         m = e.match(pn)
399       }
400       if (m)
401         matchedEntries.push(e)
402     }
403   }
404
405   //console.error('prd2', prefix, entries, remain[0]._glob, matchedEntries)
406
407   var len = matchedEntries.length
408   // If there are no matched entries, then nothing matches.
409   if (len === 0)
410     return cb()
411
412   // if this is the last remaining pattern bit, then no need for
413   // an additional stat *unless* the user has specified mark or
414   // stat explicitly.  We know they exist, since readdir returned
415   // them.
416
417   if (remain.length === 1 && !this.mark && !this.stat) {
418     if (!this.matches[index])
419       this.matches[index] = Object.create(null)
420
421     for (var i = 0; i < len; i ++) {
422       var e = matchedEntries[i]
423       if (prefix) {
424         if (prefix !== '/')
425           e = prefix + '/' + e
426         else
427           e = prefix + e
428       }
429
430       if (e.charAt(0) === '/' && !this.nomount) {
431         e = path.join(this.root, e)
432       }
433       this._emitMatch(index, e)
434     }
435     // This was the last one, and no stats were needed
436     return cb()
437   }
438
439   // now test all matched entries as stand-ins for that part
440   // of the pattern.
441   remain.shift()
442   for (var i = 0; i < len; i ++) {
443     var e = matchedEntries[i]
444     var newPattern
445     if (prefix) {
446       if (prefix !== '/')
447         e = prefix + '/' + e
448       else
449         e = prefix + e
450     }
451     this._process([e].concat(remain), index, inGlobStar, cb)
452   }
453   cb()
454 }
455
456 Glob.prototype._emitMatch = function (index, e) {
457   if (this.aborted)
458     return
459
460   if (this.matches[index][e])
461     return
462
463   if (isIgnored(this, e))
464     return
465
466   if (this.paused) {
467     this._emitQueue.push([index, e])
468     return
469   }
470
471   var abs = this._makeAbs(e)
472
473   if (this.nodir) {
474     var c = this.cache[abs]
475     if (c === 'DIR' || Array.isArray(c))
476       return
477   }
478
479   if (this.mark)
480     e = this._mark(e)
481
482   this.matches[index][e] = true
483
484   var st = this.statCache[abs]
485   if (st)
486     this.emit('stat', e, st)
487
488   this.emit('match', e)
489 }
490
491 Glob.prototype._readdirInGlobStar = function (abs, cb) {
492   if (this.aborted)
493     return
494
495   // follow all symlinked directories forever
496   // just proceed as if this is a non-globstar situation
497   if (this.follow)
498     return this._readdir(abs, false, cb)
499
500   var lstatkey = 'lstat\0' + abs
501   var self = this
502   var lstatcb = inflight(lstatkey, lstatcb_)
503
504   if (lstatcb)
505     fs.lstat(abs, lstatcb)
506
507   function lstatcb_ (er, lstat) {
508     if (er)
509       return cb()
510
511     var isSym = lstat.isSymbolicLink()
512     self.symlinks[abs] = isSym
513
514     // If it's not a symlink or a dir, then it's definitely a regular file.
515     // don't bother doing a readdir in that case.
516     if (!isSym && !lstat.isDirectory()) {
517       self.cache[abs] = 'FILE'
518       cb()
519     } else
520       self._readdir(abs, false, cb)
521   }
522 }
523
524 Glob.prototype._readdir = function (abs, inGlobStar, cb) {
525   if (this.aborted)
526     return
527
528   cb = inflight('readdir\0'+abs+'\0'+inGlobStar, cb)
529   if (!cb)
530     return
531
532   //console.error('RD %j %j', +inGlobStar, abs)
533   if (inGlobStar && !ownProp(this.symlinks, abs))
534     return this._readdirInGlobStar(abs, cb)
535
536   if (ownProp(this.cache, abs)) {
537     var c = this.cache[abs]
538     if (!c || c === 'FILE')
539       return cb()
540
541     if (Array.isArray(c))
542       return cb(null, c)
543   }
544
545   var self = this
546   fs.readdir(abs, readdirCb(this, abs, cb))
547 }
548
549 function readdirCb (self, abs, cb) {
550   return function (er, entries) {
551     if (er)
552       self._readdirError(abs, er, cb)
553     else
554       self._readdirEntries(abs, entries, cb)
555   }
556 }
557
558 Glob.prototype._readdirEntries = function (abs, entries, cb) {
559   if (this.aborted)
560     return
561
562   // if we haven't asked to stat everything, then just
563   // assume that everything in there exists, so we can avoid
564   // having to stat it a second time.
565   if (!this.mark && !this.stat) {
566     for (var i = 0; i < entries.length; i ++) {
567       var e = entries[i]
568       if (abs === '/')
569         e = abs + e
570       else
571         e = abs + '/' + e
572       this.cache[e] = true
573     }
574   }
575
576   this.cache[abs] = entries
577   return cb(null, entries)
578 }
579
580 Glob.prototype._readdirError = function (f, er, cb) {
581   if (this.aborted)
582     return
583
584   // handle errors, and cache the information
585   switch (er.code) {
586     case 'ENOTSUP': // https://github.com/isaacs/node-glob/issues/205
587     case 'ENOTDIR': // totally normal. means it *does* exist.
588       var abs = this._makeAbs(f)
589       this.cache[abs] = 'FILE'
590       if (abs === this.cwdAbs) {
591         var error = new Error(er.code + ' invalid cwd ' + this.cwd)
592         error.path = this.cwd
593         error.code = er.code
594         this.emit('error', error)
595         this.abort()
596       }
597       break
598
599     case 'ENOENT': // not terribly unusual
600     case 'ELOOP':
601     case 'ENAMETOOLONG':
602     case 'UNKNOWN':
603       this.cache[this._makeAbs(f)] = false
604       break
605
606     default: // some unusual error.  Treat as failure.
607       this.cache[this._makeAbs(f)] = false
608       if (this.strict) {
609         this.emit('error', er)
610         // If the error is handled, then we abort
611         // if not, we threw out of here
612         this.abort()
613       }
614       if (!this.silent)
615         console.error('glob error', er)
616       break
617   }
618
619   return cb()
620 }
621
622 Glob.prototype._processGlobStar = function (prefix, read, abs, remain, index, inGlobStar, cb) {
623   var self = this
624   this._readdir(abs, inGlobStar, function (er, entries) {
625     self._processGlobStar2(prefix, read, abs, remain, index, inGlobStar, entries, cb)
626   })
627 }
628
629
630 Glob.prototype._processGlobStar2 = function (prefix, read, abs, remain, index, inGlobStar, entries, cb) {
631   //console.error('pgs2', prefix, remain[0], entries)
632
633   // no entries means not a dir, so it can never have matches
634   // foo.txt/** doesn't match foo.txt
635   if (!entries)
636     return cb()
637
638   // test without the globstar, and with every child both below
639   // and replacing the globstar.
640   var remainWithoutGlobStar = remain.slice(1)
641   var gspref = prefix ? [ prefix ] : []
642   var noGlobStar = gspref.concat(remainWithoutGlobStar)
643
644   // the noGlobStar pattern exits the inGlobStar state
645   this._process(noGlobStar, index, false, cb)
646
647   var isSym = this.symlinks[abs]
648   var len = entries.length
649
650   // If it's a symlink, and we're in a globstar, then stop
651   if (isSym && inGlobStar)
652     return cb()
653
654   for (var i = 0; i < len; i++) {
655     var e = entries[i]
656     if (e.charAt(0) === '.' && !this.dot)
657       continue
658
659     // these two cases enter the inGlobStar state
660     var instead = gspref.concat(entries[i], remainWithoutGlobStar)
661     this._process(instead, index, true, cb)
662
663     var below = gspref.concat(entries[i], remain)
664     this._process(below, index, true, cb)
665   }
666
667   cb()
668 }
669
670 Glob.prototype._processSimple = function (prefix, index, cb) {
671   // XXX review this.  Shouldn't it be doing the mounting etc
672   // before doing stat?  kinda weird?
673   var self = this
674   this._stat(prefix, function (er, exists) {
675     self._processSimple2(prefix, index, er, exists, cb)
676   })
677 }
678 Glob.prototype._processSimple2 = function (prefix, index, er, exists, cb) {
679
680   //console.error('ps2', prefix, exists)
681
682   if (!this.matches[index])
683     this.matches[index] = Object.create(null)
684
685   // If it doesn't exist, then just mark the lack of results
686   if (!exists)
687     return cb()
688
689   if (prefix && isAbsolute(prefix) && !this.nomount) {
690     var trail = /[\/\\]$/.test(prefix)
691     if (prefix.charAt(0) === '/') {
692       prefix = path.join(this.root, prefix)
693     } else {
694       prefix = path.resolve(this.root, prefix)
695       if (trail)
696         prefix += '/'
697     }
698   }
699
700   if (process.platform === 'win32')
701     prefix = prefix.replace(/\\/g, '/')
702
703   // Mark this as a match
704   this._emitMatch(index, prefix)
705   cb()
706 }
707
708 // Returns either 'DIR', 'FILE', or false
709 Glob.prototype._stat = function (f, cb) {
710   var abs = this._makeAbs(f)
711   var needDir = f.slice(-1) === '/'
712
713   if (f.length > this.maxLength)
714     return cb()
715
716   if (!this.stat && ownProp(this.cache, abs)) {
717     var c = this.cache[abs]
718
719     if (Array.isArray(c))
720       c = 'DIR'
721
722     // It exists, but maybe not how we need it
723     if (!needDir || c === 'DIR')
724       return cb(null, c)
725
726     if (needDir && c === 'FILE')
727       return cb()
728
729     // otherwise we have to stat, because maybe c=true
730     // if we know it exists, but not what it is.
731   }
732
733   var exists
734   var stat = this.statCache[abs]
735   if (stat !== undefined) {
736     if (stat === false)
737       return cb(null, stat)
738     else {
739       var type = stat.isDirectory() ? 'DIR' : 'FILE'
740       if (needDir && type === 'FILE')
741         return cb()
742       else
743         return cb(null, type, stat)
744     }
745   }
746
747   var self = this
748   var statcb = inflight('stat\0' + abs, lstatcb_)
749   if (statcb)
750     fs.lstat(abs, statcb)
751
752   function lstatcb_ (er, lstat) {
753     if (lstat && lstat.isSymbolicLink()) {
754       // If it's a symlink, then treat it as the target, unless
755       // the target does not exist, then treat it as a file.
756       return fs.stat(abs, function (er, stat) {
757         if (er)
758           self._stat2(f, abs, null, lstat, cb)
759         else
760           self._stat2(f, abs, er, stat, cb)
761       })
762     } else {
763       self._stat2(f, abs, er, lstat, cb)
764     }
765   }
766 }
767
768 Glob.prototype._stat2 = function (f, abs, er, stat, cb) {
769   if (er) {
770     this.statCache[abs] = false
771     return cb()
772   }
773
774   var needDir = f.slice(-1) === '/'
775   this.statCache[abs] = stat
776
777   if (abs.slice(-1) === '/' && !stat.isDirectory())
778     return cb(null, false, stat)
779
780   var c = stat.isDirectory() ? 'DIR' : 'FILE'
781   this.cache[abs] = this.cache[abs] || c
782
783   if (needDir && c !== 'DIR')
784     return cb()
785
786   return cb(null, c, stat)
787 }