minimatch.js 27 KB

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