minimatch.js 26 KB

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