glob.js (19499B)
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 (isIgnored(this, e)) 461 return 462 463 if (this.paused) { 464 this._emitQueue.push([index, e]) 465 return 466 } 467 468 var abs = isAbsolute(e) ? e : this._makeAbs(e) 469 470 if (this.mark) 471 e = this._mark(e) 472 473 if (this.absolute) 474 e = abs 475 476 if (this.matches[index][e]) 477 return 478 479 if (this.nodir) { 480 var c = this.cache[abs] 481 if (c === 'DIR' || Array.isArray(c)) 482 return 483 } 484 485 this.matches[index][e] = true 486 487 var st = this.statCache[abs] 488 if (st) 489 this.emit('stat', e, st) 490 491 this.emit('match', e) 492 } 493 494 Glob.prototype._readdirInGlobStar = function (abs, cb) { 495 if (this.aborted) 496 return 497 498 // follow all symlinked directories forever 499 // just proceed as if this is a non-globstar situation 500 if (this.follow) 501 return this._readdir(abs, false, cb) 502 503 var lstatkey = 'lstat\0' + abs 504 var self = this 505 var lstatcb = inflight(lstatkey, lstatcb_) 506 507 if (lstatcb) 508 fs.lstat(abs, lstatcb) 509 510 function lstatcb_ (er, lstat) { 511 if (er && er.code === 'ENOENT') 512 return cb() 513 514 var isSym = lstat && lstat.isSymbolicLink() 515 self.symlinks[abs] = isSym 516 517 // If it's not a symlink or a dir, then it's definitely a regular file. 518 // don't bother doing a readdir in that case. 519 if (!isSym && lstat && !lstat.isDirectory()) { 520 self.cache[abs] = 'FILE' 521 cb() 522 } else 523 self._readdir(abs, false, cb) 524 } 525 } 526 527 Glob.prototype._readdir = function (abs, inGlobStar, cb) { 528 if (this.aborted) 529 return 530 531 cb = inflight('readdir\0'+abs+'\0'+inGlobStar, cb) 532 if (!cb) 533 return 534 535 //console.error('RD %j %j', +inGlobStar, abs) 536 if (inGlobStar && !ownProp(this.symlinks, abs)) 537 return this._readdirInGlobStar(abs, cb) 538 539 if (ownProp(this.cache, abs)) { 540 var c = this.cache[abs] 541 if (!c || c === 'FILE') 542 return cb() 543 544 if (Array.isArray(c)) 545 return cb(null, c) 546 } 547 548 var self = this 549 fs.readdir(abs, readdirCb(this, abs, cb)) 550 } 551 552 function readdirCb (self, abs, cb) { 553 return function (er, entries) { 554 if (er) 555 self._readdirError(abs, er, cb) 556 else 557 self._readdirEntries(abs, entries, cb) 558 } 559 } 560 561 Glob.prototype._readdirEntries = function (abs, entries, cb) { 562 if (this.aborted) 563 return 564 565 // if we haven't asked to stat everything, then just 566 // assume that everything in there exists, so we can avoid 567 // having to stat it a second time. 568 if (!this.mark && !this.stat) { 569 for (var i = 0; i < entries.length; i ++) { 570 var e = entries[i] 571 if (abs === '/') 572 e = abs + e 573 else 574 e = abs + '/' + e 575 this.cache[e] = true 576 } 577 } 578 579 this.cache[abs] = entries 580 return cb(null, entries) 581 } 582 583 Glob.prototype._readdirError = function (f, er, cb) { 584 if (this.aborted) 585 return 586 587 // handle errors, and cache the information 588 switch (er.code) { 589 case 'ENOTSUP': // https://github.com/isaacs/node-glob/issues/205 590 case 'ENOTDIR': // totally normal. means it *does* exist. 591 var abs = this._makeAbs(f) 592 this.cache[abs] = 'FILE' 593 if (abs === this.cwdAbs) { 594 var error = new Error(er.code + ' invalid cwd ' + this.cwd) 595 error.path = this.cwd 596 error.code = er.code 597 this.emit('error', error) 598 this.abort() 599 } 600 break 601 602 case 'ENOENT': // not terribly unusual 603 case 'ELOOP': 604 case 'ENAMETOOLONG': 605 case 'UNKNOWN': 606 this.cache[this._makeAbs(f)] = false 607 break 608 609 default: // some unusual error. Treat as failure. 610 this.cache[this._makeAbs(f)] = false 611 if (this.strict) { 612 this.emit('error', er) 613 // If the error is handled, then we abort 614 // if not, we threw out of here 615 this.abort() 616 } 617 if (!this.silent) 618 console.error('glob error', er) 619 break 620 } 621 622 return cb() 623 } 624 625 Glob.prototype._processGlobStar = function (prefix, read, abs, remain, index, inGlobStar, cb) { 626 var self = this 627 this._readdir(abs, inGlobStar, function (er, entries) { 628 self._processGlobStar2(prefix, read, abs, remain, index, inGlobStar, entries, cb) 629 }) 630 } 631 632 633 Glob.prototype._processGlobStar2 = function (prefix, read, abs, remain, index, inGlobStar, entries, cb) { 634 //console.error('pgs2', prefix, remain[0], entries) 635 636 // no entries means not a dir, so it can never have matches 637 // foo.txt/** doesn't match foo.txt 638 if (!entries) 639 return cb() 640 641 // test without the globstar, and with every child both below 642 // and replacing the globstar. 643 var remainWithoutGlobStar = remain.slice(1) 644 var gspref = prefix ? [ prefix ] : [] 645 var noGlobStar = gspref.concat(remainWithoutGlobStar) 646 647 // the noGlobStar pattern exits the inGlobStar state 648 this._process(noGlobStar, index, false, cb) 649 650 var isSym = this.symlinks[abs] 651 var len = entries.length 652 653 // If it's a symlink, and we're in a globstar, then stop 654 if (isSym && inGlobStar) 655 return cb() 656 657 for (var i = 0; i < len; i++) { 658 var e = entries[i] 659 if (e.charAt(0) === '.' && !this.dot) 660 continue 661 662 // these two cases enter the inGlobStar state 663 var instead = gspref.concat(entries[i], remainWithoutGlobStar) 664 this._process(instead, index, true, cb) 665 666 var below = gspref.concat(entries[i], remain) 667 this._process(below, index, true, cb) 668 } 669 670 cb() 671 } 672 673 Glob.prototype._processSimple = function (prefix, index, cb) { 674 // XXX review this. Shouldn't it be doing the mounting etc 675 // before doing stat? kinda weird? 676 var self = this 677 this._stat(prefix, function (er, exists) { 678 self._processSimple2(prefix, index, er, exists, cb) 679 }) 680 } 681 Glob.prototype._processSimple2 = function (prefix, index, er, exists, cb) { 682 683 //console.error('ps2', prefix, exists) 684 685 if (!this.matches[index]) 686 this.matches[index] = Object.create(null) 687 688 // If it doesn't exist, then just mark the lack of results 689 if (!exists) 690 return cb() 691 692 if (prefix && isAbsolute(prefix) && !this.nomount) { 693 var trail = /[\/\\]$/.test(prefix) 694 if (prefix.charAt(0) === '/') { 695 prefix = path.join(this.root, prefix) 696 } else { 697 prefix = path.resolve(this.root, prefix) 698 if (trail) 699 prefix += '/' 700 } 701 } 702 703 if (process.platform === 'win32') 704 prefix = prefix.replace(/\\/g, '/') 705 706 // Mark this as a match 707 this._emitMatch(index, prefix) 708 cb() 709 } 710 711 // Returns either 'DIR', 'FILE', or false 712 Glob.prototype._stat = function (f, cb) { 713 var abs = this._makeAbs(f) 714 var needDir = f.slice(-1) === '/' 715 716 if (f.length > this.maxLength) 717 return cb() 718 719 if (!this.stat && ownProp(this.cache, abs)) { 720 var c = this.cache[abs] 721 722 if (Array.isArray(c)) 723 c = 'DIR' 724 725 // It exists, but maybe not how we need it 726 if (!needDir || c === 'DIR') 727 return cb(null, c) 728 729 if (needDir && c === 'FILE') 730 return cb() 731 732 // otherwise we have to stat, because maybe c=true 733 // if we know it exists, but not what it is. 734 } 735 736 var exists 737 var stat = this.statCache[abs] 738 if (stat !== undefined) { 739 if (stat === false) 740 return cb(null, stat) 741 else { 742 var type = stat.isDirectory() ? 'DIR' : 'FILE' 743 if (needDir && type === 'FILE') 744 return cb() 745 else 746 return cb(null, type, stat) 747 } 748 } 749 750 var self = this 751 var statcb = inflight('stat\0' + abs, lstatcb_) 752 if (statcb) 753 fs.lstat(abs, statcb) 754 755 function lstatcb_ (er, lstat) { 756 if (lstat && lstat.isSymbolicLink()) { 757 // If it's a symlink, then treat it as the target, unless 758 // the target does not exist, then treat it as a file. 759 return fs.stat(abs, function (er, stat) { 760 if (er) 761 self._stat2(f, abs, null, lstat, cb) 762 else 763 self._stat2(f, abs, er, stat, cb) 764 }) 765 } else { 766 self._stat2(f, abs, er, lstat, cb) 767 } 768 } 769 } 770 771 Glob.prototype._stat2 = function (f, abs, er, stat, cb) { 772 if (er && (er.code === 'ENOENT' || er.code === 'ENOTDIR')) { 773 this.statCache[abs] = false 774 return cb() 775 } 776 777 var needDir = f.slice(-1) === '/' 778 this.statCache[abs] = stat 779 780 if (abs.slice(-1) === '/' && stat && !stat.isDirectory()) 781 return cb(null, false, stat) 782 783 var c = true 784 if (stat) 785 c = stat.isDirectory() ? 'DIR' : 'FILE' 786 this.cache[abs] = this.cache[abs] || c 787 788 if (needDir && c === 'FILE') 789 return cb() 790 791 return cb(null, c, stat) 792 }