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 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
63 var once = require('once')
65 function glob (pattern, options, cb) {
66 if (typeof options === 'function') cb = options, options = {}
67 if (!options) options = {}
71 throw new TypeError('callback provided to sync glob')
72 return globSync(pattern, options)
75 return new Glob(pattern, options, cb)
79 var GlobSync = glob.GlobSync = globSync.GlobSync
84 function extend (origin, add) {
85 if (add === null || typeof add !== 'object') {
89 var keys = Object.keys(add)
92 origin[keys[i]] = add[keys[i]]
97 glob.hasMagic = function (pattern, options_) {
98 var options = extend({}, options_)
99 options.noprocess = true
101 var g = new Glob(pattern, options)
102 var set = g.minimatch.set
110 for (var j = 0; j < set[0].length; j++) {
111 if (typeof set[0][j] !== 'string')
120 function Glob (pattern, options, cb) {
121 if (typeof options === 'function') {
126 if (options && options.sync) {
128 throw new TypeError('callback provided to sync glob')
129 return new GlobSync(pattern, options)
132 if (!(this instanceof Glob))
133 return new Glob(pattern, options, cb)
135 setopts(this, pattern, options)
136 this._didRealPath = false
138 // process each pattern in the minimatch set
139 var n = this.minimatch.set.length
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)
147 if (typeof cb === 'function') {
150 this.on('end', function (matches) {
159 this._processQueue = []
169 for (var i = 0; i < n; i ++) {
170 this._process(this.minimatch.set[i], i, false, done)
176 if (self._processing <= 0) {
178 process.nextTick(function () {
188 Glob.prototype._finish = function () {
189 assert(this instanceof Glob)
193 if (this.realpath && !this._didRealpath)
194 return this._realpath()
197 this.emit('end', this.found)
200 Glob.prototype._realpath = function () {
201 if (this._didRealpath)
204 this._didRealpath = true
206 var n = this.matches.length
208 return this._finish()
211 for (var i = 0; i < this.matches.length; i++)
212 this._realpathSet(i, next)
220 Glob.prototype._realpathSet = function (index, cb) {
221 var matchset = this.matches[index]
225 var found = Object.keys(matchset)
232 var set = this.matches[index] = Object.create(null)
233 found.forEach(function (p, i) {
234 // If there's a problem with the stat, then it means that
235 // one or more of the links in the realpath couldn't be
236 // resolved. just return the abs value in that case.
238 rp.realpath(p, self.realpathCache, function (er, real) {
241 else if (er.syscall === 'stat')
244 self.emit('error', er) // srsly wtf right here
247 self.matches[index] = set
254 Glob.prototype._mark = function (p) {
255 return common.mark(this, p)
258 Glob.prototype._makeAbs = function (f) {
259 return common.makeAbs(this, f)
262 Glob.prototype.abort = function () {
267 Glob.prototype.pause = function () {
274 Glob.prototype.resume = function () {
278 if (this._emitQueue.length) {
279 var eq = this._emitQueue.slice(0)
280 this._emitQueue.length = 0
281 for (var i = 0; i < eq.length; i ++) {
283 this._emitMatch(e[0], e[1])
286 if (this._processQueue.length) {
287 var pq = this._processQueue.slice(0)
288 this._processQueue.length = 0
289 for (var i = 0; i < pq.length; i ++) {
292 this._process(p[0], p[1], p[2], p[3])
298 Glob.prototype._process = function (pattern, index, inGlobStar, cb) {
299 assert(this instanceof Glob)
300 assert(typeof cb === 'function')
307 this._processQueue.push([pattern, index, inGlobStar, cb])
311 //console.error('PROCESS %d', this._processing, pattern)
313 // Get the first [n] parts of pattern that are all strings.
315 while (typeof pattern[n] === 'string') {
318 // now n is the index of the first one that is *not* a string.
320 // see if there's anything else
323 // if not, then this is rather simple
325 this._processSimple(pattern.join('/'), index, cb)
329 // pattern *starts* with some non-trivial item.
330 // going to readdir(cwd), but not include the prefix in matches.
335 // pattern has some string bits in the front.
336 // whatever it starts with, whether that's 'absolute' like /foo/bar,
337 // or 'relative' like '../baz'
338 prefix = pattern.slice(0, n).join('/')
342 var remain = pattern.slice(n)
344 // get the list of entries.
348 else if (isAbsolute(prefix) || isAbsolute(pattern.join('/'))) {
349 if (!prefix || !isAbsolute(prefix))
350 prefix = '/' + prefix
355 var abs = this._makeAbs(read)
357 //if ignored, skip _processing
358 if (childrenIgnored(this, read))
361 var isGlobStar = remain[0] === minimatch.GLOBSTAR
363 this._processGlobStar(prefix, read, abs, remain, index, inGlobStar, cb)
365 this._processReaddir(prefix, read, abs, remain, index, inGlobStar, cb)
368 Glob.prototype._processReaddir = function (prefix, read, abs, remain, index, inGlobStar, cb) {
370 this._readdir(abs, inGlobStar, function (er, entries) {
371 return self._processReaddir2(prefix, read, abs, remain, index, inGlobStar, entries, cb)
375 Glob.prototype._processReaddir2 = function (prefix, read, abs, remain, index, inGlobStar, entries, cb) {
377 // if the abs isn't a dir, then nothing can match!
381 // It will only match dot entries if it starts with a dot, or if
382 // dot is set. Stuff like @(.foo|.bar) isn't allowed.
384 var negate = !!this.minimatch.negate
385 var rawGlob = pn._glob
386 var dotOk = this.dot || rawGlob.charAt(0) === '.'
388 var matchedEntries = []
389 for (var i = 0; i < entries.length; i++) {
391 if (e.charAt(0) !== '.' || dotOk) {
393 if (negate && !prefix) {
399 matchedEntries.push(e)
403 //console.error('prd2', prefix, entries, remain[0]._glob, matchedEntries)
405 var len = matchedEntries.length
406 // If there are no matched entries, then nothing matches.
410 // if this is the last remaining pattern bit, then no need for
411 // an additional stat *unless* the user has specified mark or
412 // stat explicitly. We know they exist, since readdir returned
415 if (remain.length === 1 && !this.mark && !this.stat) {
416 if (!this.matches[index])
417 this.matches[index] = Object.create(null)
419 for (var i = 0; i < len; i ++) {
420 var e = matchedEntries[i]
428 if (e.charAt(0) === '/' && !this.nomount) {
429 e = path.join(this.root, e)
431 this._emitMatch(index, e)
433 // This was the last one, and no stats were needed
437 // now test all matched entries as stand-ins for that part
440 for (var i = 0; i < len; i ++) {
441 var e = matchedEntries[i]
449 this._process([e].concat(remain), index, inGlobStar, cb)
454 Glob.prototype._emitMatch = function (index, e) {
458 if (isIgnored(this, e))
462 this._emitQueue.push([index, e])
466 var abs = isAbsolute(e) ? e : this._makeAbs(e)
474 if (this.matches[index][e])
478 var c = this.cache[abs]
479 if (c === 'DIR' || Array.isArray(c))
483 this.matches[index][e] = true
485 var st = this.statCache[abs]
487 this.emit('stat', e, st)
489 this.emit('match', e)
492 Glob.prototype._readdirInGlobStar = function (abs, cb) {
496 // follow all symlinked directories forever
497 // just proceed as if this is a non-globstar situation
499 return this._readdir(abs, false, cb)
501 var lstatkey = 'lstat\0' + abs
503 var lstatcb = inflight(lstatkey, lstatcb_)
506 fs.lstat(abs, lstatcb)
508 function lstatcb_ (er, lstat) {
509 if (er && er.code === 'ENOENT')
512 var isSym = lstat && lstat.isSymbolicLink()
513 self.symlinks[abs] = isSym
515 // If it's not a symlink or a dir, then it's definitely a regular file.
516 // don't bother doing a readdir in that case.
517 if (!isSym && lstat && !lstat.isDirectory()) {
518 self.cache[abs] = 'FILE'
521 self._readdir(abs, false, cb)
525 Glob.prototype._readdir = function (abs, inGlobStar, cb) {
529 cb = inflight('readdir\0'+abs+'\0'+inGlobStar, cb)
533 //console.error('RD %j %j', +inGlobStar, abs)
534 if (inGlobStar && !ownProp(this.symlinks, abs))
535 return this._readdirInGlobStar(abs, cb)
537 if (ownProp(this.cache, abs)) {
538 var c = this.cache[abs]
539 if (!c || c === 'FILE')
542 if (Array.isArray(c))
547 fs.readdir(abs, readdirCb(this, abs, cb))
550 function readdirCb (self, abs, cb) {
551 return function (er, entries) {
553 self._readdirError(abs, er, cb)
555 self._readdirEntries(abs, entries, cb)
559 Glob.prototype._readdirEntries = function (abs, entries, cb) {
563 // if we haven't asked to stat everything, then just
564 // assume that everything in there exists, so we can avoid
565 // having to stat it a second time.
566 if (!this.mark && !this.stat) {
567 for (var i = 0; i < entries.length; i ++) {
577 this.cache[abs] = entries
578 return cb(null, entries)
581 Glob.prototype._readdirError = function (f, er, cb) {
585 // handle errors, and cache the information
587 case 'ENOTSUP': // https://github.com/isaacs/node-glob/issues/205
588 case 'ENOTDIR': // totally normal. means it *does* exist.
589 var abs = this._makeAbs(f)
590 this.cache[abs] = 'FILE'
591 if (abs === this.cwdAbs) {
592 var error = new Error(er.code + ' invalid cwd ' + this.cwd)
593 error.path = this.cwd
595 this.emit('error', error)
600 case 'ENOENT': // not terribly unusual
604 this.cache[this._makeAbs(f)] = false
607 default: // some unusual error. Treat as failure.
608 this.cache[this._makeAbs(f)] = false
610 this.emit('error', er)
611 // If the error is handled, then we abort
612 // if not, we threw out of here
616 console.error('glob error', er)
623 Glob.prototype._processGlobStar = function (prefix, read, abs, remain, index, inGlobStar, cb) {
625 this._readdir(abs, inGlobStar, function (er, entries) {
626 self._processGlobStar2(prefix, read, abs, remain, index, inGlobStar, entries, cb)
631 Glob.prototype._processGlobStar2 = function (prefix, read, abs, remain, index, inGlobStar, entries, cb) {
632 //console.error('pgs2', prefix, remain[0], entries)
634 // no entries means not a dir, so it can never have matches
635 // foo.txt/** doesn't match foo.txt
639 // test without the globstar, and with every child both below
640 // and replacing the globstar.
641 var remainWithoutGlobStar = remain.slice(1)
642 var gspref = prefix ? [ prefix ] : []
643 var noGlobStar = gspref.concat(remainWithoutGlobStar)
645 // the noGlobStar pattern exits the inGlobStar state
646 this._process(noGlobStar, index, false, cb)
648 var isSym = this.symlinks[abs]
649 var len = entries.length
651 // If it's a symlink, and we're in a globstar, then stop
652 if (isSym && inGlobStar)
655 for (var i = 0; i < len; i++) {
657 if (e.charAt(0) === '.' && !this.dot)
660 // these two cases enter the inGlobStar state
661 var instead = gspref.concat(entries[i], remainWithoutGlobStar)
662 this._process(instead, index, true, cb)
664 var below = gspref.concat(entries[i], remain)
665 this._process(below, index, true, cb)
671 Glob.prototype._processSimple = function (prefix, index, cb) {
672 // XXX review this. Shouldn't it be doing the mounting etc
673 // before doing stat? kinda weird?
675 this._stat(prefix, function (er, exists) {
676 self._processSimple2(prefix, index, er, exists, cb)
679 Glob.prototype._processSimple2 = function (prefix, index, er, exists, cb) {
681 //console.error('ps2', prefix, exists)
683 if (!this.matches[index])
684 this.matches[index] = Object.create(null)
686 // If it doesn't exist, then just mark the lack of results
690 if (prefix && isAbsolute(prefix) && !this.nomount) {
691 var trail = /[\/\\]$/.test(prefix)
692 if (prefix.charAt(0) === '/') {
693 prefix = path.join(this.root, prefix)
695 prefix = path.resolve(this.root, prefix)
701 if (process.platform === 'win32')
702 prefix = prefix.replace(/\\/g, '/')
704 // Mark this as a match
705 this._emitMatch(index, prefix)
709 // Returns either 'DIR', 'FILE', or false
710 Glob.prototype._stat = function (f, cb) {
711 var abs = this._makeAbs(f)
712 var needDir = f.slice(-1) === '/'
714 if (f.length > this.maxLength)
717 if (!this.stat && ownProp(this.cache, abs)) {
718 var c = this.cache[abs]
720 if (Array.isArray(c))
723 // It exists, but maybe not how we need it
724 if (!needDir || c === 'DIR')
727 if (needDir && c === 'FILE')
730 // otherwise we have to stat, because maybe c=true
731 // if we know it exists, but not what it is.
735 var stat = this.statCache[abs]
736 if (stat !== undefined) {
738 return cb(null, stat)
740 var type = stat.isDirectory() ? 'DIR' : 'FILE'
741 if (needDir && type === 'FILE')
744 return cb(null, type, stat)
749 var statcb = inflight('stat\0' + abs, lstatcb_)
751 fs.lstat(abs, statcb)
753 function lstatcb_ (er, lstat) {
754 if (lstat && lstat.isSymbolicLink()) {
755 // If it's a symlink, then treat it as the target, unless
756 // the target does not exist, then treat it as a file.
757 return fs.stat(abs, function (er, stat) {
759 self._stat2(f, abs, null, lstat, cb)
761 self._stat2(f, abs, er, stat, cb)
764 self._stat2(f, abs, er, lstat, cb)
769 Glob.prototype._stat2 = function (f, abs, er, stat, cb) {
770 if (er && (er.code === 'ENOENT' || er.code === 'ENOTDIR')) {
771 this.statCache[abs] = false
775 var needDir = f.slice(-1) === '/'
776 this.statCache[abs] = stat
778 if (abs.slice(-1) === '/' && stat && !stat.isDirectory())
779 return cb(null, false, stat)
783 c = stat.isDirectory() ? 'DIR' : 'FILE'
784 this.cache[abs] = this.cache[abs] || c
786 if (needDir && c === 'FILE')
789 return cb(null, c, stat)