1 module.exports = minimatch
2 minimatch.Minimatch = Minimatch
4 var path = { sep: '/' }
9 var GLOBSTAR = minimatch.GLOBSTAR = Minimatch.GLOBSTAR = {}
10 var expand = require('brace-expansion')
12 // any single thing other than /
13 // don't need to escape / when using new RegExp()
16 // * => any number of characters
17 var star = qmark + '*?'
19 // ** when dots are allowed. Anything goes, except .. and .
20 // not (^ or / followed by one or two dots followed by $ or /),
21 // followed by anything, any number of times.
22 var twoStarDot = '(?:(?!(?:\\\/|^)(?:\\.{1,2})($|\\\/)).)*?'
24 // not a ^ or / followed by a dot,
25 // followed by anything, any number of times.
26 var twoStarNoDot = '(?:(?!(?:\\\/|^)\\.).)*?'
28 // characters that need to be escaped in RegExp.
29 var reSpecials = charSet('().*{}+?[]^$\\!')
31 // "abc" -> { a:true, b:true, c:true }
32 function charSet (s) {
33 return s.split('').reduce(function (set, c) {
39 // normalizes slashes.
40 var slashSplit = /\/+/
42 minimatch.filter = filter
43 function filter (pattern, options) {
44 options = options || {}
45 return function (p, i, list) {
46 return minimatch(p, pattern, options)
54 Object.keys(b).forEach(function (k) {
57 Object.keys(a).forEach(function (k) {
63 minimatch.defaults = function (def) {
64 if (!def || !Object.keys(def).length) return minimatch
68 var m = function minimatch (p, pattern, options) {
69 return orig.minimatch(p, pattern, ext(def, options))
72 m.Minimatch = function Minimatch (pattern, options) {
73 return new orig.Minimatch(pattern, ext(def, options))
79 Minimatch.defaults = function (def) {
80 if (!def || !Object.keys(def).length) return Minimatch
81 return minimatch.defaults(def).Minimatch
84 function minimatch (p, pattern, options) {
85 if (typeof pattern !== 'string') {
86 throw new TypeError('glob pattern string required')
89 if (!options) options = {}
91 // shortcut: comments match nothing.
92 if (!options.nocomment && pattern.charAt(0) === '#') {
97 if (pattern.trim() === '') return p === ''
99 return new Minimatch(pattern, options).match(p)
102 function Minimatch (pattern, options) {
103 if (!(this instanceof Minimatch)) {
104 return new Minimatch(pattern, options)
107 if (typeof pattern !== 'string') {
108 throw new TypeError('glob pattern string required')
111 if (!options) options = {}
112 pattern = pattern.trim()
114 // windows support: need to use /, not \
115 if (path.sep !== '/') {
116 pattern = pattern.split(path.sep).join('/')
119 this.options = options
121 this.pattern = pattern
127 // make the set of regexps etc.
131 Minimatch.prototype.debug = function () {}
133 Minimatch.prototype.make = make
135 // don't do it more than once.
136 if (this._made) return
138 var pattern = this.pattern
139 var options = this.options
141 // empty patterns and comments match nothing.
142 if (!options.nocomment && pattern.charAt(0) === '#') {
151 // step 1: figure out negation, etc.
154 // step 2: expand braces
155 var set = this.globSet = this.braceExpand()
157 if (options.debug) this.debug = console.error
159 this.debug(this.pattern, set)
161 // step 3: now we have a set, so turn each one into a series of path-portion
162 // matching patterns.
163 // These will be regexps, except in the case of "**", which is
164 // set to the GLOBSTAR object for globstar behavior,
165 // and will not contain any / characters
166 set = this.globParts = set.map(function (s) {
167 return s.split(slashSplit)
170 this.debug(this.pattern, set)
173 set = set.map(function (s, si, set) {
174 return s.map(this.parse, this)
177 this.debug(this.pattern, set)
179 // filter out everything that didn't compile properly.
180 set = set.filter(function (s) {
181 return s.indexOf(false) === -1
184 this.debug(this.pattern, set)
189 Minimatch.prototype.parseNegate = parseNegate
190 function parseNegate () {
191 var pattern = this.pattern
193 var options = this.options
196 if (options.nonegate) return
198 for (var i = 0, l = pattern.length
199 ; i < l && pattern.charAt(i) === '!'
205 if (negateOffset) this.pattern = pattern.substr(negateOffset)
210 // a{b,c}d -> abd acd
212 // a{0..3}d -> a0d a1d a2d a3d
213 // a{b,c{d,e}f}g -> abg acdfg acefg
214 // a{b,c}d{e,f}g -> abdeg acdeg abdeg abdfg
216 // Invalid sets are not expanded.
217 // a{2..}b -> a{2..}b
219 minimatch.braceExpand = function (pattern, options) {
220 return braceExpand(pattern, options)
223 Minimatch.prototype.braceExpand = braceExpand
225 function braceExpand (pattern, options) {
227 if (this instanceof Minimatch) {
228 options = this.options
234 pattern = typeof pattern === 'undefined'
235 ? this.pattern : pattern
237 if (typeof pattern === 'undefined') {
238 throw new Error('undefined pattern')
241 if (options.nobrace ||
242 !pattern.match(/\{.*\}/)) {
243 // shortcut. no need to expand.
247 return expand(pattern)
250 // parse a component of the expanded set.
251 // At this point, no pattern may contain "/" in it
252 // so we're going to return a 2d array, where each entry is the full
253 // pattern, split on '/', and then turned into a regular expression.
254 // A regexp is made at the end which joins each array with an
255 // escaped /, and another full one which joins each regexp with |.
257 // Following the lead of Bash 4.1, note that "**" only has special meaning
258 // when it is the *only* thing in a path portion. Otherwise, any series
259 // of * is equivalent to a single *. Globstar behavior is enabled by
260 // default, and can be disabled by setting options.noglobstar.
261 Minimatch.prototype.parse = parse
263 function parse (pattern, isSub) {
264 var options = this.options
267 if (!options.noglobstar && pattern === '**') return GLOBSTAR
268 if (pattern === '') return ''
271 var hasMagic = !!options.nocase
273 // ? => one single character
274 var patternListStack = []
275 var negativeLists = []
279 var reClassStart = -1
281 // . and .. never match anything that doesn't start with .,
282 // even when options.dot is set.
283 var patternStart = pattern.charAt(0) === '.' ? '' // anything
284 // not (start or / followed by . or .. followed by / or end)
285 : options.dot ? '(?!(?:^|\\\/)\\.{1,2}(?:$|\\\/))'
289 function clearStateChar () {
291 // we had some state-tracking character
292 // that wasn't consumed by this pass.
303 re += '\\' + stateChar
306 self.debug('clearStateChar %j %j', stateChar, re)
311 for (var i = 0, len = pattern.length, c
312 ; (i < len) && (c = pattern.charAt(i))
314 this.debug('%s\t%s %s %j', pattern, i, re, c)
316 // skip over any that are escaped.
317 if (escaping && reSpecials[c]) {
325 // completely not allowed, even escaped.
326 // Should already be path-split by now.
334 // the various stateChar values
335 // for the "extglob" stuff.
341 this.debug('%s\t%s %s %j <-- stateChar', pattern, i, re, c)
343 // all of those are literals inside a class, except that
344 // the glob [!a] means [^a] in regexp
346 this.debug(' in class')
347 if (c === '!' && i === classStart + 1) c = '^'
352 // if we already have a stateChar, then it means
353 // that there was something like ** or +? in there.
354 // Handle the stateChar, then proceed with this one.
355 self.debug('call clearStateChar %j', stateChar)
358 // if extglob is disabled, then +(asdf|foo) isn't a thing.
359 // just clear the statechar *now*, rather than even diving into
360 // the patternList stuff.
361 if (options.noext) clearStateChar()
376 patternListStack.push({
381 // negation is (?:(?!js)[^/]*)
382 re += stateChar === '!' ? '(?:(?!(?:' : '(?:'
383 this.debug('plType %j %j', stateChar, re)
388 if (inClass || !patternListStack.length) {
396 var pl = patternListStack.pop()
398 // negation is (?:(?!js)[^/]*)
399 // The others are (?:<pattern>)<type>
402 negativeLists.push(pl)
411 case '@': break // the default anyway
416 if (inClass || !patternListStack.length || escaping) {
426 // these are mostly the same in regexp and glob
428 // swallow any state-tracking char before the [
438 reClassStart = re.length
443 // a right bracket shall lose its special
444 // meaning and represent itself in
445 // a bracket expression if it occurs
446 // first in the list. -- POSIX.2 2.8.3.2
447 if (i === classStart + 1 || !inClass) {
453 // handle the case where we left a class open.
454 // "[z-a]" is valid, equivalent to "\[z-a\]"
456 // split where the last [ was, make sure we don't have
457 // an invalid re. if so, re-walk the contents of the
458 // would-be class to re-translate any characters that
459 // were passed through as-is
460 // TODO: It would probably be faster to determine this
461 // without a try/catch and a new RegExp, but it's tricky
462 // to do safely. For now, this is safe and works.
463 var cs = pattern.substring(classStart + 1, i)
465 RegExp('[' + cs + ']')
467 // not a valid class!
468 var sp = this.parse(cs, SUBPARSE)
469 re = re.substr(0, reClassStart) + '\\[' + sp[0] + '\\]'
470 hasMagic = hasMagic || sp[1]
476 // finish up the class.
483 // swallow any state char that wasn't consumed
489 } else if (reSpecials[c]
490 && !(c === '^' && inClass)) {
499 // handle the case where we left a class open.
500 // "[abc" is valid, equivalent to "\[abc"
502 // split where the last [ was, and escape it
503 // this is a huge pita. We now have to re-walk
504 // the contents of the would-be class to re-translate
505 // any characters that were passed through as-is
506 cs = pattern.substr(classStart + 1)
507 sp = this.parse(cs, SUBPARSE)
508 re = re.substr(0, reClassStart) + '\\[' + sp[0]
509 hasMagic = hasMagic || sp[1]
512 // handle the case where we had a +( thing at the *end*
514 // each pattern list stack adds 3 chars, and we need to go through
515 // and escape any | chars that were passed through as-is for the regexp.
516 // Go through and escape them, taking care not to double-escape any
517 // | chars that were already escaped.
518 for (pl = patternListStack.pop(); pl; pl = patternListStack.pop()) {
519 var tail = re.slice(pl.reStart + 3)
520 // maybe some even number of \, then maybe 1 \, followed by a |
521 tail = tail.replace(/((?:\\{2})*)(\\?)\|/g, function (_, $1, $2) {
523 // the | isn't already escaped, so escape it.
527 // need to escape all those slashes *again*, without escaping the
528 // one that we need for escaping the | character. As it works out,
529 // escaping an even number of slashes can be done by simply repeating
530 // it exactly after itself. That's why this trick works.
532 // I am sorry that you have to see this.
533 return $1 + $1 + $2 + '|'
536 this.debug('tail=%j\n %s', tail, tail)
537 var t = pl.type === '*' ? star
538 : pl.type === '?' ? qmark
542 re = re.slice(0, pl.reStart) + t + '\\(' + tail
545 // handle trailing things that only matter at the very end.
552 // only need to apply the nodot start if the re starts with
553 // something that could conceivably capture a dot
554 var addPatternStart = false
555 switch (re.charAt(0)) {
558 case '(': addPatternStart = true
561 // Hack to work around lack of negative lookbehind in JS
562 // A pattern like: *.!(x).!(y|z) needs to ensure that a name
563 // like 'a.xyz.yz' doesn't match. So, the first negative
564 // lookahead, has to look ALL the way ahead, to the end of
566 for (var n = negativeLists.length - 1; n > -1; n--) {
567 var nl = negativeLists[n]
569 var nlBefore = re.slice(0, nl.reStart)
570 var nlFirst = re.slice(nl.reStart, nl.reEnd - 8)
571 var nlLast = re.slice(nl.reEnd - 8, nl.reEnd)
572 var nlAfter = re.slice(nl.reEnd)
576 // Handle nested stuff like *(*.js|!(*.json)), where open parens
577 // mean that we should *not* include the ) in the bit that is considered
578 // "after" the negated section.
579 var openParensBefore = nlBefore.split('(').length - 1
580 var cleanAfter = nlAfter
581 for (i = 0; i < openParensBefore; i++) {
582 cleanAfter = cleanAfter.replace(/\)[+*?]?/, '')
587 if (nlAfter === '' && isSub !== SUBPARSE) {
590 var newRe = nlBefore + nlFirst + nlAfter + dollar + nlLast
594 // if the re is not "" at this point, then we need to make sure
595 // it doesn't match against an empty path part.
596 // Otherwise a/* will match a/, which it should not.
597 if (re !== '' && hasMagic) {
601 if (addPatternStart) {
602 re = patternStart + re
605 // parsing just a piece of a larger pattern.
606 if (isSub === SUBPARSE) {
607 return [re, hasMagic]
610 // skip the regexp for non-magical patterns
611 // unescape anything in it, though, so that it'll be
612 // an exact match against a file etc.
614 return globUnescape(pattern)
617 var flags = options.nocase ? 'i' : ''
618 var regExp = new RegExp('^' + re + '$', flags)
620 regExp._glob = pattern
626 minimatch.makeRe = function (pattern, options) {
627 return new Minimatch(pattern, options || {}).makeRe()
630 Minimatch.prototype.makeRe = makeRe
632 if (this.regexp || this.regexp === false) return this.regexp
634 // at this point, this.set is a 2d array of partial
635 // pattern strings, or "**".
637 // It's better to use .match(). This function shouldn't
638 // be used, really, but it's pretty convenient sometimes,
639 // when you just want to work with a regex.
646 var options = this.options
648 var twoStar = options.noglobstar ? star
649 : options.dot ? twoStarDot
651 var flags = options.nocase ? 'i' : ''
653 var re = set.map(function (pattern) {
654 return pattern.map(function (p) {
655 return (p === GLOBSTAR) ? twoStar
656 : (typeof p === 'string') ? regExpEscape(p)
661 // must match entire pattern
662 // ending in a * or ** will make it less strict.
663 re = '^(?:' + re + ')$'
665 // can match anything, as long as it's not this.
666 if (this.negate) re = '^(?!' + re + ').*$'
669 this.regexp = new RegExp(re, flags)
676 minimatch.match = function (list, pattern, options) {
677 options = options || {}
678 var mm = new Minimatch(pattern, options)
679 list = list.filter(function (f) {
682 if (mm.options.nonull && !list.length) {
688 Minimatch.prototype.match = match
689 function match (f, partial) {
690 this.debug('match', f, this.pattern)
691 // short-circuit in the case of busted things.
693 if (this.comment) return false
694 if (this.empty) return f === ''
696 if (f === '/' && partial) return true
698 var options = this.options
700 // windows: need to use /, not \
701 if (path.sep !== '/') {
702 f = f.split(path.sep).join('/')
705 // treat the test path as a set of pathparts.
706 f = f.split(slashSplit)
707 this.debug(this.pattern, 'split', f)
709 // just ONE of the pattern sets in this.set needs to match
710 // in order for it to be valid. If negating, then just one
711 // match means that we have failed.
712 // Either way, return on the first hit.
715 this.debug(this.pattern, 'set', set)
717 // Find the basename of the path by looking for the last non-empty segment
720 for (i = f.length - 1; i >= 0; i--) {
725 for (i = 0; i < set.length; i++) {
728 if (options.matchBase && pattern.length === 1) {
731 var hit = this.matchOne(file, pattern, partial)
733 if (options.flipNegate) return true
738 // didn't get any hits. this is success if it's a negative
739 // pattern, failure otherwise.
740 if (options.flipNegate) return false
744 // set partial to true to test if, for example,
745 // "/a/b" matches the start of "/*/b/*/d"
746 // Partial means, if you run out of file before you run
747 // out of pattern, then that's fine, as long as all
749 Minimatch.prototype.matchOne = function (file, pattern, partial) {
750 var options = this.options
752 this.debug('matchOne',
753 { 'this': this, file: file, pattern: pattern })
755 this.debug('matchOne', file.length, pattern.length)
761 ; (fi < fl) && (pi < pl)
763 this.debug('matchOne loop')
767 this.debug(pattern, p, f)
769 // should be impossible.
770 // some invalid regexp stuff in the set.
771 if (p === false) return false
773 if (p === GLOBSTAR) {
774 this.debug('GLOBSTAR', [pattern, p, f])
777 // a/**/b/**/c would match the following:
782 // To do this, take the rest of the pattern after
783 // the **, and see if it would match the file remainder.
784 // If so, return success.
785 // If not, the ** "swallows" a segment, and try again.
786 // This is recursively awful.
788 // a/**/b/**/c matching a/b/x/y/z/c
791 // - matchOne(b/x/y/z/c, b/**/c)
794 // - matchOne(x/y/z/c, c) -> no
795 // - matchOne(y/z/c, c) -> no
796 // - matchOne(z/c, c) -> no
797 // - matchOne(c, c) yes, hit
801 this.debug('** at the end')
802 // a ** at the end will just swallow the rest.
803 // We have found a match.
804 // however, it will not swallow /.x, unless
805 // options.dot is set.
806 // . and .. are *never* matched by **, for explosively
807 // exponential reasons.
808 for (; fi < fl; fi++) {
809 if (file[fi] === '.' || file[fi] === '..' ||
810 (!options.dot && file[fi].charAt(0) === '.')) return false
815 // ok, let's see if we can swallow whatever we can.
817 var swallowee = file[fr]
819 this.debug('\nglobstar while', file, fr, pattern, pr, swallowee)
821 // XXX remove this slice. Just pass the start index.
822 if (this.matchOne(file.slice(fr), pattern.slice(pr), partial)) {
823 this.debug('globstar found match!', fr, fl, swallowee)
827 // can't swallow "." or ".." ever.
828 // can only swallow ".foo" when explicitly asked.
829 if (swallowee === '.' || swallowee === '..' ||
830 (!options.dot && swallowee.charAt(0) === '.')) {
831 this.debug('dot detected!', file, fr, pattern, pr)
835 // ** swallows a segment, and continue.
836 this.debug('globstar swallow a segment, and continue')
841 // no match was found.
842 // However, in partial mode, we can't say this is necessarily over.
843 // If there's more *pattern* left, then
846 this.debug('\n>>> no match, partial?', file, fr, pattern, pr)
847 if (fr === fl) return true
852 // something other than **
853 // non-magic patterns just have to match exactly
854 // patterns with magic have been turned into regexps.
856 if (typeof p === 'string') {
857 if (options.nocase) {
858 hit = f.toLowerCase() === p.toLowerCase()
862 this.debug('string match', p, f, hit)
865 this.debug('pattern match', p, f, hit)
868 if (!hit) return false
871 // Note: ending in / means that we'll get a final ""
872 // at the end of the pattern. This can only match a
873 // corresponding "" at the end of the file.
874 // If the file ends in /, then it can only match a
875 // a pattern that ends in /, unless the pattern just
876 // doesn't have any more for it. But, a/b/ should *not*
877 // match "a/b/*", even though "" matches against the
878 // [^/]*? pattern, except in partial mode, where it might
879 // simply not be reached yet.
880 // However, a/b/ should still satisfy a/*
882 // now either we fell off the end of the pattern, or we're done.
883 if (fi === fl && pi === pl) {
884 // ran out of pattern and filename at the same time.
887 } else if (fi === fl) {
888 // ran out of file, but still had pattern left.
889 // this is ok if we're doing the match as part of
890 // a glob fs traversal.
892 } else if (pi === pl) {
893 // ran out of pattern, still have file left.
894 // this is only acceptable if we're on the very last
895 // empty segment of a file with a trailing slash.
896 // a/* should match a/b/
897 var emptyFileEnd = (fi === fl - 1) && (file[fi] === '')
901 // should be unreachable.
902 throw new Error('wtf?')
905 // replace stuff like \* with *
906 function globUnescape (s) {
907 return s.replace(/\\(.)/g, '$1')
910 function regExpEscape (s) {
911 return s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&')