minimatch.js 27 KB

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