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