glob.js 18 KB

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