minimatch.js 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912
  1. module.exports = minimatch
  2. minimatch.Minimatch = Minimatch
  3. var path = { sep: '/' }
  4. try {
  5. path = require('path')
  6. } catch (er) {}
  7. var GLOBSTAR = minimatch.GLOBSTAR = Minimatch.GLOBSTAR = {}
  8. var expand = require('brace-expansion')
  9. // any single thing other than /
  10. // don't need to escape / when using new RegExp()
  11. var qmark = '[^/]'
  12. // * => any number of characters
  13. var star = qmark + '*?'
  14. // ** when dots are allowed. Anything goes, except .. and .
  15. // not (^ or / followed by one or two dots followed by $ or /),
  16. // followed by anything, any number of times.
  17. var twoStarDot = '(?:(?!(?:\\\/|^)(?:\\.{1,2})($|\\\/)).)*?'
  18. // not a ^ or / followed by a dot,
  19. // followed by anything, any number of times.
  20. var twoStarNoDot = '(?:(?!(?:\\\/|^)\\.).)*?'
  21. // characters that need to be escaped in RegExp.
  22. var reSpecials = charSet('().*{}+?[]^$\\!')
  23. // "abc" -> { a:true, b:true, c:true }
  24. function charSet (s) {
  25. return s.split('').reduce(function (set, c) {
  26. set[c] = true
  27. return set
  28. }, {})
  29. }
  30. // normalizes slashes.
  31. var slashSplit = /\/+/
  32. minimatch.filter = filter
  33. function filter (pattern, options) {
  34. options = options || {}
  35. return function (p, i, list) {
  36. return minimatch(p, pattern, options)
  37. }
  38. }
  39. function ext (a, b) {
  40. a = a || {}
  41. b = b || {}
  42. var t = {}
  43. Object.keys(b).forEach(function (k) {
  44. t[k] = b[k]
  45. })
  46. Object.keys(a).forEach(function (k) {
  47. t[k] = a[k]
  48. })
  49. return t
  50. }
  51. minimatch.defaults = function (def) {
  52. if (!def || !Object.keys(def).length) return minimatch
  53. var orig = minimatch
  54. var m = function minimatch (p, pattern, options) {
  55. return orig.minimatch(p, pattern, ext(def, options))
  56. }
  57. m.Minimatch = function Minimatch (pattern, options) {
  58. return new orig.Minimatch(pattern, ext(def, options))
  59. }
  60. return m
  61. }
  62. Minimatch.defaults = function (def) {
  63. if (!def || !Object.keys(def).length) return Minimatch
  64. return minimatch.defaults(def).Minimatch
  65. }
  66. function minimatch (p, pattern, options) {
  67. if (typeof pattern !== 'string') {
  68. throw new TypeError('glob pattern string required')
  69. }
  70. if (!options) options = {}
  71. // shortcut: comments match nothing.
  72. if (!options.nocomment && pattern.charAt(0) === '#') {
  73. return false
  74. }
  75. // "" only matches ""
  76. if (pattern.trim() === '') return p === ''
  77. return new Minimatch(pattern, options).match(p)
  78. }
  79. function Minimatch (pattern, options) {
  80. if (!(this instanceof Minimatch)) {
  81. return new Minimatch(pattern, options)
  82. }
  83. if (typeof pattern !== 'string') {
  84. throw new TypeError('glob pattern string required')
  85. }
  86. if (!options) options = {}
  87. pattern = pattern.trim()
  88. // windows support: need to use /, not \
  89. if (path.sep !== '/') {
  90. pattern = pattern.split(path.sep).join('/')
  91. }
  92. this.options = options
  93. this.set = []
  94. this.pattern = pattern
  95. this.regexp = null
  96. this.negate = false
  97. this.comment = false
  98. this.empty = false
  99. // make the set of regexps etc.
  100. this.make()
  101. }
  102. Minimatch.prototype.debug = function () {}
  103. Minimatch.prototype.make = make
  104. function make () {
  105. // don't do it more than once.
  106. if (this._made) return
  107. var pattern = this.pattern
  108. var options = this.options
  109. // empty patterns and comments match nothing.
  110. if (!options.nocomment && pattern.charAt(0) === '#') {
  111. this.comment = true
  112. return
  113. }
  114. if (!pattern) {
  115. this.empty = true
  116. return
  117. }
  118. // step 1: figure out negation, etc.
  119. this.parseNegate()
  120. // step 2: expand braces
  121. var set = this.globSet = this.braceExpand()
  122. if (options.debug) this.debug = console.error
  123. this.debug(this.pattern, set)
  124. // step 3: now we have a set, so turn each one into a series of path-portion
  125. // matching patterns.
  126. // These will be regexps, except in the case of "**", which is
  127. // set to the GLOBSTAR object for globstar behavior,
  128. // and will not contain any / characters
  129. set = this.globParts = set.map(function (s) {
  130. return s.split(slashSplit)
  131. })
  132. this.debug(this.pattern, set)
  133. // glob --> regexps
  134. set = set.map(function (s, si, set) {
  135. return s.map(this.parse, this)
  136. }, this)
  137. this.debug(this.pattern, set)
  138. // filter out everything that didn't compile properly.
  139. set = set.filter(function (s) {
  140. return s.indexOf(false) === -1
  141. })
  142. this.debug(this.pattern, set)
  143. this.set = set
  144. }
  145. Minimatch.prototype.parseNegate = parseNegate
  146. function parseNegate () {
  147. var pattern = this.pattern
  148. var negate = false
  149. var options = this.options
  150. var negateOffset = 0
  151. if (options.nonegate) return
  152. for (var i = 0, l = pattern.length
  153. ; i < l && pattern.charAt(i) === '!'
  154. ; i++) {
  155. negate = !negate
  156. negateOffset++
  157. }
  158. if (negateOffset) this.pattern = pattern.substr(negateOffset)
  159. this.negate = negate
  160. }
  161. // Brace expansion:
  162. // a{b,c}d -> abd acd
  163. // a{b,}c -> abc ac
  164. // a{0..3}d -> a0d a1d a2d a3d
  165. // a{b,c{d,e}f}g -> abg acdfg acefg
  166. // a{b,c}d{e,f}g -> abdeg acdeg abdeg abdfg
  167. //
  168. // Invalid sets are not expanded.
  169. // a{2..}b -> a{2..}b
  170. // a{b}c -> a{b}c
  171. minimatch.braceExpand = function (pattern, options) {
  172. return braceExpand(pattern, options)
  173. }
  174. Minimatch.prototype.braceExpand = braceExpand
  175. function braceExpand (pattern, options) {
  176. if (!options) {
  177. if (this instanceof Minimatch) {
  178. options = this.options
  179. } else {
  180. options = {}
  181. }
  182. }
  183. pattern = typeof pattern === 'undefined'
  184. ? this.pattern : pattern
  185. if (typeof pattern === 'undefined') {
  186. throw new Error('undefined pattern')
  187. }
  188. if (options.nobrace ||
  189. !pattern.match(/\{.*\}/)) {
  190. // shortcut. no need to expand.
  191. return [pattern]
  192. }
  193. return expand(pattern)
  194. }
  195. // parse a component of the expanded set.
  196. // At this point, no pattern may contain "/" in it
  197. // so we're going to return a 2d array, where each entry is the full
  198. // pattern, split on '/', and then turned into a regular expression.
  199. // A regexp is made at the end which joins each array with an
  200. // escaped /, and another full one which joins each regexp with |.
  201. //
  202. // Following the lead of Bash 4.1, note that "**" only has special meaning
  203. // when it is the *only* thing in a path portion. Otherwise, any series
  204. // of * is equivalent to a single *. Globstar behavior is enabled by
  205. // default, and can be disabled by setting options.noglobstar.
  206. Minimatch.prototype.parse = parse
  207. var SUBPARSE = {}
  208. function parse (pattern, isSub) {
  209. var options = this.options
  210. // shortcuts
  211. if (!options.noglobstar && pattern === '**') return GLOBSTAR
  212. if (pattern === '') return ''
  213. var re = ''
  214. var hasMagic = !!options.nocase
  215. var escaping = false
  216. // ? => one single character
  217. var patternListStack = []
  218. var negativeLists = []
  219. var plType
  220. var stateChar
  221. var inClass = false
  222. var reClassStart = -1
  223. var classStart = -1
  224. // . and .. never match anything that doesn't start with .,
  225. // even when options.dot is set.
  226. var patternStart = pattern.charAt(0) === '.' ? '' // anything
  227. // not (start or / followed by . or .. followed by / or end)
  228. : options.dot ? '(?!(?:^|\\\/)\\.{1,2}(?:$|\\\/))'
  229. : '(?!\\.)'
  230. var self = this
  231. function clearStateChar () {
  232. if (stateChar) {
  233. // we had some state-tracking character
  234. // that wasn't consumed by this pass.
  235. switch (stateChar) {
  236. case '*':
  237. re += star
  238. hasMagic = true
  239. break
  240. case '?':
  241. re += qmark
  242. hasMagic = true
  243. break
  244. default:
  245. re += '\\' + stateChar
  246. break
  247. }
  248. self.debug('clearStateChar %j %j', stateChar, re)
  249. stateChar = false
  250. }
  251. }
  252. for (var i = 0, len = pattern.length, c
  253. ; (i < len) && (c = pattern.charAt(i))
  254. ; i++) {
  255. this.debug('%s\t%s %s %j', pattern, i, re, c)
  256. // skip over any that are escaped.
  257. if (escaping && reSpecials[c]) {
  258. re += '\\' + c
  259. escaping = false
  260. continue
  261. }
  262. switch (c) {
  263. case '/':
  264. // completely not allowed, even escaped.
  265. // Should already be path-split by now.
  266. return false
  267. case '\\':
  268. clearStateChar()
  269. escaping = true
  270. continue
  271. // the various stateChar values
  272. // for the "extglob" stuff.
  273. case '?':
  274. case '*':
  275. case '+':
  276. case '@':
  277. case '!':
  278. this.debug('%s\t%s %s %j <-- stateChar', pattern, i, re, c)
  279. // all of those are literals inside a class, except that
  280. // the glob [!a] means [^a] in regexp
  281. if (inClass) {
  282. this.debug(' in class')
  283. if (c === '!' && i === classStart + 1) c = '^'
  284. re += c
  285. continue
  286. }
  287. // if we already have a stateChar, then it means
  288. // that there was something like ** or +? in there.
  289. // Handle the stateChar, then proceed with this one.
  290. self.debug('call clearStateChar %j', stateChar)
  291. clearStateChar()
  292. stateChar = c
  293. // if extglob is disabled, then +(asdf|foo) isn't a thing.
  294. // just clear the statechar *now*, rather than even diving into
  295. // the patternList stuff.
  296. if (options.noext) clearStateChar()
  297. continue
  298. case '(':
  299. if (inClass) {
  300. re += '('
  301. continue
  302. }
  303. if (!stateChar) {
  304. re += '\\('
  305. continue
  306. }
  307. plType = stateChar
  308. patternListStack.push({
  309. type: plType,
  310. start: i - 1,
  311. reStart: re.length
  312. })
  313. // negation is (?:(?!js)[^/]*)
  314. re += stateChar === '!' ? '(?:(?!(?:' : '(?:'
  315. this.debug('plType %j %j', stateChar, re)
  316. stateChar = false
  317. continue
  318. case ')':
  319. if (inClass || !patternListStack.length) {
  320. re += '\\)'
  321. continue
  322. }
  323. clearStateChar()
  324. hasMagic = true
  325. re += ')'
  326. var pl = patternListStack.pop()
  327. plType = pl.type
  328. // negation is (?:(?!js)[^/]*)
  329. // The others are (?:<pattern>)<type>
  330. switch (plType) {
  331. case '!':
  332. negativeLists.push(pl)
  333. re += ')[^/]*?)'
  334. pl.reEnd = re.length
  335. break
  336. case '?':
  337. case '+':
  338. case '*':
  339. re += plType
  340. break
  341. case '@': break // the default anyway
  342. }
  343. continue
  344. case '|':
  345. if (inClass || !patternListStack.length || escaping) {
  346. re += '\\|'
  347. escaping = false
  348. continue
  349. }
  350. clearStateChar()
  351. re += '|'
  352. continue
  353. // these are mostly the same in regexp and glob
  354. case '[':
  355. // swallow any state-tracking char before the [
  356. clearStateChar()
  357. if (inClass) {
  358. re += '\\' + c
  359. continue
  360. }
  361. inClass = true
  362. classStart = i
  363. reClassStart = re.length
  364. re += c
  365. continue
  366. case ']':
  367. // a right bracket shall lose its special
  368. // meaning and represent itself in
  369. // a bracket expression if it occurs
  370. // first in the list. -- POSIX.2 2.8.3.2
  371. if (i === classStart + 1 || !inClass) {
  372. re += '\\' + c
  373. escaping = false
  374. continue
  375. }
  376. // handle the case where we left a class open.
  377. // "[z-a]" is valid, equivalent to "\[z-a\]"
  378. if (inClass) {
  379. // split where the last [ was, make sure we don't have
  380. // an invalid re. if so, re-walk the contents of the
  381. // would-be class to re-translate any characters that
  382. // were passed through as-is
  383. // TODO: It would probably be faster to determine this
  384. // without a try/catch and a new RegExp, but it's tricky
  385. // to do safely. For now, this is safe and works.
  386. var cs = pattern.substring(classStart + 1, i)
  387. try {
  388. RegExp('[' + cs + ']')
  389. } catch (er) {
  390. // not a valid class!
  391. var sp = this.parse(cs, SUBPARSE)
  392. re = re.substr(0, reClassStart) + '\\[' + sp[0] + '\\]'
  393. hasMagic = hasMagic || sp[1]
  394. inClass = false
  395. continue
  396. }
  397. }
  398. // finish up the class.
  399. hasMagic = true
  400. inClass = false
  401. re += c
  402. continue
  403. default:
  404. // swallow any state char that wasn't consumed
  405. clearStateChar()
  406. if (escaping) {
  407. // no need
  408. escaping = false
  409. } else if (reSpecials[c]
  410. && !(c === '^' && inClass)) {
  411. re += '\\'
  412. }
  413. re += c
  414. } // switch
  415. } // for
  416. // handle the case where we left a class open.
  417. // "[abc" is valid, equivalent to "\[abc"
  418. if (inClass) {
  419. // split where the last [ was, and escape it
  420. // this is a huge pita. We now have to re-walk
  421. // the contents of the would-be class to re-translate
  422. // any characters that were passed through as-is
  423. cs = pattern.substr(classStart + 1)
  424. sp = this.parse(cs, SUBPARSE)
  425. re = re.substr(0, reClassStart) + '\\[' + sp[0]
  426. hasMagic = hasMagic || sp[1]
  427. }
  428. // handle the case where we had a +( thing at the *end*
  429. // of the pattern.
  430. // each pattern list stack adds 3 chars, and we need to go through
  431. // and escape any | chars that were passed through as-is for the regexp.
  432. // Go through and escape them, taking care not to double-escape any
  433. // | chars that were already escaped.
  434. for (pl = patternListStack.pop(); pl; pl = patternListStack.pop()) {
  435. var tail = re.slice(pl.reStart + 3)
  436. // maybe some even number of \, then maybe 1 \, followed by a |
  437. tail = tail.replace(/((?:\\{2})*)(\\?)\|/g, function (_, $1, $2) {
  438. if (!$2) {
  439. // the | isn't already escaped, so escape it.
  440. $2 = '\\'
  441. }
  442. // need to escape all those slashes *again*, without escaping the
  443. // one that we need for escaping the | character. As it works out,
  444. // escaping an even number of slashes can be done by simply repeating
  445. // it exactly after itself. That's why this trick works.
  446. //
  447. // I am sorry that you have to see this.
  448. return $1 + $1 + $2 + '|'
  449. })
  450. this.debug('tail=%j\n %s', tail, tail)
  451. var t = pl.type === '*' ? star
  452. : pl.type === '?' ? qmark
  453. : '\\' + pl.type
  454. hasMagic = true
  455. re = re.slice(0, pl.reStart) + t + '\\(' + tail
  456. }
  457. // handle trailing things that only matter at the very end.
  458. clearStateChar()
  459. if (escaping) {
  460. // trailing \\
  461. re += '\\\\'
  462. }
  463. // only need to apply the nodot start if the re starts with
  464. // something that could conceivably capture a dot
  465. var addPatternStart = false
  466. switch (re.charAt(0)) {
  467. case '.':
  468. case '[':
  469. case '(': addPatternStart = true
  470. }
  471. // Hack to work around lack of negative lookbehind in JS
  472. // A pattern like: *.!(x).!(y|z) needs to ensure that a name
  473. // like 'a.xyz.yz' doesn't match. So, the first negative
  474. // lookahead, has to look ALL the way ahead, to the end of
  475. // the pattern.
  476. for (var n = negativeLists.length - 1; n > -1; n--) {
  477. var nl = negativeLists[n]
  478. var nlBefore = re.slice(0, nl.reStart)
  479. var nlFirst = re.slice(nl.reStart, nl.reEnd - 8)
  480. var nlLast = re.slice(nl.reEnd - 8, nl.reEnd)
  481. var nlAfter = re.slice(nl.reEnd)
  482. nlLast += nlAfter
  483. // Handle nested stuff like *(*.js|!(*.json)), where open parens
  484. // mean that we should *not* include the ) in the bit that is considered
  485. // "after" the negated section.
  486. var openParensBefore = nlBefore.split('(').length - 1
  487. var cleanAfter = nlAfter
  488. for (i = 0; i < openParensBefore; i++) {
  489. cleanAfter = cleanAfter.replace(/\)[+*?]?/, '')
  490. }
  491. nlAfter = cleanAfter
  492. var dollar = ''
  493. if (nlAfter === '' && isSub !== SUBPARSE) {
  494. dollar = '$'
  495. }
  496. var newRe = nlBefore + nlFirst + nlAfter + dollar + nlLast
  497. re = newRe
  498. }
  499. // if the re is not "" at this point, then we need to make sure
  500. // it doesn't match against an empty path part.
  501. // Otherwise a/* will match a/, which it should not.
  502. if (re !== '' && hasMagic) {
  503. re = '(?=.)' + re
  504. }
  505. if (addPatternStart) {
  506. re = patternStart + re
  507. }
  508. // parsing just a piece of a larger pattern.
  509. if (isSub === SUBPARSE) {
  510. return [re, hasMagic]
  511. }
  512. // skip the regexp for non-magical patterns
  513. // unescape anything in it, though, so that it'll be
  514. // an exact match against a file etc.
  515. if (!hasMagic) {
  516. return globUnescape(pattern)
  517. }
  518. var flags = options.nocase ? 'i' : ''
  519. var regExp = new RegExp('^' + re + '$', flags)
  520. regExp._glob = pattern
  521. regExp._src = re
  522. return regExp
  523. }
  524. minimatch.makeRe = function (pattern, options) {
  525. return new Minimatch(pattern, options || {}).makeRe()
  526. }
  527. Minimatch.prototype.makeRe = makeRe
  528. function makeRe () {
  529. if (this.regexp || this.regexp === false) return this.regexp
  530. // at this point, this.set is a 2d array of partial
  531. // pattern strings, or "**".
  532. //
  533. // It's better to use .match(). This function shouldn't
  534. // be used, really, but it's pretty convenient sometimes,
  535. // when you just want to work with a regex.
  536. var set = this.set
  537. if (!set.length) {
  538. this.regexp = false
  539. return this.regexp
  540. }
  541. var options = this.options
  542. var twoStar = options.noglobstar ? star
  543. : options.dot ? twoStarDot
  544. : twoStarNoDot
  545. var flags = options.nocase ? 'i' : ''
  546. var re = set.map(function (pattern) {
  547. return pattern.map(function (p) {
  548. return (p === GLOBSTAR) ? twoStar
  549. : (typeof p === 'string') ? regExpEscape(p)
  550. : p._src
  551. }).join('\\\/')
  552. }).join('|')
  553. // must match entire pattern
  554. // ending in a * or ** will make it less strict.
  555. re = '^(?:' + re + ')$'
  556. // can match anything, as long as it's not this.
  557. if (this.negate) re = '^(?!' + re + ').*$'
  558. try {
  559. this.regexp = new RegExp(re, flags)
  560. } catch (ex) {
  561. this.regexp = false
  562. }
  563. return this.regexp
  564. }
  565. minimatch.match = function (list, pattern, options) {
  566. options = options || {}
  567. var mm = new Minimatch(pattern, options)
  568. list = list.filter(function (f) {
  569. return mm.match(f)
  570. })
  571. if (mm.options.nonull && !list.length) {
  572. list.push(pattern)
  573. }
  574. return list
  575. }
  576. Minimatch.prototype.match = match
  577. function match (f, partial) {
  578. this.debug('match', f, this.pattern)
  579. // short-circuit in the case of busted things.
  580. // comments, etc.
  581. if (this.comment) return false
  582. if (this.empty) return f === ''
  583. if (f === '/' && partial) return true
  584. var options = this.options
  585. // windows: need to use /, not \
  586. if (path.sep !== '/') {
  587. f = f.split(path.sep).join('/')
  588. }
  589. // treat the test path as a set of pathparts.
  590. f = f.split(slashSplit)
  591. this.debug(this.pattern, 'split', f)
  592. // just ONE of the pattern sets in this.set needs to match
  593. // in order for it to be valid. If negating, then just one
  594. // match means that we have failed.
  595. // Either way, return on the first hit.
  596. var set = this.set
  597. this.debug(this.pattern, 'set', set)
  598. // Find the basename of the path by looking for the last non-empty segment
  599. var filename
  600. var i
  601. for (i = f.length - 1; i >= 0; i--) {
  602. filename = f[i]
  603. if (filename) break
  604. }
  605. for (i = 0; i < set.length; i++) {
  606. var pattern = set[i]
  607. var file = f
  608. if (options.matchBase && pattern.length === 1) {
  609. file = [filename]
  610. }
  611. var hit = this.matchOne(file, pattern, partial)
  612. if (hit) {
  613. if (options.flipNegate) return true
  614. return !this.negate
  615. }
  616. }
  617. // didn't get any hits. this is success if it's a negative
  618. // pattern, failure otherwise.
  619. if (options.flipNegate) return false
  620. return this.negate
  621. }
  622. // set partial to true to test if, for example,
  623. // "/a/b" matches the start of "/*/b/*/d"
  624. // Partial means, if you run out of file before you run
  625. // out of pattern, then that's fine, as long as all
  626. // the parts match.
  627. Minimatch.prototype.matchOne = function (file, pattern, partial) {
  628. var options = this.options
  629. this.debug('matchOne',
  630. { 'this': this, file: file, pattern: pattern })
  631. this.debug('matchOne', file.length, pattern.length)
  632. for (var fi = 0,
  633. pi = 0,
  634. fl = file.length,
  635. pl = pattern.length
  636. ; (fi < fl) && (pi < pl)
  637. ; fi++, pi++) {
  638. this.debug('matchOne loop')
  639. var p = pattern[pi]
  640. var f = file[fi]
  641. this.debug(pattern, p, f)
  642. // should be impossible.
  643. // some invalid regexp stuff in the set.
  644. if (p === false) return false
  645. if (p === GLOBSTAR) {
  646. this.debug('GLOBSTAR', [pattern, p, f])
  647. // "**"
  648. // a/**/b/**/c would match the following:
  649. // a/b/x/y/z/c
  650. // a/x/y/z/b/c
  651. // a/b/x/b/x/c
  652. // a/b/c
  653. // To do this, take the rest of the pattern after
  654. // the **, and see if it would match the file remainder.
  655. // If so, return success.
  656. // If not, the ** "swallows" a segment, and try again.
  657. // This is recursively awful.
  658. //
  659. // a/**/b/**/c matching a/b/x/y/z/c
  660. // - a matches a
  661. // - doublestar
  662. // - matchOne(b/x/y/z/c, b/**/c)
  663. // - b matches b
  664. // - doublestar
  665. // - matchOne(x/y/z/c, c) -> no
  666. // - matchOne(y/z/c, c) -> no
  667. // - matchOne(z/c, c) -> no
  668. // - matchOne(c, c) yes, hit
  669. var fr = fi
  670. var pr = pi + 1
  671. if (pr === pl) {
  672. this.debug('** at the end')
  673. // a ** at the end will just swallow the rest.
  674. // We have found a match.
  675. // however, it will not swallow /.x, unless
  676. // options.dot is set.
  677. // . and .. are *never* matched by **, for explosively
  678. // exponential reasons.
  679. for (; fi < fl; fi++) {
  680. if (file[fi] === '.' || file[fi] === '..' ||
  681. (!options.dot && file[fi].charAt(0) === '.')) return false
  682. }
  683. return true
  684. }
  685. // ok, let's see if we can swallow whatever we can.
  686. while (fr < fl) {
  687. var swallowee = file[fr]
  688. this.debug('\nglobstar while', file, fr, pattern, pr, swallowee)
  689. // XXX remove this slice. Just pass the start index.
  690. if (this.matchOne(file.slice(fr), pattern.slice(pr), partial)) {
  691. this.debug('globstar found match!', fr, fl, swallowee)
  692. // found a match.
  693. return true
  694. } else {
  695. // can't swallow "." or ".." ever.
  696. // can only swallow ".foo" when explicitly asked.
  697. if (swallowee === '.' || swallowee === '..' ||
  698. (!options.dot && swallowee.charAt(0) === '.')) {
  699. this.debug('dot detected!', file, fr, pattern, pr)
  700. break
  701. }
  702. // ** swallows a segment, and continue.
  703. this.debug('globstar swallow a segment, and continue')
  704. fr++
  705. }
  706. }
  707. // no match was found.
  708. // However, in partial mode, we can't say this is necessarily over.
  709. // If there's more *pattern* left, then
  710. if (partial) {
  711. // ran out of file
  712. this.debug('\n>>> no match, partial?', file, fr, pattern, pr)
  713. if (fr === fl) return true
  714. }
  715. return false
  716. }
  717. // something other than **
  718. // non-magic patterns just have to match exactly
  719. // patterns with magic have been turned into regexps.
  720. var hit
  721. if (typeof p === 'string') {
  722. if (options.nocase) {
  723. hit = f.toLowerCase() === p.toLowerCase()
  724. } else {
  725. hit = f === p
  726. }
  727. this.debug('string match', p, f, hit)
  728. } else {
  729. hit = f.match(p)
  730. this.debug('pattern match', p, f, hit)
  731. }
  732. if (!hit) return false
  733. }
  734. // Note: ending in / means that we'll get a final ""
  735. // at the end of the pattern. This can only match a
  736. // corresponding "" at the end of the file.
  737. // If the file ends in /, then it can only match a
  738. // a pattern that ends in /, unless the pattern just
  739. // doesn't have any more for it. But, a/b/ should *not*
  740. // match "a/b/*", even though "" matches against the
  741. // [^/]*? pattern, except in partial mode, where it might
  742. // simply not be reached yet.
  743. // However, a/b/ should still satisfy a/*
  744. // now either we fell off the end of the pattern, or we're done.
  745. if (fi === fl && pi === pl) {
  746. // ran out of pattern and filename at the same time.
  747. // an exact hit!
  748. return true
  749. } else if (fi === fl) {
  750. // ran out of file, but still had pattern left.
  751. // this is ok if we're doing the match as part of
  752. // a glob fs traversal.
  753. return partial
  754. } else if (pi === pl) {
  755. // ran out of pattern, still have file left.
  756. // this is only acceptable if we're on the very last
  757. // empty segment of a file with a trailing slash.
  758. // a/* should match a/b/
  759. var emptyFileEnd = (fi === fl - 1) && (file[fi] === '')
  760. return emptyFileEnd
  761. }
  762. // should be unreachable.
  763. throw new Error('wtf?')
  764. }
  765. // replace stuff like \* with *
  766. function globUnescape (s) {
  767. return s.replace(/\\(.)/g, '$1')
  768. }
  769. function regExpEscape (s) {
  770. return s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&')
  771. }