sync.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484
  1. module.exports = globSync
  2. globSync.GlobSync = GlobSync
  3. var fs = require('fs')
  4. var rp = require('fs.realpath')
  5. var minimatch = require('minimatch')
  6. var Minimatch = minimatch.Minimatch
  7. var Glob = require('./glob.js').Glob
  8. var util = require('util')
  9. var path = require('path')
  10. var assert = require('assert')
  11. var isAbsolute = require('path-is-absolute')
  12. var common = require('./common.js')
  13. var setopts = common.setopts
  14. var ownProp = common.ownProp
  15. var childrenIgnored = common.childrenIgnored
  16. var isIgnored = common.isIgnored
  17. function globSync (pattern, options) {
  18. if (typeof options === 'function' || arguments.length === 3)
  19. throw new TypeError('callback provided to sync glob\n'+
  20. 'See: https://github.com/isaacs/node-glob/issues/167')
  21. return new GlobSync(pattern, options).found
  22. }
  23. function GlobSync (pattern, options) {
  24. if (!pattern)
  25. throw new Error('must provide pattern')
  26. if (typeof options === 'function' || arguments.length === 3)
  27. throw new TypeError('callback provided to sync glob\n'+
  28. 'See: https://github.com/isaacs/node-glob/issues/167')
  29. if (!(this instanceof GlobSync))
  30. return new GlobSync(pattern, options)
  31. setopts(this, pattern, options)
  32. if (this.noprocess)
  33. return this
  34. var n = this.minimatch.set.length
  35. this.matches = new Array(n)
  36. for (var i = 0; i < n; i ++) {
  37. this._process(this.minimatch.set[i], i, false)
  38. }
  39. this._finish()
  40. }
  41. GlobSync.prototype._finish = function () {
  42. assert(this instanceof GlobSync)
  43. if (this.realpath) {
  44. var self = this
  45. this.matches.forEach(function (matchset, index) {
  46. var set = self.matches[index] = Object.create(null)
  47. for (var p in matchset) {
  48. try {
  49. p = self._makeAbs(p)
  50. var real = rp.realpathSync(p, self.realpathCache)
  51. set[real] = true
  52. } catch (er) {
  53. if (er.syscall === 'stat')
  54. set[self._makeAbs(p)] = true
  55. else
  56. throw er
  57. }
  58. }
  59. })
  60. }
  61. common.finish(this)
  62. }
  63. GlobSync.prototype._process = function (pattern, index, inGlobStar) {
  64. assert(this instanceof GlobSync)
  65. // Get the first [n] parts of pattern that are all strings.
  66. var n = 0
  67. while (typeof pattern[n] === 'string') {
  68. n ++
  69. }
  70. // now n is the index of the first one that is *not* a string.
  71. // See if there's anything else
  72. var prefix
  73. switch (n) {
  74. // if not, then this is rather simple
  75. case pattern.length:
  76. this._processSimple(pattern.join('/'), index)
  77. return
  78. case 0:
  79. // pattern *starts* with some non-trivial item.
  80. // going to readdir(cwd), but not include the prefix in matches.
  81. prefix = null
  82. break
  83. default:
  84. // pattern has some string bits in the front.
  85. // whatever it starts with, whether that's 'absolute' like /foo/bar,
  86. // or 'relative' like '../baz'
  87. prefix = pattern.slice(0, n).join('/')
  88. break
  89. }
  90. var remain = pattern.slice(n)
  91. // get the list of entries.
  92. var read
  93. if (prefix === null)
  94. read = '.'
  95. else if (isAbsolute(prefix) || isAbsolute(pattern.join('/'))) {
  96. if (!prefix || !isAbsolute(prefix))
  97. prefix = '/' + prefix
  98. read = prefix
  99. } else
  100. read = prefix
  101. var abs = this._makeAbs(read)
  102. //if ignored, skip processing
  103. if (childrenIgnored(this, read))
  104. return
  105. var isGlobStar = remain[0] === minimatch.GLOBSTAR
  106. if (isGlobStar)
  107. this._processGlobStar(prefix, read, abs, remain, index, inGlobStar)
  108. else
  109. this._processReaddir(prefix, read, abs, remain, index, inGlobStar)
  110. }
  111. GlobSync.prototype._processReaddir = function (prefix, read, abs, remain, index, inGlobStar) {
  112. var entries = this._readdir(abs, inGlobStar)
  113. // if the abs isn't a dir, then nothing can match!
  114. if (!entries)
  115. return
  116. // It will only match dot entries if it starts with a dot, or if
  117. // dot is set. Stuff like @(.foo|.bar) isn't allowed.
  118. var pn = remain[0]
  119. var negate = !!this.minimatch.negate
  120. var rawGlob = pn._glob
  121. var dotOk = this.dot || rawGlob.charAt(0) === '.'
  122. var matchedEntries = []
  123. for (var i = 0; i < entries.length; i++) {
  124. var e = entries[i]
  125. if (e.charAt(0) !== '.' || dotOk) {
  126. var m
  127. if (negate && !prefix) {
  128. m = !e.match(pn)
  129. } else {
  130. m = e.match(pn)
  131. }
  132. if (m)
  133. matchedEntries.push(e)
  134. }
  135. }
  136. var len = matchedEntries.length
  137. // If there are no matched entries, then nothing matches.
  138. if (len === 0)
  139. return
  140. // if this is the last remaining pattern bit, then no need for
  141. // an additional stat *unless* the user has specified mark or
  142. // stat explicitly. We know they exist, since readdir returned
  143. // them.
  144. if (remain.length === 1 && !this.mark && !this.stat) {
  145. if (!this.matches[index])
  146. this.matches[index] = Object.create(null)
  147. for (var i = 0; i < len; i ++) {
  148. var e = matchedEntries[i]
  149. if (prefix) {
  150. if (prefix.slice(-1) !== '/')
  151. e = prefix + '/' + e
  152. else
  153. e = prefix + e
  154. }
  155. if (e.charAt(0) === '/' && !this.nomount) {
  156. e = path.join(this.root, e)
  157. }
  158. this._emitMatch(index, e)
  159. }
  160. // This was the last one, and no stats were needed
  161. return
  162. }
  163. // now test all matched entries as stand-ins for that part
  164. // of the pattern.
  165. remain.shift()
  166. for (var i = 0; i < len; i ++) {
  167. var e = matchedEntries[i]
  168. var newPattern
  169. if (prefix)
  170. newPattern = [prefix, e]
  171. else
  172. newPattern = [e]
  173. this._process(newPattern.concat(remain), index, inGlobStar)
  174. }
  175. }
  176. GlobSync.prototype._emitMatch = function (index, e) {
  177. if (isIgnored(this, e))
  178. return
  179. var abs = this._makeAbs(e)
  180. if (this.mark)
  181. e = this._mark(e)
  182. if (this.absolute) {
  183. e = abs
  184. }
  185. if (this.matches[index][e])
  186. return
  187. if (this.nodir) {
  188. var c = this.cache[abs]
  189. if (c === 'DIR' || Array.isArray(c))
  190. return
  191. }
  192. this.matches[index][e] = true
  193. if (this.stat)
  194. this._stat(e)
  195. }
  196. GlobSync.prototype._readdirInGlobStar = function (abs) {
  197. // follow all symlinked directories forever
  198. // just proceed as if this is a non-globstar situation
  199. if (this.follow)
  200. return this._readdir(abs, false)
  201. var entries
  202. var lstat
  203. var stat
  204. try {
  205. lstat = fs.lstatSync(abs)
  206. } catch (er) {
  207. if (er.code === 'ENOENT') {
  208. // lstat failed, doesn't exist
  209. return null
  210. }
  211. }
  212. var isSym = lstat && lstat.isSymbolicLink()
  213. this.symlinks[abs] = isSym
  214. // If it's not a symlink or a dir, then it's definitely a regular file.
  215. // don't bother doing a readdir in that case.
  216. if (!isSym && lstat && !lstat.isDirectory())
  217. this.cache[abs] = 'FILE'
  218. else
  219. entries = this._readdir(abs, false)
  220. return entries
  221. }
  222. GlobSync.prototype._readdir = function (abs, inGlobStar) {
  223. var entries
  224. if (inGlobStar && !ownProp(this.symlinks, abs))
  225. return this._readdirInGlobStar(abs)
  226. if (ownProp(this.cache, abs)) {
  227. var c = this.cache[abs]
  228. if (!c || c === 'FILE')
  229. return null
  230. if (Array.isArray(c))
  231. return c
  232. }
  233. try {
  234. return this._readdirEntries(abs, fs.readdirSync(abs))
  235. } catch (er) {
  236. this._readdirError(abs, er)
  237. return null
  238. }
  239. }
  240. GlobSync.prototype._readdirEntries = function (abs, entries) {
  241. // if we haven't asked to stat everything, then just
  242. // assume that everything in there exists, so we can avoid
  243. // having to stat it a second time.
  244. if (!this.mark && !this.stat) {
  245. for (var i = 0; i < entries.length; i ++) {
  246. var e = entries[i]
  247. if (abs === '/')
  248. e = abs + e
  249. else
  250. e = abs + '/' + e
  251. this.cache[e] = true
  252. }
  253. }
  254. this.cache[abs] = entries
  255. // mark and cache dir-ness
  256. return entries
  257. }
  258. GlobSync.prototype._readdirError = function (f, er) {
  259. // handle errors, and cache the information
  260. switch (er.code) {
  261. case 'ENOTSUP': // https://github.com/isaacs/node-glob/issues/205
  262. case 'ENOTDIR': // totally normal. means it *does* exist.
  263. var abs = this._makeAbs(f)
  264. this.cache[abs] = 'FILE'
  265. if (abs === this.cwdAbs) {
  266. var error = new Error(er.code + ' invalid cwd ' + this.cwd)
  267. error.path = this.cwd
  268. error.code = er.code
  269. throw error
  270. }
  271. break
  272. case 'ENOENT': // not terribly unusual
  273. case 'ELOOP':
  274. case 'ENAMETOOLONG':
  275. case 'UNKNOWN':
  276. this.cache[this._makeAbs(f)] = false
  277. break
  278. default: // some unusual error. Treat as failure.
  279. this.cache[this._makeAbs(f)] = false
  280. if (this.strict)
  281. throw er
  282. if (!this.silent)
  283. console.error('glob error', er)
  284. break
  285. }
  286. }
  287. GlobSync.prototype._processGlobStar = function (prefix, read, abs, remain, index, inGlobStar) {
  288. var entries = this._readdir(abs, inGlobStar)
  289. // no entries means not a dir, so it can never have matches
  290. // foo.txt/** doesn't match foo.txt
  291. if (!entries)
  292. return
  293. // test without the globstar, and with every child both below
  294. // and replacing the globstar.
  295. var remainWithoutGlobStar = remain.slice(1)
  296. var gspref = prefix ? [ prefix ] : []
  297. var noGlobStar = gspref.concat(remainWithoutGlobStar)
  298. // the noGlobStar pattern exits the inGlobStar state
  299. this._process(noGlobStar, index, false)
  300. var len = entries.length
  301. var isSym = this.symlinks[abs]
  302. // If it's a symlink, and we're in a globstar, then stop
  303. if (isSym && inGlobStar)
  304. return
  305. for (var i = 0; i < len; i++) {
  306. var e = entries[i]
  307. if (e.charAt(0) === '.' && !this.dot)
  308. continue
  309. // these two cases enter the inGlobStar state
  310. var instead = gspref.concat(entries[i], remainWithoutGlobStar)
  311. this._process(instead, index, true)
  312. var below = gspref.concat(entries[i], remain)
  313. this._process(below, index, true)
  314. }
  315. }
  316. GlobSync.prototype._processSimple = function (prefix, index) {
  317. // XXX review this. Shouldn't it be doing the mounting etc
  318. // before doing stat? kinda weird?
  319. var exists = this._stat(prefix)
  320. if (!this.matches[index])
  321. this.matches[index] = Object.create(null)
  322. // If it doesn't exist, then just mark the lack of results
  323. if (!exists)
  324. return
  325. if (prefix && isAbsolute(prefix) && !this.nomount) {
  326. var trail = /[\/\\]$/.test(prefix)
  327. if (prefix.charAt(0) === '/') {
  328. prefix = path.join(this.root, prefix)
  329. } else {
  330. prefix = path.resolve(this.root, prefix)
  331. if (trail)
  332. prefix += '/'
  333. }
  334. }
  335. if (process.platform === 'win32')
  336. prefix = prefix.replace(/\\/g, '/')
  337. // Mark this as a match
  338. this._emitMatch(index, prefix)
  339. }
  340. // Returns either 'DIR', 'FILE', or false
  341. GlobSync.prototype._stat = function (f) {
  342. var abs = this._makeAbs(f)
  343. var needDir = f.slice(-1) === '/'
  344. if (f.length > this.maxLength)
  345. return false
  346. if (!this.stat && ownProp(this.cache, abs)) {
  347. var c = this.cache[abs]
  348. if (Array.isArray(c))
  349. c = 'DIR'
  350. // It exists, but maybe not how we need it
  351. if (!needDir || c === 'DIR')
  352. return c
  353. if (needDir && c === 'FILE')
  354. return false
  355. // otherwise we have to stat, because maybe c=true
  356. // if we know it exists, but not what it is.
  357. }
  358. var exists
  359. var stat = this.statCache[abs]
  360. if (!stat) {
  361. var lstat
  362. try {
  363. lstat = fs.lstatSync(abs)
  364. } catch (er) {
  365. if (er && (er.code === 'ENOENT' || er.code === 'ENOTDIR')) {
  366. this.statCache[abs] = false
  367. return false
  368. }
  369. }
  370. if (lstat && lstat.isSymbolicLink()) {
  371. try {
  372. stat = fs.statSync(abs)
  373. } catch (er) {
  374. stat = lstat
  375. }
  376. } else {
  377. stat = lstat
  378. }
  379. }
  380. this.statCache[abs] = stat
  381. var c = true
  382. if (stat)
  383. c = stat.isDirectory() ? 'DIR' : 'FILE'
  384. this.cache[abs] = this.cache[abs] || c
  385. if (needDir && c === 'FILE')
  386. return false
  387. return c
  388. }
  389. GlobSync.prototype._mark = function (p) {
  390. return common.mark(this, p)
  391. }
  392. GlobSync.prototype._makeAbs = function (f) {
  393. return common.makeAbs(this, f)
  394. }