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