react / wstein / node_modules / browserify / node_modules / glob / node_modules / minimatch / minimatch.js
80538 viewsmodule.exports = minimatch1minimatch.Minimatch = Minimatch23var path = { sep: '/' }4try {5path = require('path')6} catch (er) {}78var GLOBSTAR = minimatch.GLOBSTAR = Minimatch.GLOBSTAR = {}9var expand = require('brace-expansion')1011// any single thing other than /12// don't need to escape / when using new RegExp()13var qmark = '[^/]'1415// * => any number of characters16var star = qmark + '*?'1718// ** when dots are allowed. Anything goes, except .. and .19// not (^ or / followed by one or two dots followed by $ or /),20// followed by anything, any number of times.21var twoStarDot = '(?:(?!(?:\\\/|^)(?:\\.{1,2})($|\\\/)).)*?'2223// not a ^ or / followed by a dot,24// followed by anything, any number of times.25var twoStarNoDot = '(?:(?!(?:\\\/|^)\\.).)*?'2627// characters that need to be escaped in RegExp.28var reSpecials = charSet('().*{}+?[]^$\\!')2930// "abc" -> { a:true, b:true, c:true }31function charSet (s) {32return s.split('').reduce(function (set, c) {33set[c] = true34return set35}, {})36}3738// normalizes slashes.39var slashSplit = /\/+/4041minimatch.filter = filter42function filter (pattern, options) {43options = options || {}44return function (p, i, list) {45return minimatch(p, pattern, options)46}47}4849function ext (a, b) {50a = a || {}51b = b || {}52var t = {}53Object.keys(b).forEach(function (k) {54t[k] = b[k]55})56Object.keys(a).forEach(function (k) {57t[k] = a[k]58})59return t60}6162minimatch.defaults = function (def) {63if (!def || !Object.keys(def).length) return minimatch6465var orig = minimatch6667var m = function minimatch (p, pattern, options) {68return orig.minimatch(p, pattern, ext(def, options))69}7071m.Minimatch = function Minimatch (pattern, options) {72return new orig.Minimatch(pattern, ext(def, options))73}7475return m76}7778Minimatch.defaults = function (def) {79if (!def || !Object.keys(def).length) return Minimatch80return minimatch.defaults(def).Minimatch81}8283function minimatch (p, pattern, options) {84if (typeof pattern !== 'string') {85throw new TypeError('glob pattern string required')86}8788if (!options) options = {}8990// shortcut: comments match nothing.91if (!options.nocomment && pattern.charAt(0) === '#') {92return false93}9495// "" only matches ""96if (pattern.trim() === '') return p === ''9798return new Minimatch(pattern, options).match(p)99}100101function Minimatch (pattern, options) {102if (!(this instanceof Minimatch)) {103return new Minimatch(pattern, options)104}105106if (typeof pattern !== 'string') {107throw new TypeError('glob pattern string required')108}109110if (!options) options = {}111pattern = pattern.trim()112113// windows support: need to use /, not \114if (path.sep !== '/') {115pattern = pattern.split(path.sep).join('/')116}117118this.options = options119this.set = []120this.pattern = pattern121this.regexp = null122this.negate = false123this.comment = false124this.empty = false125126// make the set of regexps etc.127this.make()128}129130Minimatch.prototype.debug = function () {}131132Minimatch.prototype.make = make133function make () {134// don't do it more than once.135if (this._made) return136137var pattern = this.pattern138var options = this.options139140// empty patterns and comments match nothing.141if (!options.nocomment && pattern.charAt(0) === '#') {142this.comment = true143return144}145if (!pattern) {146this.empty = true147return148}149150// step 1: figure out negation, etc.151this.parseNegate()152153// step 2: expand braces154var set = this.globSet = this.braceExpand()155156if (options.debug) this.debug = console.error157158this.debug(this.pattern, set)159160// step 3: now we have a set, so turn each one into a series of path-portion161// matching patterns.162// These will be regexps, except in the case of "**", which is163// set to the GLOBSTAR object for globstar behavior,164// and will not contain any / characters165set = this.globParts = set.map(function (s) {166return s.split(slashSplit)167})168169this.debug(this.pattern, set)170171// glob --> regexps172set = set.map(function (s, si, set) {173return s.map(this.parse, this)174}, this)175176this.debug(this.pattern, set)177178// filter out everything that didn't compile properly.179set = set.filter(function (s) {180return s.indexOf(false) === -1181})182183this.debug(this.pattern, set)184185this.set = set186}187188Minimatch.prototype.parseNegate = parseNegate189function parseNegate () {190var pattern = this.pattern191var negate = false192var options = this.options193var negateOffset = 0194195if (options.nonegate) return196197for (var i = 0, l = pattern.length198; i < l && pattern.charAt(i) === '!'199; i++) {200negate = !negate201negateOffset++202}203204if (negateOffset) this.pattern = pattern.substr(negateOffset)205this.negate = negate206}207208// Brace expansion:209// a{b,c}d -> abd acd210// a{b,}c -> abc ac211// a{0..3}d -> a0d a1d a2d a3d212// a{b,c{d,e}f}g -> abg acdfg acefg213// a{b,c}d{e,f}g -> abdeg acdeg abdeg abdfg214//215// Invalid sets are not expanded.216// a{2..}b -> a{2..}b217// a{b}c -> a{b}c218minimatch.braceExpand = function (pattern, options) {219return braceExpand(pattern, options)220}221222Minimatch.prototype.braceExpand = braceExpand223224function braceExpand (pattern, options) {225if (!options) {226if (this instanceof Minimatch) {227options = this.options228} else {229options = {}230}231}232233pattern = typeof pattern === 'undefined'234? this.pattern : pattern235236if (typeof pattern === 'undefined') {237throw new Error('undefined pattern')238}239240if (options.nobrace ||241!pattern.match(/\{.*\}/)) {242// shortcut. no need to expand.243return [pattern]244}245246return expand(pattern)247}248249// parse a component of the expanded set.250// At this point, no pattern may contain "/" in it251// so we're going to return a 2d array, where each entry is the full252// pattern, split on '/', and then turned into a regular expression.253// A regexp is made at the end which joins each array with an254// escaped /, and another full one which joins each regexp with |.255//256// Following the lead of Bash 4.1, note that "**" only has special meaning257// when it is the *only* thing in a path portion. Otherwise, any series258// of * is equivalent to a single *. Globstar behavior is enabled by259// default, and can be disabled by setting options.noglobstar.260Minimatch.prototype.parse = parse261var SUBPARSE = {}262function parse (pattern, isSub) {263var options = this.options264265// shortcuts266if (!options.noglobstar && pattern === '**') return GLOBSTAR267if (pattern === '') return ''268269var re = ''270var hasMagic = !!options.nocase271var escaping = false272// ? => one single character273var patternListStack = []274var plType275var stateChar276var inClass = false277var reClassStart = -1278var classStart = -1279// . and .. never match anything that doesn't start with .,280// even when options.dot is set.281var patternStart = pattern.charAt(0) === '.' ? '' // anything282// not (start or / followed by . or .. followed by / or end)283: options.dot ? '(?!(?:^|\\\/)\\.{1,2}(?:$|\\\/))'284: '(?!\\.)'285var self = this286287function clearStateChar () {288if (stateChar) {289// we had some state-tracking character290// that wasn't consumed by this pass.291switch (stateChar) {292case '*':293re += star294hasMagic = true295break296case '?':297re += qmark298hasMagic = true299break300default:301re += '\\' + stateChar302break303}304self.debug('clearStateChar %j %j', stateChar, re)305stateChar = false306}307}308309for (var i = 0, len = pattern.length, c310; (i < len) && (c = pattern.charAt(i))311; i++) {312this.debug('%s\t%s %s %j', pattern, i, re, c)313314// skip over any that are escaped.315if (escaping && reSpecials[c]) {316re += '\\' + c317escaping = false318continue319}320321switch (c) {322case '/':323// completely not allowed, even escaped.324// Should already be path-split by now.325return false326327case '\\':328clearStateChar()329escaping = true330continue331332// the various stateChar values333// for the "extglob" stuff.334case '?':335case '*':336case '+':337case '@':338case '!':339this.debug('%s\t%s %s %j <-- stateChar', pattern, i, re, c)340341// all of those are literals inside a class, except that342// the glob [!a] means [^a] in regexp343if (inClass) {344this.debug(' in class')345if (c === '!' && i === classStart + 1) c = '^'346re += c347continue348}349350// if we already have a stateChar, then it means351// that there was something like ** or +? in there.352// Handle the stateChar, then proceed with this one.353self.debug('call clearStateChar %j', stateChar)354clearStateChar()355stateChar = c356// if extglob is disabled, then +(asdf|foo) isn't a thing.357// just clear the statechar *now*, rather than even diving into358// the patternList stuff.359if (options.noext) clearStateChar()360continue361362case '(':363if (inClass) {364re += '('365continue366}367368if (!stateChar) {369re += '\\('370continue371}372373plType = stateChar374patternListStack.push({ type: plType, start: i - 1, reStart: re.length })375// negation is (?:(?!js)[^/]*)376re += stateChar === '!' ? '(?:(?!' : '(?:'377this.debug('plType %j %j', stateChar, re)378stateChar = false379continue380381case ')':382if (inClass || !patternListStack.length) {383re += '\\)'384continue385}386387clearStateChar()388hasMagic = true389re += ')'390plType = patternListStack.pop().type391// negation is (?:(?!js)[^/]*)392// The others are (?:<pattern>)<type>393switch (plType) {394case '!':395re += '[^/]*?)'396break397case '?':398case '+':399case '*':400re += plType401break402case '@': break // the default anyway403}404continue405406case '|':407if (inClass || !patternListStack.length || escaping) {408re += '\\|'409escaping = false410continue411}412413clearStateChar()414re += '|'415continue416417// these are mostly the same in regexp and glob418case '[':419// swallow any state-tracking char before the [420clearStateChar()421422if (inClass) {423re += '\\' + c424continue425}426427inClass = true428classStart = i429reClassStart = re.length430re += c431continue432433case ']':434// a right bracket shall lose its special435// meaning and represent itself in436// a bracket expression if it occurs437// first in the list. -- POSIX.2 2.8.3.2438if (i === classStart + 1 || !inClass) {439re += '\\' + c440escaping = false441continue442}443444// handle the case where we left a class open.445// "[z-a]" is valid, equivalent to "\[z-a\]"446if (inClass) {447// split where the last [ was, make sure we don't have448// an invalid re. if so, re-walk the contents of the449// would-be class to re-translate any characters that450// were passed through as-is451// TODO: It would probably be faster to determine this452// without a try/catch and a new RegExp, but it's tricky453// to do safely. For now, this is safe and works.454var cs = pattern.substring(classStart + 1, i)455try {456RegExp('[' + cs + ']')457} catch (er) {458// not a valid class!459var sp = this.parse(cs, SUBPARSE)460re = re.substr(0, reClassStart) + '\\[' + sp[0] + '\\]'461hasMagic = hasMagic || sp[1]462inClass = false463continue464}465}466467// finish up the class.468hasMagic = true469inClass = false470re += c471continue472473default:474// swallow any state char that wasn't consumed475clearStateChar()476477if (escaping) {478// no need479escaping = false480} else if (reSpecials[c]481&& !(c === '^' && inClass)) {482re += '\\'483}484485re += c486487} // switch488} // for489490// handle the case where we left a class open.491// "[abc" is valid, equivalent to "\[abc"492if (inClass) {493// split where the last [ was, and escape it494// this is a huge pita. We now have to re-walk495// the contents of the would-be class to re-translate496// any characters that were passed through as-is497cs = pattern.substr(classStart + 1)498sp = this.parse(cs, SUBPARSE)499re = re.substr(0, reClassStart) + '\\[' + sp[0]500hasMagic = hasMagic || sp[1]501}502503// handle the case where we had a +( thing at the *end*504// of the pattern.505// each pattern list stack adds 3 chars, and we need to go through506// and escape any | chars that were passed through as-is for the regexp.507// Go through and escape them, taking care not to double-escape any508// | chars that were already escaped.509for (var pl = patternListStack.pop(); pl; pl = patternListStack.pop()) {510var tail = re.slice(pl.reStart + 3)511// maybe some even number of \, then maybe 1 \, followed by a |512tail = tail.replace(/((?:\\{2})*)(\\?)\|/g, function (_, $1, $2) {513if (!$2) {514// the | isn't already escaped, so escape it.515$2 = '\\'516}517518// need to escape all those slashes *again*, without escaping the519// one that we need for escaping the | character. As it works out,520// escaping an even number of slashes can be done by simply repeating521// it exactly after itself. That's why this trick works.522//523// I am sorry that you have to see this.524return $1 + $1 + $2 + '|'525})526527this.debug('tail=%j\n %s', tail, tail)528var t = pl.type === '*' ? star529: pl.type === '?' ? qmark530: '\\' + pl.type531532hasMagic = true533re = re.slice(0, pl.reStart) + t + '\\(' + tail534}535536// handle trailing things that only matter at the very end.537clearStateChar()538if (escaping) {539// trailing \\540re += '\\\\'541}542543// only need to apply the nodot start if the re starts with544// something that could conceivably capture a dot545var addPatternStart = false546switch (re.charAt(0)) {547case '.':548case '[':549case '(': addPatternStart = true550}551552// if the re is not "" at this point, then we need to make sure553// it doesn't match against an empty path part.554// Otherwise a/* will match a/, which it should not.555if (re !== '' && hasMagic) re = '(?=.)' + re556557if (addPatternStart) re = patternStart + re558559// parsing just a piece of a larger pattern.560if (isSub === SUBPARSE) {561return [re, hasMagic]562}563564// skip the regexp for non-magical patterns565// unescape anything in it, though, so that it'll be566// an exact match against a file etc.567if (!hasMagic) {568return globUnescape(pattern)569}570571var flags = options.nocase ? 'i' : ''572var regExp = new RegExp('^' + re + '$', flags)573574regExp._glob = pattern575regExp._src = re576577return regExp578}579580minimatch.makeRe = function (pattern, options) {581return new Minimatch(pattern, options || {}).makeRe()582}583584Minimatch.prototype.makeRe = makeRe585function makeRe () {586if (this.regexp || this.regexp === false) return this.regexp587588// at this point, this.set is a 2d array of partial589// pattern strings, or "**".590//591// It's better to use .match(). This function shouldn't592// be used, really, but it's pretty convenient sometimes,593// when you just want to work with a regex.594var set = this.set595596if (!set.length) {597this.regexp = false598return this.regexp599}600var options = this.options601602var twoStar = options.noglobstar ? star603: options.dot ? twoStarDot604: twoStarNoDot605var flags = options.nocase ? 'i' : ''606607var re = set.map(function (pattern) {608return pattern.map(function (p) {609return (p === GLOBSTAR) ? twoStar610: (typeof p === 'string') ? regExpEscape(p)611: p._src612}).join('\\\/')613}).join('|')614615// must match entire pattern616// ending in a * or ** will make it less strict.617re = '^(?:' + re + ')$'618619// can match anything, as long as it's not this.620if (this.negate) re = '^(?!' + re + ').*$'621622try {623this.regexp = new RegExp(re, flags)624} catch (ex) {625this.regexp = false626}627return this.regexp628}629630minimatch.match = function (list, pattern, options) {631options = options || {}632var mm = new Minimatch(pattern, options)633list = list.filter(function (f) {634return mm.match(f)635})636if (mm.options.nonull && !list.length) {637list.push(pattern)638}639return list640}641642Minimatch.prototype.match = match643function match (f, partial) {644this.debug('match', f, this.pattern)645// short-circuit in the case of busted things.646// comments, etc.647if (this.comment) return false648if (this.empty) return f === ''649650if (f === '/' && partial) return true651652var options = this.options653654// windows: need to use /, not \655if (path.sep !== '/') {656f = f.split(path.sep).join('/')657}658659// treat the test path as a set of pathparts.660f = f.split(slashSplit)661this.debug(this.pattern, 'split', f)662663// just ONE of the pattern sets in this.set needs to match664// in order for it to be valid. If negating, then just one665// match means that we have failed.666// Either way, return on the first hit.667668var set = this.set669this.debug(this.pattern, 'set', set)670671// Find the basename of the path by looking for the last non-empty segment672var filename673var i674for (i = f.length - 1; i >= 0; i--) {675filename = f[i]676if (filename) break677}678679for (i = 0; i < set.length; i++) {680var pattern = set[i]681var file = f682if (options.matchBase && pattern.length === 1) {683file = [filename]684}685var hit = this.matchOne(file, pattern, partial)686if (hit) {687if (options.flipNegate) return true688return !this.negate689}690}691692// didn't get any hits. this is success if it's a negative693// pattern, failure otherwise.694if (options.flipNegate) return false695return this.negate696}697698// set partial to true to test if, for example,699// "/a/b" matches the start of "/*/b/*/d"700// Partial means, if you run out of file before you run701// out of pattern, then that's fine, as long as all702// the parts match.703Minimatch.prototype.matchOne = function (file, pattern, partial) {704var options = this.options705706this.debug('matchOne',707{ 'this': this, file: file, pattern: pattern })708709this.debug('matchOne', file.length, pattern.length)710711for (var fi = 0,712pi = 0,713fl = file.length,714pl = pattern.length715; (fi < fl) && (pi < pl)716; fi++, pi++) {717this.debug('matchOne loop')718var p = pattern[pi]719var f = file[fi]720721this.debug(pattern, p, f)722723// should be impossible.724// some invalid regexp stuff in the set.725if (p === false) return false726727if (p === GLOBSTAR) {728this.debug('GLOBSTAR', [pattern, p, f])729730// "**"731// a/**/b/**/c would match the following:732// a/b/x/y/z/c733// a/x/y/z/b/c734// a/b/x/b/x/c735// a/b/c736// To do this, take the rest of the pattern after737// the **, and see if it would match the file remainder.738// If so, return success.739// If not, the ** "swallows" a segment, and try again.740// This is recursively awful.741//742// a/**/b/**/c matching a/b/x/y/z/c743// - a matches a744// - doublestar745// - matchOne(b/x/y/z/c, b/**/c)746// - b matches b747// - doublestar748// - matchOne(x/y/z/c, c) -> no749// - matchOne(y/z/c, c) -> no750// - matchOne(z/c, c) -> no751// - matchOne(c, c) yes, hit752var fr = fi753var pr = pi + 1754if (pr === pl) {755this.debug('** at the end')756// a ** at the end will just swallow the rest.757// We have found a match.758// however, it will not swallow /.x, unless759// options.dot is set.760// . and .. are *never* matched by **, for explosively761// exponential reasons.762for (; fi < fl; fi++) {763if (file[fi] === '.' || file[fi] === '..' ||764(!options.dot && file[fi].charAt(0) === '.')) return false765}766return true767}768769// ok, let's see if we can swallow whatever we can.770while (fr < fl) {771var swallowee = file[fr]772773this.debug('\nglobstar while', file, fr, pattern, pr, swallowee)774775// XXX remove this slice. Just pass the start index.776if (this.matchOne(file.slice(fr), pattern.slice(pr), partial)) {777this.debug('globstar found match!', fr, fl, swallowee)778// found a match.779return true780} else {781// can't swallow "." or ".." ever.782// can only swallow ".foo" when explicitly asked.783if (swallowee === '.' || swallowee === '..' ||784(!options.dot && swallowee.charAt(0) === '.')) {785this.debug('dot detected!', file, fr, pattern, pr)786break787}788789// ** swallows a segment, and continue.790this.debug('globstar swallow a segment, and continue')791fr++792}793}794795// no match was found.796// However, in partial mode, we can't say this is necessarily over.797// If there's more *pattern* left, then798if (partial) {799// ran out of file800this.debug('\n>>> no match, partial?', file, fr, pattern, pr)801if (fr === fl) return true802}803return false804}805806// something other than **807// non-magic patterns just have to match exactly808// patterns with magic have been turned into regexps.809var hit810if (typeof p === 'string') {811if (options.nocase) {812hit = f.toLowerCase() === p.toLowerCase()813} else {814hit = f === p815}816this.debug('string match', p, f, hit)817} else {818hit = f.match(p)819this.debug('pattern match', p, f, hit)820}821822if (!hit) return false823}824825// Note: ending in / means that we'll get a final ""826// at the end of the pattern. This can only match a827// corresponding "" at the end of the file.828// If the file ends in /, then it can only match a829// a pattern that ends in /, unless the pattern just830// doesn't have any more for it. But, a/b/ should *not*831// match "a/b/*", even though "" matches against the832// [^/]*? pattern, except in partial mode, where it might833// simply not be reached yet.834// However, a/b/ should still satisfy a/*835836// now either we fell off the end of the pattern, or we're done.837if (fi === fl && pi === pl) {838// ran out of pattern and filename at the same time.839// an exact hit!840return true841} else if (fi === fl) {842// ran out of file, but still had pattern left.843// this is ok if we're doing the match as part of844// a glob fs traversal.845return partial846} else if (pi === pl) {847// ran out of pattern, still have file left.848// this is only acceptable if we're on the very last849// empty segment of a file with a trailing slash.850// a/* should match a/b/851var emptyFileEnd = (fi === fl - 1) && (file[fi] === '')852return emptyFileEnd853}854855// should be unreachable.856throw new Error('wtf?')857}858859// replace stuff like \* with *860function globUnescape (s) {861return s.replace(/\\(.)/g, '$1')862}863864function regExpEscape (s) {865return s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&')866}867868869