glob.js 18 KB

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