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
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.
13 // If inGlobStar and PREFIX is symlink and points to dir
15 // else readdir(PREFIX) as 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)
29 // else // not globstar
30 // for ENTRY in ENTRIES (not dotfiles, unless pattern[n] is dot)
31 // Test ENTRY against pattern[n]
33 // If passes, PROCESS(pattern[0..n] + item + pattern[n+1 .. $])
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.
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
61 var once = require('once')
63 function glob (pattern, options, cb) {
64 if (typeof options === 'function') cb = options, options = {}
65 if (!options) options = {}
69 throw new TypeError('callback provided to sync glob')
70 return globSync(pattern, options)
73 return new Glob(pattern, options, cb)
77 var GlobSync = glob.GlobSync = globSync.GlobSync
82 glob.hasMagic = function (pattern, options_) {
83 var options = util._extend({}, options_)
84 options.noprocess = true
86 var g = new Glob(pattern, options)
87 var set = g.minimatch.set
91 for (var j = 0; j < set[0].length; j++) {
92 if (typeof set[0][j] !== 'string')
101 function Glob (pattern, options, cb) {
102 if (typeof options === 'function') {
107 if (options && options.sync) {
109 throw new TypeError('callback provided to sync glob')
110 return new GlobSync(pattern, options)
113 if (!(this instanceof Glob))
114 return new Glob(pattern, options, cb)
116 setopts(this, pattern, options)
117 this._didRealPath = false
119 // process each pattern in the minimatch set
120 var n = this.minimatch.set.length
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)
128 if (typeof cb === 'function') {
131 this.on('end', function (matches) {
137 var n = this.minimatch.set.length
139 this.matches = new Array(n)
142 this._processQueue = []
151 for (var i = 0; i < n; i ++) {
152 this._process(this.minimatch.set[i], i, false, done)
157 if (self._processing <= 0)
162 Glob.prototype._finish = function () {
163 assert(this instanceof Glob)
167 if (this.realpath && !this._didRealpath)
168 return this._realpath()
171 this.emit('end', this.found)
174 Glob.prototype._realpath = function () {
175 if (this._didRealpath)
178 this._didRealpath = true
180 var n = this.matches.length
182 return this._finish()
185 for (var i = 0; i < this.matches.length; i++)
186 this._realpathSet(i, next)
194 Glob.prototype._realpathSet = function (index, cb) {
195 var matchset = this.matches[index]
199 var found = Object.keys(matchset)
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.
212 fs.realpath(p, self.realpathCache, function (er, real) {
215 else if (er.syscall === 'stat')
218 self.emit('error', er) // srsly wtf right here
221 self.matches[index] = set
228 Glob.prototype._mark = function (p) {
229 return common.mark(this, p)
232 Glob.prototype._makeAbs = function (f) {
233 return common.makeAbs(this, f)
236 Glob.prototype.abort = function () {
241 Glob.prototype.pause = function () {
248 Glob.prototype.resume = function () {
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 ++) {
257 this._emitMatch(e[0], e[1])
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 ++) {
266 this._process(p[0], p[1], p[2], p[3])
272 Glob.prototype._process = function (pattern, index, inGlobStar, cb) {
273 assert(this instanceof Glob)
274 assert(typeof cb === 'function')
281 this._processQueue.push([pattern, index, inGlobStar, cb])
285 //console.error('PROCESS %d', this._processing, pattern)
287 // Get the first [n] parts of pattern that are all strings.
289 while (typeof pattern[n] === 'string') {
292 // now n is the index of the first one that is *not* a string.
294 // see if there's anything else
297 // if not, then this is rather simple
299 this._processSimple(pattern.join('/'), index, cb)
303 // pattern *starts* with some non-trivial item.
304 // going to readdir(cwd), but not include the prefix in matches.
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('/')
316 var remain = pattern.slice(n)
318 // get the list of entries.
322 else if (isAbsolute(prefix) || isAbsolute(pattern.join('/'))) {
323 if (!prefix || !isAbsolute(prefix))
324 prefix = '/' + prefix
329 var abs = this._makeAbs(read)
331 //if ignored, skip _processing
332 if (childrenIgnored(this, read))
335 var isGlobStar = remain[0] === minimatch.GLOBSTAR
337 this._processGlobStar(prefix, read, abs, remain, index, inGlobStar, cb)
339 this._processReaddir(prefix, read, abs, remain, index, inGlobStar, cb)
342 Glob.prototype._processReaddir = function (prefix, read, abs, remain, index, inGlobStar, cb) {
344 this._readdir(abs, inGlobStar, function (er, entries) {
345 return self._processReaddir2(prefix, read, abs, remain, index, inGlobStar, entries, cb)
349 Glob.prototype._processReaddir2 = function (prefix, read, abs, remain, index, inGlobStar, entries, cb) {
351 // if the abs isn't a dir, then nothing can match!
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.
358 var negate = !!this.minimatch.negate
359 var rawGlob = pn._glob
360 var dotOk = this.dot || rawGlob.charAt(0) === '.'
362 var matchedEntries = []
363 for (var i = 0; i < entries.length; i++) {
365 if (e.charAt(0) !== '.' || dotOk) {
367 if (negate && !prefix) {
373 matchedEntries.push(e)
377 //console.error('prd2', prefix, entries, remain[0]._glob, matchedEntries)
379 var len = matchedEntries.length
380 // If there are no matched entries, then nothing matches.
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
389 if (remain.length === 1 && !this.mark && !this.stat) {
390 if (!this.matches[index])
391 this.matches[index] = Object.create(null)
393 for (var i = 0; i < len; i ++) {
394 var e = matchedEntries[i]
402 if (e.charAt(0) === '/' && !this.nomount) {
403 e = path.join(this.root, e)
405 this._emitMatch(index, e)
407 // This was the last one, and no stats were needed
411 // now test all matched entries as stand-ins for that part
414 for (var i = 0; i < len; i ++) {
415 var e = matchedEntries[i]
423 this._process([e].concat(remain), index, inGlobStar, cb)
428 Glob.prototype._emitMatch = function (index, e) {
432 if (this.matches[index][e])
436 this._emitQueue.push([index, e])
440 var abs = this._makeAbs(e)
443 var c = this.cache[abs]
444 if (c === 'DIR' || Array.isArray(c))
451 this.matches[index][e] = true
453 var st = this.statCache[abs]
455 this.emit('stat', e, st)
457 this.emit('match', e)
460 Glob.prototype._readdirInGlobStar = function (abs, cb) {
464 // follow all symlinked directories forever
465 // just proceed as if this is a non-globstar situation
467 return this._readdir(abs, false, cb)
469 var lstatkey = 'lstat\0' + abs
471 var lstatcb = inflight(lstatkey, lstatcb_)
474 fs.lstat(abs, lstatcb)
476 function lstatcb_ (er, lstat) {
480 var isSym = lstat.isSymbolicLink()
481 self.symlinks[abs] = isSym
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'
489 self._readdir(abs, false, cb)
493 Glob.prototype._readdir = function (abs, inGlobStar, cb) {
497 cb = inflight('readdir\0'+abs+'\0'+inGlobStar, cb)
501 //console.error('RD %j %j', +inGlobStar, abs)
502 if (inGlobStar && !ownProp(this.symlinks, abs))
503 return this._readdirInGlobStar(abs, cb)
505 if (ownProp(this.cache, abs)) {
506 var c = this.cache[abs]
507 if (!c || c === 'FILE')
510 if (Array.isArray(c))
515 fs.readdir(abs, readdirCb(this, abs, cb))
518 function readdirCb (self, abs, cb) {
519 return function (er, entries) {
521 self._readdirError(abs, er, cb)
523 self._readdirEntries(abs, entries, cb)
527 Glob.prototype._readdirEntries = function (abs, entries, cb) {
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 ++) {
545 this.cache[abs] = entries
546 return cb(null, entries)
549 Glob.prototype._readdirError = function (f, er, cb) {
553 // handle errors, and cache the information
555 case 'ENOTDIR': // totally normal. means it *does* exist.
556 this.cache[this._makeAbs(f)] = 'FILE'
559 case 'ENOENT': // not terribly unusual
563 this.cache[this._makeAbs(f)] = false
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)
575 Glob.prototype._processGlobStar = function (prefix, read, abs, remain, index, inGlobStar, cb) {
577 this._readdir(abs, inGlobStar, function (er, entries) {
578 self._processGlobStar2(prefix, read, abs, remain, index, inGlobStar, entries, cb)
583 Glob.prototype._processGlobStar2 = function (prefix, read, abs, remain, index, inGlobStar, entries, cb) {
584 //console.error('pgs2', prefix, remain[0], entries)
586 // no entries means not a dir, so it can never have matches
587 // foo.txt/** doesn't match foo.txt
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)
597 // the noGlobStar pattern exits the inGlobStar state
598 this._process(noGlobStar, index, false, cb)
600 var isSym = this.symlinks[abs]
601 var len = entries.length
603 // If it's a symlink, and we're in a globstar, then stop
604 if (isSym && inGlobStar)
607 for (var i = 0; i < len; i++) {
609 if (e.charAt(0) === '.' && !this.dot)
612 // these two cases enter the inGlobStar state
613 var instead = gspref.concat(entries[i], remainWithoutGlobStar)
614 this._process(instead, index, true, cb)
616 var below = gspref.concat(entries[i], remain)
617 this._process(below, index, true, cb)
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?
627 this._stat(prefix, function (er, exists) {
628 self._processSimple2(prefix, index, er, exists, cb)
631 Glob.prototype._processSimple2 = function (prefix, index, er, exists, cb) {
633 //console.error('ps2', prefix, exists)
635 if (!this.matches[index])
636 this.matches[index] = Object.create(null)
638 // If it doesn't exist, then just mark the lack of results
642 if (prefix && isAbsolute(prefix) && !this.nomount) {
643 var trail = /[\/\\]$/.test(prefix)
644 if (prefix.charAt(0) === '/') {
645 prefix = path.join(this.root, prefix)
647 prefix = path.resolve(this.root, prefix)
653 if (process.platform === 'win32')
654 prefix = prefix.replace(/\\/g, '/')
656 // Mark this as a match
657 this._emitMatch(index, prefix)
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) === '/'
666 if (f.length > this.maxLength)
669 if (!this.stat && ownProp(this.cache, abs)) {
670 var c = this.cache[abs]
672 if (Array.isArray(c))
675 // It exists, but maybe not how we need it
676 if (!needDir || c === 'DIR')
679 if (needDir && c === 'FILE')
682 // otherwise we have to stat, because maybe c=true
683 // if we know it exists, but not what it is.
687 var stat = this.statCache[abs]
688 if (stat !== undefined) {
690 return cb(null, stat)
692 var type = stat.isDirectory() ? 'DIR' : 'FILE'
693 if (needDir && type === 'FILE')
696 return cb(null, type, stat)
701 var statcb = inflight('stat\0' + abs, lstatcb_)
703 fs.lstat(abs, statcb)
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) {
711 self._stat2(f, abs, null, lstat, cb)
713 self._stat2(f, abs, er, stat, cb)
716 self._stat2(f, abs, er, lstat, cb)
721 Glob.prototype._stat2 = function (f, abs, er, stat, cb) {
723 this.statCache[abs] = false
727 var needDir = f.slice(-1) === '/'
728 this.statCache[abs] = stat
730 if (abs.slice(-1) === '/' && !stat.isDirectory())
731 return cb(null, false, stat)
733 var c = stat.isDirectory() ? 'DIR' : 'FILE'
734 this.cache[abs] = this.cache[abs] || c
736 if (needDir && c !== 'DIR')
739 return cb(null, c, stat)