sync.js 9.9 KB

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