micromatch
Advanced tools
Comparing version 2.3.11 to 3.0.0
977
index.js
@@ -1,431 +0,848 @@ | ||
/*! | ||
* micromatch <https://github.com/jonschlinkert/micromatch> | ||
* | ||
* Copyright (c) 2014-2015, Jon Schlinkert. | ||
* Licensed under the MIT License. | ||
'use strict'; | ||
/** | ||
* Module dependencies | ||
*/ | ||
'use strict'; | ||
var util = require('util'); | ||
var braces = require('braces'); | ||
var toRegex = require('to-regex'); | ||
var extend = require('extend-shallow'); | ||
var expand = require('./lib/expand'); | ||
/** | ||
* Local dependencies | ||
*/ | ||
var compilers = require('./lib/compilers'); | ||
var parsers = require('./lib/parsers'); | ||
var cache = require('./lib/cache'); | ||
var utils = require('./lib/utils'); | ||
var MAX_LENGTH = 1024 * 64; | ||
/** | ||
* The main function. Pass an array of filepaths, | ||
* and a string or array of glob patterns | ||
* The main function takes a list of strings and one or more | ||
* glob patterns to use for matching. | ||
* | ||
* @param {Array|String} `files` | ||
* @param {Array|String} `patterns` | ||
* @param {Object} `opts` | ||
* @return {Array} Array of matches | ||
* ```js | ||
* var mm = require('micromatch'); | ||
* mm(list, patterns[, options]); | ||
* | ||
* console.log(mm(['a.js', 'a.txt'], ['*.js'])); | ||
* //=> [ 'a.js' ] | ||
* ``` | ||
* @param {Array} `list` A list of strings to match | ||
* @param {String|Array} `patterns` One or more glob patterns to use for matching. | ||
* @param {Object} `options` See available [options](#options) for changing how matches are performed | ||
* @return {Array} Returns an array of matches | ||
* @summary false | ||
* @api public | ||
*/ | ||
function micromatch(files, patterns, opts) { | ||
if (!files || !patterns) return []; | ||
opts = opts || {}; | ||
function micromatch(list, patterns, options) { | ||
patterns = utils.arrayify(patterns); | ||
list = utils.arrayify(list); | ||
if (typeof opts.cache === 'undefined') { | ||
opts.cache = true; | ||
var len = patterns.length; | ||
if (list.length === 0 || len === 0) { | ||
return []; | ||
} | ||
if (!Array.isArray(patterns)) { | ||
return match(files, patterns, opts); | ||
if (len === 1) { | ||
return micromatch.match(list, patterns[0], options); | ||
} | ||
var len = patterns.length, i = 0; | ||
var omit = [], keep = []; | ||
var negated = false; | ||
var omit = []; | ||
var keep = []; | ||
var idx = -1; | ||
while (len--) { | ||
var glob = patterns[i++]; | ||
if (typeof glob === 'string' && glob.charCodeAt(0) === 33 /* ! */) { | ||
omit.push.apply(omit, match(files, glob.slice(1), opts)); | ||
while (++idx < len) { | ||
var pattern = patterns[idx]; | ||
if (typeof pattern === 'string' && pattern.charCodeAt(0) === 33 /* ! */) { | ||
omit.push.apply(omit, micromatch.match(list, pattern.slice(1), options)); | ||
negated = true; | ||
} else { | ||
keep.push.apply(keep, match(files, glob, opts)); | ||
keep.push.apply(keep, micromatch.match(list, pattern, options)); | ||
} | ||
} | ||
return utils.diff(keep, omit); | ||
// minimatch.match parity | ||
if (negated && keep.length === 0) { | ||
if (options && options.unixify === false) { | ||
keep = list.slice(); | ||
} else { | ||
var unixify = utils.unixify(options); | ||
for (var i = 0; i < list.length; i++) { | ||
keep.push(unixify(list[i])); | ||
} | ||
} | ||
} | ||
var matches = utils.diff(keep, omit); | ||
if (!options || options.nodupes !== false) { | ||
return utils.unique(matches); | ||
} | ||
return matches; | ||
} | ||
/** | ||
* Return an array of files that match the given glob pattern. | ||
* Similar to the main function, but `pattern` must be a string. | ||
* | ||
* This function is called by the main `micromatch` function If you only | ||
* need to pass a single pattern you might get very minor speed improvements | ||
* using this function. | ||
* ```js | ||
* var mm = require('micromatch'); | ||
* mm.match(list, pattern[, options]); | ||
* | ||
* @param {Array} `files` | ||
* @param {String} `pattern` | ||
* @param {Object} `options` | ||
* @return {Array} | ||
* console.log(mm.match(['a.a', 'a.aa', 'a.b', 'a.c'], '*.a')); | ||
* //=> ['a.a', 'a.aa'] | ||
* ``` | ||
* @param {Array} `list` Array of strings to match | ||
* @param {String} `pattern` Glob pattern to use for matching. | ||
* @param {Object} `options` See available [options](#options) for changing how matches are performed | ||
* @return {Array} Returns an array of matches | ||
* @api public | ||
*/ | ||
function match(files, pattern, opts) { | ||
if (utils.typeOf(files) !== 'string' && !Array.isArray(files)) { | ||
throw new Error(msg('match', 'files', 'a string or array')); | ||
micromatch.match = function(list, pattern, options) { | ||
if (Array.isArray(pattern)) { | ||
throw new TypeError('expected pattern to be a string'); | ||
} | ||
files = utils.arrayify(files); | ||
opts = opts || {}; | ||
var unixify = utils.unixify(options); | ||
var isMatch = memoize('match', pattern, options, micromatch.matcher); | ||
var matches = []; | ||
var negate = opts.negate || false; | ||
var orig = pattern; | ||
list = utils.arrayify(list); | ||
var len = list.length; | ||
var idx = -1; | ||
if (typeof pattern === 'string') { | ||
negate = pattern.charAt(0) === '!'; | ||
if (negate) { | ||
pattern = pattern.slice(1); | ||
while (++idx < len) { | ||
var ele = list[idx]; | ||
if (ele === pattern || isMatch(ele)) { | ||
matches.push(utils.value(ele, unixify, options)); | ||
} | ||
} | ||
// we need to remove the character regardless, | ||
// so the above logic is still needed | ||
if (opts.nonegate === true) { | ||
negate = false; | ||
// if no options were passed, uniquify results and return | ||
if (typeof options === 'undefined') { | ||
return utils.unique(matches); | ||
} | ||
if (matches.length === 0) { | ||
if (options.failglob === true) { | ||
throw new Error('no matches found for "' + pattern + '"'); | ||
} | ||
if (options.nonull === true || options.nullglob === true) { | ||
return [options.unescape ? utils.unescape(pattern) : pattern]; | ||
} | ||
} | ||
var _isMatch = matcher(pattern, opts); | ||
var len = files.length, i = 0; | ||
var res = []; | ||
// if `opts.ignore` was defined, diff ignored list | ||
if (options.ignore) { | ||
matches = micromatch.not(matches, options.ignore, options); | ||
} | ||
while (i < len) { | ||
var file = files[i++]; | ||
var fp = utils.unixify(file, opts); | ||
return options.nodupes !== false ? utils.unique(matches) : matches; | ||
}; | ||
if (!_isMatch(fp)) { continue; } | ||
res.push(fp); | ||
/** | ||
* Returns true if the specified `string` matches the given glob `pattern`. | ||
* | ||
* ```js | ||
* var mm = require('micromatch'); | ||
* mm.isMatch(string, pattern[, options]); | ||
* | ||
* console.log(mm.isMatch('a.a', '*.a')); | ||
* //=> true | ||
* console.log(mm.isMatch('a.b', '*.a')); | ||
* //=> false | ||
* ``` | ||
* @param {String} `string` String to match | ||
* @param {String} `pattern` Glob pattern to use for matching. | ||
* @param {Object} `options` See available [options](#options) for changing how matches are performed | ||
* @return {Boolean} Returns true if the string matches the glob pattern. | ||
* @api public | ||
*/ | ||
micromatch.isMatch = function(str, pattern, options) { | ||
if (typeof str !== 'string') { | ||
throw new TypeError('expected a string: "' + util.inspect(str) + '"'); | ||
} | ||
if (res.length === 0) { | ||
if (opts.failglob === true) { | ||
throw new Error('micromatch.match() found no matches for: "' + orig + '".'); | ||
} | ||
if (isEmptyString(str) || isEmptyString(pattern)) { | ||
return false; | ||
} | ||
if (opts.nonull || opts.nullglob) { | ||
res.push(utils.unescapeGlob(orig)); | ||
} | ||
var equals = utils.equalsPattern(options); | ||
if (equals(str)) { | ||
return true; | ||
} | ||
// if `negate` was defined, diff negated files | ||
if (negate) { res = utils.diff(files, res); } | ||
var isMatch = memoize('isMatch', pattern, options, micromatch.matcher); | ||
return isMatch(str); | ||
}; | ||
// if `ignore` was defined, diff ignored filed | ||
if (opts.ignore && opts.ignore.length) { | ||
pattern = opts.ignore; | ||
opts = utils.omit(opts, ['ignore']); | ||
res = utils.diff(res, micromatch(res, pattern, opts)); | ||
/** | ||
* Returns true if some of the strings in the given `list` match any of the | ||
* given glob `patterns`. | ||
* | ||
* ```js | ||
* var mm = require('micromatch'); | ||
* mm.some(list, patterns[, options]); | ||
* | ||
* console.log(mm.some(['foo.js', 'bar.js'], ['*.js', '!foo.js'])); | ||
* // true | ||
* console.log(mm.some(['foo.js'], ['*.js', '!foo.js'])); | ||
* // false | ||
* ``` | ||
* @param {String|Array} `list` The string or array of strings to test. Returns as soon as the first match is found. | ||
* @param {String|Array} `patterns` One or more glob patterns to use for matching. | ||
* @param {Object} `options` See available [options](#options) for changing how matches are performed | ||
* @return {Boolean} Returns true if any patterns match `str` | ||
* @api public | ||
*/ | ||
micromatch.some = function(list, patterns, options) { | ||
if (typeof list === 'string') { | ||
list = [list]; | ||
} | ||
for (var i = 0; i < list.length; i++) { | ||
if (micromatch(list[i], patterns, options).length === 1) { | ||
return true; | ||
} | ||
} | ||
return false; | ||
}; | ||
if (opts.nodupes) { | ||
return utils.unique(res); | ||
/** | ||
* Returns true if every string in the given `list` matches | ||
* any of the given glob `patterns`. | ||
* | ||
* ```js | ||
* var mm = require('micromatch'); | ||
* mm.every(list, patterns[, options]); | ||
* | ||
* console.log(mm.every('foo.js', ['foo.js'])); | ||
* // true | ||
* console.log(mm.every(['foo.js', 'bar.js'], ['*.js'])); | ||
* // true | ||
* console.log(mm.every(['foo.js', 'bar.js'], ['*.js', '!foo.js'])); | ||
* // false | ||
* console.log(mm.every(['foo.js'], ['*.js', '!foo.js'])); | ||
* // false | ||
* ``` | ||
* @param {String|Array} `list` The string or array of strings to test. | ||
* @param {String|Array} `patterns` One or more glob patterns to use for matching. | ||
* @param {Object} `options` See available [options](#options) for changing how matches are performed | ||
* @return {Boolean} Returns true if any patterns match `str` | ||
* @api public | ||
*/ | ||
micromatch.every = function(list, patterns, options) { | ||
if (typeof list === 'string') { | ||
list = [list]; | ||
} | ||
return res; | ||
} | ||
for (var i = 0; i < list.length; i++) { | ||
if (micromatch(list[i], patterns, options).length !== 1) { | ||
return false; | ||
} | ||
} | ||
return true; | ||
}; | ||
/** | ||
* Returns a function that takes a glob pattern or array of glob patterns | ||
* to be used with `Array#filter()`. (Internally this function generates | ||
* the matching function using the [matcher] method). | ||
* Returns true if **any** of the given glob `patterns` | ||
* match the specified `string`. | ||
* | ||
* ```js | ||
* var fn = mm.filter('[a-c]'); | ||
* ['a', 'b', 'c', 'd', 'e'].filter(fn); | ||
* //=> ['a', 'b', 'c'] | ||
* var mm = require('micromatch'); | ||
* mm.any(string, patterns[, options]); | ||
* | ||
* console.log(mm.any('a.a', ['b.*', '*.a'])); | ||
* //=> true | ||
* console.log(mm.any('a.a', 'b.*')); | ||
* //=> false | ||
* ``` | ||
* @param {String|Array} `patterns` Can be a glob or array of globs. | ||
* @param {Options} `opts` Options to pass to the [matcher] method. | ||
* @return {Function} Filter function to be passed to `Array#filter()`. | ||
* @param {String|Array} `str` The string to test. | ||
* @param {String|Array} `patterns` One or more glob patterns to use for matching. | ||
* @param {Object} `options` See available [options](#options) for changing how matches are performed | ||
* @return {Boolean} Returns true if any patterns match `str` | ||
* @api public | ||
*/ | ||
function filter(patterns, opts) { | ||
if (!Array.isArray(patterns) && typeof patterns !== 'string') { | ||
throw new TypeError(msg('filter', 'patterns', 'a string or array')); | ||
micromatch.any = function(str, patterns, options) { | ||
if (typeof str !== 'string') { | ||
throw new TypeError('expected a string: "' + util.inspect(str) + '"'); | ||
} | ||
patterns = utils.arrayify(patterns); | ||
var len = patterns.length, i = 0; | ||
var patternMatchers = Array(len); | ||
while (i < len) { | ||
patternMatchers[i] = matcher(patterns[i++], opts); | ||
if (isEmptyString(str) || isEmptyString(patterns)) { | ||
return false; | ||
} | ||
return function(fp) { | ||
if (fp == null) return []; | ||
var len = patternMatchers.length, i = 0; | ||
var res = true; | ||
if (typeof patterns === 'string') { | ||
patterns = [patterns]; | ||
} | ||
fp = utils.unixify(fp, opts); | ||
while (i < len) { | ||
var fn = patternMatchers[i++]; | ||
if (!fn(fp)) { | ||
res = false; | ||
break; | ||
} | ||
for (var i = 0; i < patterns.length; i++) { | ||
if (micromatch.isMatch(str, patterns[i], options)) { | ||
return true; | ||
} | ||
return res; | ||
}; | ||
} | ||
} | ||
return false; | ||
}; | ||
/** | ||
* Returns true if the filepath contains the given | ||
* pattern. Can also return a function for matching. | ||
* Returns true if **all** of the given `patterns` match | ||
* the specified string. | ||
* | ||
* ```js | ||
* isMatch('foo.md', '*.md', {}); | ||
* //=> true | ||
* var mm = require('micromatch'); | ||
* mm.all(string, patterns[, options]); | ||
* | ||
* isMatch('*.md', {})('foo.md') | ||
* //=> true | ||
* console.log(mm.all('foo.js', ['foo.js'])); | ||
* // true | ||
* | ||
* console.log(mm.all('foo.js', ['*.js', '!foo.js'])); | ||
* // false | ||
* | ||
* console.log(mm.all('foo.js', ['*.js', 'foo.js'])); | ||
* // true | ||
* | ||
* console.log(mm.all('foo.js', ['*.js', 'f*', '*o*', '*o.js'])); | ||
* // true | ||
* ``` | ||
* @param {String} `fp` | ||
* @param {String} `pattern` | ||
* @param {Object} `opts` | ||
* @return {Boolean} | ||
* @param {String|Array} `str` The string to test. | ||
* @param {String|Array} `patterns` One or more glob patterns to use for matching. | ||
* @param {Object} `options` See available [options](#options) for changing how matches are performed | ||
* @return {Boolean} Returns true if any patterns match `str` | ||
* @api public | ||
*/ | ||
function isMatch(fp, pattern, opts) { | ||
if (typeof fp !== 'string') { | ||
throw new TypeError(msg('isMatch', 'filepath', 'a string')); | ||
micromatch.all = function(str, patterns, options) { | ||
if (typeof str !== 'string') { | ||
throw new TypeError('expected a string: "' + util.inspect(str) + '"'); | ||
} | ||
fp = utils.unixify(fp, opts); | ||
if (utils.typeOf(pattern) === 'object') { | ||
return matcher(fp, pattern); | ||
if (typeof patterns === 'string') { | ||
patterns = [patterns]; | ||
} | ||
return matcher(pattern, opts)(fp); | ||
} | ||
for (var i = 0; i < patterns.length; i++) { | ||
if (!micromatch.isMatch(str, patterns[i], options)) { | ||
return false; | ||
} | ||
} | ||
return true; | ||
}; | ||
/** | ||
* Returns true if the filepath matches the | ||
* given pattern. | ||
* Returns a list of strings that _**do not match any**_ of the given `patterns`. | ||
* | ||
* ```js | ||
* var mm = require('micromatch'); | ||
* mm.not(list, patterns[, options]); | ||
* | ||
* console.log(mm.not(['a.a', 'b.b', 'c.c'], '*.a')); | ||
* //=> ['b.b', 'c.c'] | ||
* ``` | ||
* @param {Array} `list` Array of strings to match. | ||
* @param {String|Array} `patterns` One or more glob pattern to use for matching. | ||
* @param {Object} `options` See available [options](#options) for changing how matches are performed | ||
* @return {Array} Returns an array of strings that **do not match** the given patterns. | ||
* @api public | ||
*/ | ||
function contains(fp, pattern, opts) { | ||
if (typeof fp !== 'string') { | ||
throw new TypeError(msg('contains', 'pattern', 'a string')); | ||
} | ||
micromatch.not = function(list, patterns, options) { | ||
var opts = extend({}, options); | ||
var ignore = opts.ignore; | ||
delete opts.ignore; | ||
opts = opts || {}; | ||
opts.contains = (pattern !== ''); | ||
fp = utils.unixify(fp, opts); | ||
list = utils.arrayify(list); | ||
if (opts.contains && !utils.isGlob(pattern)) { | ||
return fp.indexOf(pattern) !== -1; | ||
var matches = utils.diff(list, micromatch(list, patterns, opts)); | ||
if (ignore) { | ||
matches = utils.diff(matches, micromatch(list, ignore)); | ||
} | ||
return matcher(pattern, opts)(fp); | ||
} | ||
return opts.nodupes !== false ? utils.unique(matches) : matches; | ||
}; | ||
/** | ||
* Returns true if a file path matches any of the | ||
* given patterns. | ||
* Returns true if the given `string` contains the given pattern. Similar | ||
* to [.isMatch](#isMatch) but the pattern can match any part of the string. | ||
* | ||
* @param {String} `fp` The filepath to test. | ||
* @param {String|Array} `patterns` Glob patterns to use. | ||
* @param {Object} `opts` Options to pass to the `matcher()` function. | ||
* @return {String} | ||
* ```js | ||
* var mm = require('micromatch'); | ||
* mm.contains(string, pattern[, options]); | ||
* | ||
* console.log(mm.contains('aa/bb/cc', '*b')); | ||
* //=> true | ||
* console.log(mm.contains('aa/bb/cc', '*d')); | ||
* //=> false | ||
* ``` | ||
* @param {String} `str` The string to match. | ||
* @param {String|Array} `patterns` Glob pattern to use for matching. | ||
* @param {Object} `options` See available [options](#options) for changing how matches are performed | ||
* @return {Boolean} Returns true if the patter matches any part of `str`. | ||
* @api public | ||
*/ | ||
function any(fp, patterns, opts) { | ||
if (!Array.isArray(patterns) && typeof patterns !== 'string') { | ||
throw new TypeError(msg('any', 'patterns', 'a string or array')); | ||
micromatch.contains = function(str, patterns, options) { | ||
if (typeof str !== 'string') { | ||
throw new TypeError('expected a string: "' + util.inspect(str) + '"'); | ||
} | ||
patterns = utils.arrayify(patterns); | ||
var len = patterns.length; | ||
if (typeof patterns === 'string') { | ||
if (isEmptyString(str) || isEmptyString(patterns)) { | ||
return false; | ||
} | ||
fp = utils.unixify(fp, opts); | ||
while (len--) { | ||
var isMatch = matcher(patterns[len], opts); | ||
if (isMatch(fp)) { | ||
var equals = utils.equalsPattern(patterns, options); | ||
if (equals(str)) { | ||
return true; | ||
} | ||
var contains = utils.containsPattern(patterns, options); | ||
if (contains(str)) { | ||
return true; | ||
} | ||
} | ||
return false; | ||
} | ||
var opts = extend({}, options, {contains: true}); | ||
return micromatch.any(str, patterns, opts); | ||
}; | ||
/** | ||
* Filter the keys of an object with the given `glob` pattern | ||
* and `options` | ||
* | ||
* @param {Object} `object` | ||
* @param {Pattern} `object` | ||
* @return {Array} | ||
* Returns true if the given pattern and options should enable | ||
* the `matchBase` option. | ||
* @return {Boolean} | ||
* @api private | ||
*/ | ||
function matchKeys(obj, glob, options) { | ||
if (utils.typeOf(obj) !== 'object') { | ||
throw new TypeError(msg('matchKeys', 'first argument', 'an object')); | ||
} | ||
micromatch.matchBase = function(pattern, options) { | ||
if (pattern && pattern.indexOf('/') !== -1 || !options) return false; | ||
return options.basename === true || options.matchBase === true; | ||
}; | ||
var fn = matcher(glob, options); | ||
var res = {}; | ||
/** | ||
* Filter the keys of the given object with the given `glob` pattern | ||
* and `options`. Does not attempt to match nested keys. If you need this feature, | ||
* use [glob-object][] instead. | ||
* | ||
* ```js | ||
* var mm = require('micromatch'); | ||
* mm.matchKeys(object, patterns[, options]); | ||
* | ||
* var obj = { aa: 'a', ab: 'b', ac: 'c' }; | ||
* console.log(mm.matchKeys(obj, '*b')); | ||
* //=> { ab: 'b' } | ||
* ``` | ||
* @param {Object} `object` The object with keys to filter. | ||
* @param {String|Array} `patterns` One or more glob patterns to use for matching. | ||
* @param {Object} `options` See available [options](#options) for changing how matches are performed | ||
* @return {Object} Returns an object with only keys that match the given patterns. | ||
* @api public | ||
*/ | ||
for (var key in obj) { | ||
if (obj.hasOwnProperty(key) && fn(key)) { | ||
res[key] = obj[key]; | ||
} | ||
micromatch.matchKeys = function(obj, patterns, options) { | ||
if (!utils.isObject(obj)) { | ||
throw new TypeError('expected the first argument to be an object'); | ||
} | ||
return res; | ||
} | ||
var keys = micromatch(Object.keys(obj), patterns, options); | ||
return utils.pick(obj, keys); | ||
}; | ||
/** | ||
* Return a function for matching based on the | ||
* given `pattern` and `options`. | ||
* Returns a memoized matcher function from the given glob `pattern` and `options`. | ||
* The returned function takes a string to match as its only argument and returns | ||
* true if the string is a match. | ||
* | ||
* @param {String} `pattern` | ||
* @param {Object} `options` | ||
* @return {Function} | ||
* ```js | ||
* var mm = require('micromatch'); | ||
* mm.matcher(pattern[, options]); | ||
* | ||
* var isMatch = mm.matcher('*.!(*a)'); | ||
* console.log(isMatch('a.a')); | ||
* //=> false | ||
* console.log(isMatch('a.b')); | ||
* //=> true | ||
* ``` | ||
* @param {String} `pattern` Glob pattern | ||
* @param {Object} `options` See available [options](#options) for changing how matches are performed. | ||
* @return {Function} Returns a matcher function. | ||
* @api public | ||
*/ | ||
function matcher(pattern, opts) { | ||
// pattern is a function | ||
if (typeof pattern === 'function') { | ||
return pattern; | ||
micromatch.matcher = function matcher(pattern, options) { | ||
if (Array.isArray(pattern)) { | ||
return compose(pattern, options, matcher); | ||
} | ||
// pattern is a regex | ||
// if pattern is a regex | ||
if (pattern instanceof RegExp) { | ||
return function(fp) { | ||
return pattern.test(fp); | ||
}; | ||
return test(pattern); | ||
} | ||
if (typeof pattern !== 'string') { | ||
throw new TypeError(msg('matcher', 'pattern', 'a string, regex, or function')); | ||
// if pattern is invalid | ||
if (!utils.isString(pattern)) { | ||
throw new TypeError('expected pattern to be an array, string or regex'); | ||
} | ||
// strings, all the way down... | ||
pattern = utils.unixify(pattern, opts); | ||
// if pattern is a non-glob string | ||
if (!utils.hasSpecialChars(pattern)) { | ||
if (options && options.nocase === true) { | ||
pattern = pattern.toLowerCase(); | ||
} | ||
return utils.matchPath(pattern, options); | ||
} | ||
// pattern is a non-glob string | ||
if (!utils.isGlob(pattern)) { | ||
return utils.matchPath(pattern, opts); | ||
// if pattern is a glob string | ||
var re = micromatch.makeRe(pattern, options); | ||
// if `options.matchBase` or `options.basename` is defined | ||
if (micromatch.matchBase(pattern, options)) { | ||
return utils.matchBasename(re, options); | ||
} | ||
// pattern is a glob string | ||
var re = makeRe(pattern, opts); | ||
// `matchBase` is defined | ||
if (opts && opts.matchBase) { | ||
return utils.hasFilename(re, opts); | ||
function test(regex) { | ||
var equals = utils.equalsPattern(options); | ||
var unixify = utils.unixify(options); | ||
return function(str) { | ||
if (equals(str)) { | ||
return true; | ||
} | ||
if (regex.test(unixify(str))) { | ||
return true; | ||
} | ||
return false; | ||
}; | ||
} | ||
// `matchBase` is not defined | ||
return function(fp) { | ||
fp = utils.unixify(fp, opts); | ||
return re.test(fp); | ||
}; | ||
} | ||
var fn = test(re); | ||
fn.result = re.result; | ||
return fn; | ||
}; | ||
/** | ||
* Create and cache a regular expression for matching | ||
* file paths. | ||
* Create a regular expression from the given glob `pattern`. | ||
* | ||
* If the leading character in the `glob` is `!`, a negation | ||
* regex is returned. | ||
* ```js | ||
* var mm = require('micromatch'); | ||
* mm.makeRe(pattern[, options]); | ||
* | ||
* @param {String} `glob` | ||
* @param {Object} `options` | ||
* @return {RegExp} | ||
* console.log(mm.makeRe('*.js')); | ||
* //=> /^(?:(\.[\\\/])?(?!\.)(?=.)[^\/]*?\.js)$/ | ||
* ``` | ||
* @param {String} `pattern` A glob pattern to convert to regex. | ||
* @param {Object} `options` See available [options](#options) for changing how matches are performed. | ||
* @return {RegExp} Returns a regex created from the given pattern. | ||
* @api public | ||
*/ | ||
function toRegex(glob, options) { | ||
// clone options to prevent mutating the original object | ||
var opts = Object.create(options || {}); | ||
var flags = opts.flags || ''; | ||
if (opts.nocase && flags.indexOf('i') === -1) { | ||
flags += 'i'; | ||
micromatch.makeRe = function(pattern, options) { | ||
if (typeof pattern !== 'string') { | ||
throw new TypeError('expected pattern to be a string'); | ||
} | ||
var parsed = expand(glob, opts); | ||
if (pattern.length > MAX_LENGTH) { | ||
throw new Error('expected pattern to be less than ' + MAX_LENGTH + ' characters'); | ||
} | ||
// pass in tokens to avoid parsing more than once | ||
opts.negated = opts.negated || parsed.negated; | ||
opts.negate = opts.negated; | ||
glob = wrapGlob(parsed.pattern, opts); | ||
var re; | ||
function makeRe() { | ||
var result = micromatch.create(pattern, options); | ||
var asts = []; | ||
var output = result.map(function(obj) { | ||
obj.ast.state = obj.state; | ||
asts.push(obj.ast); | ||
return obj.output; | ||
}); | ||
try { | ||
re = new RegExp(glob, flags); | ||
return re; | ||
} catch (err) { | ||
err.reason = 'micromatch invalid regex: (' + re + ')'; | ||
if (opts.strict) throw new SyntaxError(err); | ||
var regex = toRegex(output.join('|'), options); | ||
regex.result = asts; | ||
return regex; | ||
} | ||
// we're only here if a bad pattern was used and the user | ||
// passed `options.silent`, so match nothing | ||
return /$^/; | ||
} | ||
return memoize('makeRe', pattern, options, makeRe); | ||
}; | ||
/** | ||
* Create the regex to do the matching. If the leading | ||
* character in the `glob` is `!` a negation regex is returned. | ||
* Expand the given brace `pattern`. | ||
* | ||
* @param {String} `glob` | ||
* @param {Boolean} `negate` | ||
* ```js | ||
* var mm = require('micromatch'); | ||
* console.log(mm.braces('foo/{a,b}/bar')); | ||
* //=> ['foo/(a|b)/bar'] | ||
* | ||
* console.log(mm.braces('foo/{a,b}/bar', {expand: true})); | ||
* //=> ['foo/(a|b)/bar'] | ||
* ``` | ||
* @param {String} `pattern` String with brace pattern to expand. | ||
* @param {Object} `options` Any [options](#options) to change how expansion is performed. See the [braces][] library for all available options. | ||
* @return {Array} | ||
* @api public | ||
*/ | ||
function wrapGlob(glob, opts) { | ||
var prefix = (opts && !opts.contains) ? '^' : ''; | ||
var after = (opts && !opts.contains) ? '$' : ''; | ||
glob = ('(?:' + glob + ')' + after); | ||
if (opts && opts.negate) { | ||
return prefix + ('(?!^' + glob + ').*$'); | ||
micromatch.braces = function(pattern, options) { | ||
if (typeof pattern !== 'string') { | ||
throw new TypeError('expected a string'); | ||
} | ||
return prefix + glob; | ||
} | ||
function expand() { | ||
if (options && options.nobrace === true) return [pattern]; | ||
if (!/\{.*\}/.test(pattern)) return [pattern]; | ||
return braces(pattern, options); | ||
} | ||
return memoize('braces', pattern, options, expand); | ||
}; | ||
/** | ||
* Create and cache a regular expression for matching file paths. | ||
* If the leading character in the `glob` is `!`, a negation | ||
* regex is returned. | ||
* Proxy to the [micromatch.braces](#method), for parity with | ||
* minimatch. | ||
*/ | ||
micromatch.braceExpand = function(pattern, options) { | ||
var opts = extend({}, options, {expand: true}); | ||
return micromatch.braces(pattern, opts); | ||
}; | ||
/** | ||
* Parses the given glob `pattern` and returns an array of abstract syntax | ||
* trees (ASTs), with the compiled `output` and optional source `map` on | ||
* each AST. | ||
* | ||
* @param {String} `glob` | ||
* @param {Object} `options` | ||
* @return {RegExp} | ||
* ```js | ||
* var mm = require('micromatch'); | ||
* mm.create(pattern[, options]); | ||
* | ||
* console.log(mm.create('abc/*.js')); | ||
* // [{ options: { source: 'string', sourcemap: true }, | ||
* // state: {}, | ||
* // compilers: | ||
* // { ... }, | ||
* // output: '(\\.[\\\\\\/])?abc\\/(?!\\.)(?=.)[^\\/]*?\\.js', | ||
* // ast: | ||
* // { type: 'root', | ||
* // errors: [], | ||
* // nodes: | ||
* // [ ... ], | ||
* // dot: false, | ||
* // input: 'abc/*.js' }, | ||
* // parsingErrors: [], | ||
* // map: | ||
* // { version: 3, | ||
* // sources: [ 'string' ], | ||
* // names: [], | ||
* // mappings: 'AAAA,GAAG,EAAC,kBAAC,EAAC,EAAE', | ||
* // sourcesContent: [ 'abc/*.js' ] }, | ||
* // position: { line: 1, column: 28 }, | ||
* // content: {}, | ||
* // files: {}, | ||
* // idx: 6 }] | ||
* ``` | ||
* @param {String} `pattern` Glob pattern to parse and compile. | ||
* @param {Object} `options` Any [options](#options) to change how parsing and compiling is performed. | ||
* @return {Object} Returns an object with the parsed AST, compiled string and optional source map. | ||
* @api public | ||
*/ | ||
function makeRe(glob, opts) { | ||
if (utils.typeOf(glob) !== 'string') { | ||
throw new Error(msg('makeRe', 'glob', 'a string')); | ||
micromatch.create = function(pattern, options) { | ||
return memoize('create', pattern, options, function() { | ||
function create(str, opts) { | ||
return micromatch.compile(micromatch.parse(str, opts), opts); | ||
} | ||
pattern = micromatch.braces(pattern, options); | ||
var len = pattern.length; | ||
var idx = -1; | ||
var res = []; | ||
while (++idx < len) { | ||
res.push(create(pattern[idx], options)); | ||
} | ||
return res; | ||
}); | ||
}; | ||
/** | ||
* Parse the given `str` with the given `options`. | ||
* | ||
* ```js | ||
* var mm = require('micromatch'); | ||
* mm.parse(pattern[, options]); | ||
* | ||
* var ast = mm.parse('a/{b,c}/d'); | ||
* console.log(ast); | ||
* // { type: 'root', | ||
* // errors: [], | ||
* // input: 'a/{b,c}/d', | ||
* // nodes: | ||
* // [ { type: 'bos', val: '' }, | ||
* // { type: 'text', val: 'a/' }, | ||
* // { type: 'brace', | ||
* // nodes: | ||
* // [ { type: 'brace.open', val: '{' }, | ||
* // { type: 'text', val: 'b,c' }, | ||
* // { type: 'brace.close', val: '}' } ] }, | ||
* // { type: 'text', val: '/d' }, | ||
* // { type: 'eos', val: '' } ] } | ||
* ``` | ||
* @param {String} `str` | ||
* @param {Object} `options` | ||
* @return {Object} Returns an AST | ||
* @api public | ||
*/ | ||
micromatch.parse = function(pattern, options) { | ||
if (typeof pattern !== 'string') { | ||
throw new TypeError('expected a string'); | ||
} | ||
return utils.cache(toRegex, glob, opts); | ||
} | ||
function parse() { | ||
var snapdragon = utils.instantiate(null, options); | ||
parsers(snapdragon, options); | ||
if (pattern.slice(0, 2) === './') { | ||
pattern = pattern.slice(2); | ||
} | ||
pattern = utils.combineDuplicates(pattern, '\\*\\*\\/|\\/\\*\\*'); | ||
var ast = snapdragon.parse(pattern, options); | ||
utils.define(ast, 'snapdragon', snapdragon); | ||
ast.input = pattern; | ||
return ast; | ||
} | ||
return memoize('parse', pattern, options, parse); | ||
}; | ||
/** | ||
* Make error messages consistent. Follows this format: | ||
* Compile the given `ast` or string with the given `options`. | ||
* | ||
* ```js | ||
* msg(methodName, argNumber, nativeType); | ||
* // example: | ||
* msg('matchKeys', 'first', 'an object'); | ||
* var mm = require('micromatch'); | ||
* mm.compile(ast[, options]); | ||
* | ||
* var ast = mm.parse('a/{b,c}/d'); | ||
* console.log(mm.compile(ast)); | ||
* // { options: { source: 'string' }, | ||
* // state: {}, | ||
* // compilers: | ||
* // { eos: [Function], | ||
* // noop: [Function], | ||
* // bos: [Function], | ||
* // brace: [Function], | ||
* // 'brace.open': [Function], | ||
* // text: [Function], | ||
* // 'brace.close': [Function] }, | ||
* // output: [ 'a/(b|c)/d' ], | ||
* // ast: | ||
* // { ... }, | ||
* // parsingErrors: [] } | ||
* ``` | ||
* @param {Object|String} `ast` | ||
* @param {Object} `options` | ||
* @return {Object} Returns an object that has an `output` property with the compiled string. | ||
* @api public | ||
*/ | ||
micromatch.compile = function(ast, options) { | ||
if (typeof ast === 'string') { | ||
ast = micromatch.parse(ast, options); | ||
} | ||
return memoize('compile', ast.input, options, function() { | ||
var snapdragon = utils.instantiate(ast, options); | ||
compilers(snapdragon, options); | ||
return snapdragon.compile(ast, options); | ||
}); | ||
}; | ||
/** | ||
* Clear the regex cache. | ||
* | ||
* @param {String} `method` | ||
* @param {String} `num` | ||
* @param {String} `type` | ||
* @return {String} | ||
* ```js | ||
* mm.clearCache(); | ||
* ``` | ||
* @api public | ||
*/ | ||
function msg(method, what, type) { | ||
return 'micromatch.' + method + '(): ' + what + ' should be ' + type + '.'; | ||
micromatch.clearCache = function() { | ||
micromatch.cache.caches = {}; | ||
}; | ||
/** | ||
* Returns true if the given value is effectively an empty string | ||
*/ | ||
function isEmptyString(val) { | ||
return String(val) === '' || String(val) === './'; | ||
} | ||
/** | ||
* Public methods | ||
* Compose a matcher function with the given patterns. | ||
* This allows matcher functions to be compiled once and | ||
* called multiple times. | ||
*/ | ||
/* eslint no-multi-spaces: 0 */ | ||
micromatch.any = any; | ||
micromatch.braces = micromatch.braceExpand = utils.braces; | ||
micromatch.contains = contains; | ||
micromatch.expand = expand; | ||
micromatch.filter = filter; | ||
micromatch.isMatch = isMatch; | ||
micromatch.makeRe = makeRe; | ||
micromatch.match = match; | ||
micromatch.matcher = matcher; | ||
micromatch.matchKeys = matchKeys; | ||
function compose(patterns, options, matcher) { | ||
var matchers; | ||
return memoize('compose', String(patterns), options, function() { | ||
return function(file) { | ||
// delay composition until it's invoked the first time, | ||
// after that it won't be called again | ||
if (!matchers) { | ||
matchers = []; | ||
for (var i = 0; i < patterns.length; i++) { | ||
matchers.push(matcher(patterns[i], options)); | ||
} | ||
} | ||
var len = matchers.length; | ||
while (len--) { | ||
if (matchers[len](file) === true) { | ||
return true; | ||
} | ||
} | ||
return false; | ||
}; | ||
}); | ||
} | ||
/** | ||
* Memoize a generated regex or function. A unique key is generated | ||
* from the `type` (usually method name), the `pattern`, and | ||
* user-defined options. | ||
*/ | ||
function memoize(type, pattern, options, fn) { | ||
var key = utils.createKey(type + '=' + pattern, options); | ||
if (options && options.cache === false) { | ||
return fn(pattern, options); | ||
} | ||
if (cache.has(type, key)) { | ||
return cache.get(type, key); | ||
} | ||
var val = fn(pattern, options); | ||
cache.set(type, key, val); | ||
return val; | ||
} | ||
/** | ||
* Expose compiler, parser and cache on `micromatch` | ||
*/ | ||
micromatch.compilers = compilers; | ||
micromatch.parsers = parsers; | ||
micromatch.caches = cache.caches; | ||
/** | ||
* Expose `micromatch` | ||
* @type {Function} | ||
*/ | ||
module.exports = micromatch; |
329
lib/utils.js
'use strict'; | ||
var win32 = process && process.platform === 'win32'; | ||
var utils = module.exports; | ||
var path = require('path'); | ||
var fileRe = require('filename-regex'); | ||
var utils = module.exports; | ||
@@ -12,49 +10,184 @@ /** | ||
var Snapdragon = require('snapdragon'); | ||
utils.define = require('define-property'); | ||
utils.diff = require('arr-diff'); | ||
utils.extend = require('extend-shallow'); | ||
utils.pick = require('object.pick'); | ||
utils.typeOf = require('kind-of'); | ||
utils.unique = require('array-unique'); | ||
utils.braces = require('braces'); | ||
utils.brackets = require('expand-brackets'); | ||
utils.extglob = require('extglob'); | ||
utils.isExtglob = require('is-extglob'); | ||
utils.isGlob = require('is-glob'); | ||
utils.typeOf = require('kind-of'); | ||
utils.normalize = require('normalize-path'); | ||
utils.omit = require('object.omit'); | ||
utils.parseGlob = require('parse-glob'); | ||
utils.cache = require('regex-cache'); | ||
/** | ||
* Get the filename of a filepath | ||
* Returns true if the platform is windows, or `path.sep` is `\\`. | ||
* This is defined as a function to allow `path.sep` to be set in unit tests, | ||
* or by the user, if there is a reason to do so. | ||
* @return {Boolean} | ||
*/ | ||
utils.isWindows = function() { | ||
return path.sep === '\\' || process.platform === 'win32'; | ||
}; | ||
/** | ||
* Get the `Snapdragon` instance to use | ||
*/ | ||
utils.instantiate = function(ast, options) { | ||
var snapdragon; | ||
// if an instance was created by `.parse`, use that instance | ||
if (utils.typeOf(ast) === 'object' && ast.snapdragon) { | ||
snapdragon = ast.snapdragon; | ||
// if the user supplies an instance on options, use that instance | ||
} else if (utils.typeOf(options) === 'object' && options.snapdragon) { | ||
snapdragon = options.snapdragon; | ||
// create a new instance | ||
} else { | ||
snapdragon = new Snapdragon(options); | ||
} | ||
utils.define(snapdragon, 'parse', function(str, options) { | ||
var parsed = Snapdragon.prototype.parse.apply(this, arguments); | ||
parsed.input = str; | ||
// escape unmatched brace/bracket/parens | ||
var last = this.parser.stack.pop(); | ||
if (last && this.options.strictErrors !== true) { | ||
var open = last.nodes[0]; | ||
var inner = last.nodes[1]; | ||
if (last.type === 'bracket') { | ||
if (inner.val.charAt(0) === '[') { | ||
inner.val = '\\' + inner.val; | ||
} | ||
} else { | ||
open.val = '\\' + open.val; | ||
var sibling = open.parent.nodes[1]; | ||
if (sibling.type === 'star') { | ||
sibling.loose = true; | ||
} | ||
} | ||
} | ||
// add non-enumerable parser reference | ||
utils.define(parsed, 'parser', this.parser); | ||
return parsed; | ||
}); | ||
return snapdragon; | ||
}; | ||
/** | ||
* Create the key to use for memoization. The key is generated | ||
* by iterating over the options and concatenating key-value pairs | ||
* to the pattern string. | ||
*/ | ||
utils.createKey = function(pattern, options) { | ||
if (typeof options === 'undefined') { | ||
return pattern; | ||
} | ||
var val = pattern; | ||
var keys = Object.keys(options); | ||
for (var i = 0; i < keys.length; i++) { | ||
var key = keys[i]; | ||
val += ';' + key + '=' + String(options[key]); | ||
} | ||
return val; | ||
}; | ||
/** | ||
* Cast `val` to an array | ||
* @return {Array} | ||
*/ | ||
utils.arrayify = function(val) { | ||
if (typeof val === 'string') return [val]; | ||
return val ? (Array.isArray(val) ? val : [val]) : []; | ||
}; | ||
/** | ||
* Return true if `val` is a non-empty string | ||
*/ | ||
utils.isString = function(val) { | ||
return typeof val === 'string'; | ||
}; | ||
/** | ||
* Return true if `val` is a non-empty string | ||
*/ | ||
utils.isObject = function(val) { | ||
return utils.typeOf(val) === 'object'; | ||
}; | ||
/** | ||
* Combines duplicate characters in the provided string. | ||
* @param {String} `str` | ||
* @returns {String} | ||
*/ | ||
utils.combineDuplicates = function(str, val) { | ||
var re = new RegExp('(' + val + ')(?=(?:' + val + ')*\\1)', 'g'); | ||
return str.replace(re, ''); | ||
}; | ||
/** | ||
* Returns true if the given `str` has special characters | ||
*/ | ||
utils.hasSpecialChars = function(str) { | ||
return /(?:(?:(^|\/)[!.])|[*?+()|\[\]{}]|[+@]\()/.test(str); | ||
}; | ||
/** | ||
* Normalize slashes in the given filepath. | ||
* | ||
* @param {String} `string` | ||
* @param {String} `filepath` | ||
* @return {String} | ||
*/ | ||
utils.filename = function filename(fp) { | ||
var seg = fp.match(fileRe()); | ||
return seg && seg[0]; | ||
utils.toPosixPath = function(str) { | ||
return str.replace(/\\+/g, '/'); | ||
}; | ||
/** | ||
* Returns a function that returns true if the given | ||
* pattern is the same as a given `filepath` | ||
* Strip backslashes before special characters in a string. | ||
* | ||
* @param {String} `pattern` | ||
* @return {Function} | ||
* @param {String} `str` | ||
* @return {String} | ||
*/ | ||
utils.isPath = function isPath(pattern, opts) { | ||
opts = opts || {}; | ||
return function(fp) { | ||
var unixified = utils.unixify(fp, opts); | ||
if(opts.nocase){ | ||
return pattern.toLowerCase() === unixified.toLowerCase(); | ||
} | ||
return pattern === unixified; | ||
}; | ||
utils.unescape = function(str) { | ||
return utils.toPosixPath(str.replace(/\\(?=[*+?!.])/g, '')); | ||
}; | ||
/** | ||
* Strip the prefix from a filepath | ||
* @param {String} `fp` | ||
* @return {String} | ||
*/ | ||
utils.stripPrefix = function(str) { | ||
if (str.charAt(0) !== '.') { | ||
return str; | ||
} | ||
var ch = str.charAt(1); | ||
if (utils.isSlash(ch)) { | ||
return str.slice(2); | ||
} | ||
return str; | ||
}; | ||
/** | ||
* Returns true if the given str is an escaped or | ||
* unescaped path character | ||
*/ | ||
utils.isSlash = function(str) { | ||
return str === '/' || str === '\\/' || str === '\\' || str === '\\\\'; | ||
}; | ||
/** | ||
* Returns a function that returns true if the given | ||
* pattern contains a `filepath` | ||
* pattern matches or contains a `filepath` | ||
* | ||
@@ -65,11 +198,29 @@ * @param {String} `pattern` | ||
utils.hasPath = function hasPath(pattern, opts) { | ||
return function(fp) { | ||
return utils.unixify(pattern, opts).indexOf(fp) !== -1; | ||
}; | ||
utils.matchPath = function(pattern, options) { | ||
return (options && options.contains) | ||
? utils.containsPattern(pattern, options) | ||
: utils.equalsPattern(pattern, options); | ||
}; | ||
/** | ||
* Returns true if the given (original) filepath or unixified path are equal | ||
* to the given pattern. | ||
*/ | ||
utils._equals = function(filepath, unixPath, pattern) { | ||
return pattern === filepath || pattern === unixPath; | ||
}; | ||
/** | ||
* Returns true if the given (original) filepath or unixified path contain | ||
* the given pattern. | ||
*/ | ||
utils._contains = function(filepath, unixPath, pattern) { | ||
return filepath.indexOf(pattern) !== -1 || unixPath.indexOf(pattern) !== -1; | ||
}; | ||
/** | ||
* Returns a function that returns true if the given | ||
* pattern matches or contains a `filepath` | ||
* pattern is the same as a given `filepath` | ||
* | ||
@@ -80,7 +231,14 @@ * @param {String} `pattern` | ||
utils.matchPath = function matchPath(pattern, opts) { | ||
var fn = (opts && opts.contains) | ||
? utils.hasPath(pattern, opts) | ||
: utils.isPath(pattern, opts); | ||
return fn; | ||
utils.equalsPattern = function(pattern, options) { | ||
var unixify = utils.unixify(options); | ||
options = options || {}; | ||
return function fn(filepath) { | ||
var equal = utils._equals(filepath, unixify(filepath), pattern); | ||
if (equal === true || options.nocase !== true) { | ||
return equal; | ||
} | ||
var lower = filepath.toLowerCase(); | ||
return utils._equals(lower, unixify(lower), pattern); | ||
}; | ||
}; | ||
@@ -90,12 +248,19 @@ | ||
* Returns a function that returns true if the given | ||
* regex matches the `filename` of a file path. | ||
* pattern contains a `filepath` | ||
* | ||
* @param {RegExp} `re` | ||
* @return {Boolean} | ||
* @param {String} `pattern` | ||
* @return {Function} | ||
*/ | ||
utils.hasFilename = function hasFilename(re) { | ||
return function(fp) { | ||
var name = utils.filename(fp); | ||
return name && re.test(name); | ||
utils.containsPattern = function(pattern, options) { | ||
var unixify = utils.unixify(options); | ||
options = options || {}; | ||
return function(filepath) { | ||
var contains = utils._contains(filepath, unixify(filepath), pattern); | ||
if (contains === true || options.nocase !== true) { | ||
return contains; | ||
} | ||
var lower = filepath.toLowerCase(); | ||
return utils._contains(lower, unixify(lower), pattern); | ||
}; | ||
@@ -105,50 +270,48 @@ }; | ||
/** | ||
* Coerce `val` to an array | ||
* Returns a function that returns true if the given | ||
* regex matches the `filename` of a file path. | ||
* | ||
* @param {*} val | ||
* @return {Array} | ||
* @param {RegExp} `re` Matching regex | ||
* @return {Function} | ||
*/ | ||
utils.arrayify = function arrayify(val) { | ||
return !Array.isArray(val) | ||
? [val] | ||
: val; | ||
utils.matchBasename = function(re) { | ||
return function(filepath) { | ||
return re.test(filepath) || re.test(path.basename(filepath)); | ||
}; | ||
}; | ||
/** | ||
* Normalize all slashes in a file path or glob pattern to | ||
* forward slashes. | ||
* Determines the filepath to return based on the provided options. | ||
* @return {any} | ||
*/ | ||
utils.unixify = function unixify(fp, opts) { | ||
if (opts && opts.unixify === false) return fp; | ||
if (opts && opts.unixify === true || win32 || path.sep === '\\') { | ||
return utils.normalize(fp, false); | ||
utils.value = function(str, unixify, options) { | ||
if (options && options.unixify === false) { | ||
return str; | ||
} | ||
if (opts && opts.unescape === true) { | ||
return fp ? fp.toString().replace(/\\(\w)/g, '$1') : ''; | ||
} | ||
return fp; | ||
return unixify(str); | ||
}; | ||
/** | ||
* Escape/unescape utils | ||
* Returns a function that normalizes slashes in a string to forward | ||
* slashes, strips `./` from beginning of paths, and optionally unescapes | ||
* special characters. | ||
* @return {Function} | ||
*/ | ||
utils.escapePath = function escapePath(fp) { | ||
return fp.replace(/[\\.]/g, '\\$&'); | ||
utils.unixify = function(options) { | ||
options = options || {}; | ||
return function(filepath) { | ||
if (utils.isWindows() || options.unixify === true) { | ||
filepath = utils.toPosixPath(filepath); | ||
} | ||
if (options.stripPrefix !== false) { | ||
filepath = utils.stripPrefix(filepath); | ||
} | ||
if (options.unescape === true) { | ||
filepath = utils.unescape(filepath); | ||
} | ||
return filepath; | ||
}; | ||
}; | ||
utils.unescapeGlob = function unescapeGlob(fp) { | ||
return fp.replace(/[\\"']/g, ''); | ||
}; | ||
utils.escapeRe = function escapeRe(str) { | ||
return str.replace(/[-[\\$*+?.#^\s{}(|)\]]/g, '\\$&'); | ||
}; | ||
/** | ||
* Expose `utils` | ||
*/ | ||
module.exports = utils; |
128
package.json
{ | ||
"name": "micromatch", | ||
"description": "Glob matching for javascript/node.js. A drop-in replacement and faster alternative to minimatch and multimatch.", | ||
"version": "2.3.11", | ||
"homepage": "https://github.com/jonschlinkert/micromatch", | ||
"version": "3.0.0", | ||
"homepage": "https://github.com/micromatch/micromatch", | ||
"author": "Jon Schlinkert (https://github.com/jonschlinkert)", | ||
"repository": "jonschlinkert/micromatch", | ||
"contributors": [ | ||
"Amila Welihinda (amilajack.com)", | ||
"Bogdan Chadkin (https://github.com/TrySound)", | ||
"Brian Woodward (https://twitter.com/doowb)", | ||
"Charlike Mike Reagent (https://i.am.charlike.online)", | ||
"Elan Shanker (https://github.com/es128)", | ||
"Fabrício Matté (http://ultcombo.js.org)", | ||
"Jon Schlinkert (http://twitter.com/jonschlinkert)", | ||
"Martin Kolárik (https://kolarik.sk)", | ||
"Paul Miller (paulmillr.com)", | ||
"Tom Byrer (https://github.com/tomByrer)", | ||
"(https://github.com/DianeLooney)" | ||
], | ||
"repository": "micromatch/micromatch", | ||
"bugs": { | ||
"url": "https://github.com/jonschlinkert/micromatch/issues" | ||
"url": "https://github.com/micromatch/micromatch/issues" | ||
}, | ||
@@ -24,30 +37,29 @@ "license": "MIT", | ||
"dependencies": { | ||
"arr-diff": "^2.0.0", | ||
"array-unique": "^0.2.1", | ||
"braces": "^1.8.2", | ||
"expand-brackets": "^0.1.4", | ||
"extglob": "^0.3.1", | ||
"filename-regex": "^2.0.0", | ||
"is-extglob": "^1.0.0", | ||
"is-glob": "^2.0.1", | ||
"kind-of": "^3.0.2", | ||
"normalize-path": "^2.0.1", | ||
"object.omit": "^2.0.0", | ||
"parse-glob": "^3.0.4", | ||
"regex-cache": "^0.4.2" | ||
"arr-diff": "^3.0.0", | ||
"array-unique": "^0.3.2", | ||
"braces": "^2.0.3", | ||
"define-property": "^0.2.5", | ||
"extend-shallow": "^2.0.1", | ||
"extglob": "^1.1.0", | ||
"fragment-cache": "^0.2.1", | ||
"kind-of": "^3.1.0", | ||
"nanomatch": "^1.1.1", | ||
"object.pick": "^1.2.0", | ||
"regex-not": "^1.0.0", | ||
"snapdragon": "^0.8.1", | ||
"to-regex": "^3.0.1" | ||
}, | ||
"devDependencies": { | ||
"benchmarked": "^0.1.4", | ||
"chalk": "^1.1.1", | ||
"gulp": "^3.9.0", | ||
"gulp-eslint": "^1.1.1", | ||
"gulp-format-md": "^0.1.8", | ||
"gulp-istanbul": "^0.10.1", | ||
"gulp-mocha": "^2.1.3", | ||
"minimatch": "^3.0.0", | ||
"bash-match": "^0.2.0", | ||
"extend-shallow": "^2.0.1", | ||
"for-own": "^1.0.0", | ||
"gulp": "^3.9.1", | ||
"gulp-istanbul": "^1.1.1", | ||
"gulp-mocha": "^3.0.0", | ||
"gulp-unused": "^0.2.1", | ||
"is-windows": "^1.0.1", | ||
"minimatch": "^3.0.3", | ||
"minimist": "^1.2.0", | ||
"mocha": "^2", | ||
"multimatch": "^2.0.0", | ||
"should": "^8", | ||
"write": "^0.2.1" | ||
"mocha": "^3.4.2", | ||
"multimatch": "^2.1.0" | ||
}, | ||
@@ -71,2 +83,3 @@ "keywords": [ | ||
"matching", | ||
"micromatch", | ||
"minimatch", | ||
@@ -83,3 +96,33 @@ "multimatch", | ||
], | ||
"lintDeps": { | ||
"dependencies": { | ||
"lock": { | ||
"snapdragon": "^0.8.1" | ||
} | ||
}, | ||
"devDependencies": { | ||
"options": { | ||
"ignore": [ | ||
"benchmark/**" | ||
] | ||
}, | ||
"files": [ | ||
"examples/*.js", | ||
"gulpfile.js", | ||
"test/**/*.js" | ||
] | ||
} | ||
}, | ||
"verb": { | ||
"toc": "collapsible", | ||
"layout": "default", | ||
"tasks": [ | ||
"readme" | ||
], | ||
"plugins": [ | ||
"gulp-format-md" | ||
], | ||
"helpers": [ | ||
"./benchmark/helper.js" | ||
], | ||
"related": { | ||
@@ -89,30 +132,19 @@ "list": [ | ||
"expand-brackets", | ||
"expand-range", | ||
"extglob", | ||
"fill-range", | ||
"gulp-micromatch", | ||
"is-glob", | ||
"parse-glob" | ||
"nanomatch" | ||
] | ||
}, | ||
"lint": { | ||
"reflinks": true | ||
}, | ||
"reflinks": [ | ||
"braces", | ||
"expand-brackets", | ||
"extglob", | ||
"glob-object", | ||
"minimatch", | ||
"multimatch", | ||
"verb" | ||
], | ||
"toc": false, | ||
"layout": false, | ||
"tasks": [ | ||
"readme" | ||
], | ||
"plugins": [ | ||
"gulp-format-md" | ||
], | ||
"lint": { | ||
"reflinks": true | ||
} | ||
"snapdragon", | ||
"expand-brackets" | ||
] | ||
} | ||
} |
1068
README.md
@@ -1,11 +0,53 @@ | ||
# micromatch [![NPM version](https://img.shields.io/npm/v/micromatch.svg?style=flat)](https://www.npmjs.com/package/micromatch) [![NPM downloads](https://img.shields.io/npm/dm/micromatch.svg?style=flat)](https://npmjs.org/package/micromatch) [![Build Status](https://img.shields.io/travis/jonschlinkert/micromatch.svg?style=flat)](https://travis-ci.org/jonschlinkert/micromatch) | ||
# micromatch [![NPM version](https://img.shields.io/npm/v/micromatch.svg?style=flat)](https://www.npmjs.com/package/micromatch) [![NPM monthly downloads](https://img.shields.io/npm/dm/micromatch.svg?style=flat)](https://npmjs.org/package/micromatch) [![NPM total downloads](https://img.shields.io/npm/dt/micromatch.svg?style=flat)](https://npmjs.org/package/micromatch) [![Linux Build Status](https://img.shields.io/travis/micromatch/micromatch.svg?style=flat&label=Travis)](https://travis-ci.org/micromatch/micromatch) [![Windows Build Status](https://img.shields.io/appveyor/ci/micromatch/micromatch.svg?style=flat&label=AppVeyor)](https://ci.appveyor.com/project/micromatch/micromatch) | ||
> Glob matching for javascript/node.js. A drop-in replacement and faster alternative to minimatch and multimatch. | ||
Micromatch supports all of the same matching features as [minimatch](https://github.com/isaacs/minimatch) and [multimatch](https://github.com/sindresorhus/multimatch). | ||
<details> | ||
<summary><strong>Table of Contents</strong></summary> | ||
* [mm()](#usage) is the same as [multimatch()](https://github.com/sindresorhus/multimatch) | ||
* [mm.match()](#match) is the same as [minimatch.match()](https://github.com/isaacs/minimatch) | ||
* use [mm.isMatch()](#ismatch) instead of [minimatch()](https://github.com/isaacs/minimatch) | ||
- [Install](#install) | ||
- [Quickstart](#quickstart) | ||
- [Why use micromatch?](#why-use-micromatch) | ||
* [Matching features](#matching-features) | ||
- [Switching to micromatch](#switching-to-micromatch) | ||
* [From minimatch](#from-minimatch) | ||
* [From multimatch](#from-multimatch) | ||
- [API](#api) | ||
- [Options](#options) | ||
* [options.basename](#optionsbasename) | ||
* [options.bash](#optionsbash) | ||
* [options.cache](#optionscache) | ||
* [options.dot](#optionsdot) | ||
* [options.failglob](#optionsfailglob) | ||
* [options.ignore](#optionsignore) | ||
* [options.matchBase](#optionsmatchbase) | ||
* [options.nobrace](#optionsnobrace) | ||
* [options.nocase](#optionsnocase) | ||
* [options.nodupes](#optionsnodupes) | ||
* [options.noext](#optionsnoext) | ||
* [options.nonegate](#optionsnonegate) | ||
* [options.noglobstar](#optionsnoglobstar) | ||
* [options.nonull](#optionsnonull) | ||
* [options.nullglob](#optionsnullglob) | ||
* [options.snapdragon](#optionssnapdragon) | ||
* [options.sourcemap](#optionssourcemap) | ||
* [options.unescape](#optionsunescape) | ||
* [options.unixify](#optionsunixify) | ||
- [Extended globbing](#extended-globbing) | ||
* [extglobs](#extglobs) | ||
* [braces](#braces) | ||
* [regex character classes](#regex-character-classes) | ||
* [regex groups](#regex-groups) | ||
* [POSIX bracket expressions](#posix-bracket-expressions) | ||
- [Notes](#notes) | ||
* [Bash 4.3 parity](#bash-43-parity) | ||
* [Backslashes](#backslashes) | ||
- [Contributing](#contributing) | ||
- [Benchmarks](#benchmarks) | ||
* [Running benchmarks](#running-benchmarks) | ||
* [Latest results](#latest-results) | ||
- [About](#about) | ||
</details> | ||
## Install | ||
@@ -19,48 +61,58 @@ | ||
## Start matching! | ||
## Quickstart | ||
```js | ||
var mm = require('micromatch'); | ||
console.log(mm([''])) | ||
mm(list, patterns[, options]); | ||
``` | ||
*** | ||
The [main export](#micromatch) takes a list of strings and one or more glob patterns: | ||
### Features | ||
```js | ||
console.log(mm(['foo', 'bar', 'qux'], ['f*', 'b*'])); | ||
//=> ['foo', 'bar'] | ||
``` | ||
* [Drop-in replacement](#switch-from-minimatch) for [minimatch](https://github.com/isaacs/minimatch) and [multimatch](https://github.com/sindresorhus/multimatch) | ||
* Built-in support for multiple glob patterns, like `['foo/*.js', '!bar.js']` | ||
* [Brace Expansion](https://github.com/jonschlinkert/braces) (`foo/bar-{1..5}.md`, `one/{two,three}/four.md`) | ||
* Typical glob patterns, like `**/*`, `a/b/*.js`, or `['foo/*.js', '!bar.js']` | ||
* Methods like `.isMatch()`, `.contains()` and `.any()` | ||
Use [.isMatch()](#ismatch) to get true/false: | ||
**Extended globbing features:** | ||
```js | ||
console.log(mm.isMatch('foo', 'f*')); | ||
//=> true | ||
``` | ||
* Logical `OR` (`foo/bar/(abc|xyz).js`) | ||
* Regex character classes (`foo/bar/baz-[1-5].js`) | ||
* POSIX [bracket expressions](https://github.com/jonschlinkert/expand-brackets) (`**/[[:alpha:][:digit:]]/`) | ||
* [extglobs](https://github.com/jonschlinkert/extglob) (`**/+(x|y)`, `!(a|b)`, etc). | ||
[Switching](#switching-to-micromatch) from minimatch and multimatch is easy! | ||
You can combine these to create whatever matching patterns you need. | ||
## Why use micromatch? | ||
**Example** | ||
> micromatch is a [drop-in replacement](#switching-to-micromatch) for minimatch and multimatch | ||
```js | ||
// double-negation! | ||
mm(['fa', 'fb', 'f', 'fo'], '!(f!(o))'); | ||
//=> ['fo'] | ||
``` | ||
* Supports all of the same matching features as [minimatch](https://github.com/isaacs/minimatch) and [multimatch](https://github.com/sindresorhus/multimatch) | ||
* Micromatch uses [snapdragon](https://github.com/jonschlinkert/snapdragon) for parsing and compiling globs, which provides granular control over the entire conversion process in a way that is easy to understand, reason about, and maintain. | ||
* More accurate, with more than 36,000 [test assertions](./test) to prove it. | ||
* More complete support for the Bash 4.3 specification than minimatch and multimatch. Micromatch passes _all of the spec tests_ from bash, including some that bash still fails. | ||
* [Faster matching](#benchmarks), from a combination of optimized glob patterns, faster algorithms, and regex caching. | ||
* [Micromatch is safer](https://github.com/micromatch/braces#braces-is-safe), and is not subject to DoS with brace patterns, like minimatch and multimatch. | ||
* More reliable windows support than minimatch and multimatch. | ||
## Why switch to micromatch? | ||
### Matching features | ||
* Native support for multiple glob patterns, no need for wrappers like [multimatch](https://github.com/sindresorhus/multimatch) | ||
* [10-55x faster](#benchmarks) and more performant than [minimatch](https://github.com/isaacs/minimatch) and [multimatch](https://github.com/sindresorhus/multimatch). This is achieved through a combination of caching and regex optimization strategies, a fundamentally different approach than minimatch. | ||
* More extensive support for the Bash 4.3 specification | ||
* More complete extglob support | ||
* Extensive [unit tests](./test) (approx. 1,300 tests). Minimatch fails many of the tests. | ||
* Support for multiple glob patterns (no need for wrappers like multimatch) | ||
* Wildcards (`**`, `*.js`) | ||
* Negation (`'!a/*.js'`, `'*!(b).js']`) | ||
* [extglobs](https://github.com/jonschlinkert/extglob) (`+(x|y)`, `!(a|b)`) | ||
* [POSIX character classes](https://github.com/micromatch/expand-brackets) (`[[:alpha:][:digit:]]`) | ||
* [brace expansion](https://github.com/micromatch/braces) (`foo/{1..5}.md`, `bar/{a,b,c}.js`) | ||
* regex character classes (`foo-[1-5].js`) | ||
* regex logical "or" (`foo/(abc|xyz).js`) | ||
### Switch from minimatch | ||
You can mix and match these features to create whatever patterns you need! | ||
Use `mm.isMatch()` instead of `minimatch()`: | ||
## Switching to micromatch | ||
There is one notable difference between micromatch and minimatch in regards to how backslashes are handled. See [the notes about backslashes](#backslashes) for more information. | ||
### From minimatch | ||
Use [mm.isMatch()](#ismatch) instead of `minimatch()`: | ||
```js | ||
@@ -71,3 +123,3 @@ mm.isMatch('foo', 'b*'); | ||
Use `mm.match()` instead of `minimatch.match()`: | ||
Use [mm.match()](#match) instead of `minimatch.match()`: | ||
@@ -79,3 +131,3 @@ ```js | ||
### Switch from multimatch | ||
### From multimatch | ||
@@ -89,202 +141,353 @@ Same signature: | ||
*** | ||
## API | ||
## Usage | ||
### [micromatch](index.js#L41) | ||
Add micromatch to your node.js project: | ||
The main function takes a list of strings and one or more glob patterns to use for matching. | ||
**Params** | ||
* `list` **{Array}**: A list of strings to match | ||
* `patterns` **{String|Array}**: One or more glob patterns to use for matching. | ||
* `options` **{Object}**: See available [options](#options) for changing how matches are performed | ||
* `returns` **{Array}**: Returns an array of matches | ||
**Example** | ||
```js | ||
var mm = require('micromatch'); | ||
mm(list, patterns[, options]); | ||
console.log(mm(['a.js', 'a.txt'], ['*.js'])); | ||
//=> [ 'a.js' ] | ||
``` | ||
**Signature** | ||
### [.match](index.js#L107) | ||
```js | ||
mm(array_of_strings, glob_patterns[, options]); | ||
``` | ||
Similar to the main function, but `pattern` must be a string. | ||
**Params** | ||
* `list` **{Array}**: Array of strings to match | ||
* `pattern` **{String}**: Glob pattern to use for matching. | ||
* `options` **{Object}**: See available [options](#options) for changing how matches are performed | ||
* `returns` **{Array}**: Returns an array of matches | ||
**Example** | ||
```js | ||
mm(['foo', 'bar', 'baz'], 'b*'); | ||
//=> ['bar', 'baz'] | ||
var mm = require('micromatch'); | ||
mm.match(list, pattern[, options]); | ||
console.log(mm.match(['a.a', 'a.aa', 'a.b', 'a.c'], '*.a')); | ||
//=> ['a.a', 'a.aa'] | ||
``` | ||
### Usage examples | ||
### [.isMatch](index.js#L168) | ||
**Brace expansion** | ||
Returns true if the specified `string` matches the given glob `pattern`. | ||
Match files with `.js` or `.txt` extensions. | ||
**Params** | ||
* `string` **{String}**: String to match | ||
* `pattern` **{String}**: Glob pattern to use for matching. | ||
* `options` **{Object}**: See available [options](#options) for changing how matches are performed | ||
* `returns` **{Boolean}**: Returns true if the string matches the glob pattern. | ||
**Example** | ||
```js | ||
mm(['a.js', 'b.md', 'c.txt'], '*.{js,txt}'); | ||
//=> ['a.js', 'c.txt'] | ||
var mm = require('micromatch'); | ||
mm.isMatch(string, pattern[, options]); | ||
console.log(mm.isMatch('a.a', '*.a')); | ||
//=> true | ||
console.log(mm.isMatch('a.b', '*.a')); | ||
//=> false | ||
``` | ||
**Extglobs** | ||
### [.some](index.js#L206) | ||
Match anything except for files with the `.md` extension. | ||
Returns true if some of the strings in the given `list` match any of the given glob `patterns`. | ||
**Params** | ||
* `list` **{String|Array}**: The string or array of strings to test. Returns as soon as the first match is found. | ||
* `patterns` **{String|Array}**: One or more glob patterns to use for matching. | ||
* `options` **{Object}**: See available [options](#options) for changing how matches are performed | ||
* `returns` **{Boolean}**: Returns true if any patterns match `str` | ||
**Example** | ||
```js | ||
mm(files, '**/*.!(md)'); | ||
var mm = require('micromatch'); | ||
mm.some(list, patterns[, options]); | ||
//=> ['a.js', 'c.txt'] | ||
console.log(mm.some(['foo.js', 'bar.js'], ['*.js', '!foo.js'])); | ||
// true | ||
console.log(mm.some(['foo.js'], ['*.js', '!foo.js'])); | ||
// false | ||
``` | ||
**Multiple patterns** | ||
### [.every](index.js#L242) | ||
Match using an array of patterns. | ||
Returns true if every string in the given `list` matches any of the given glob `patterns`. | ||
**Params** | ||
* `list` **{String|Array}**: The string or array of strings to test. | ||
* `patterns` **{String|Array}**: One or more glob patterns to use for matching. | ||
* `options` **{Object}**: See available [options](#options) for changing how matches are performed | ||
* `returns` **{Boolean}**: Returns true if any patterns match `str` | ||
**Example** | ||
```js | ||
mm(['a.md', 'b.js', 'c.txt', 'd.json'], ['*.md', '*.txt']); | ||
//=> ['a.md', 'c.txt'] | ||
var mm = require('micromatch'); | ||
mm.every(list, patterns[, options]); | ||
console.log(mm.every('foo.js', ['foo.js'])); | ||
// true | ||
console.log(mm.every(['foo.js', 'bar.js'], ['*.js'])); | ||
// true | ||
console.log(mm.every(['foo.js', 'bar.js'], ['*.js', '!foo.js'])); | ||
// false | ||
console.log(mm.every(['foo.js'], ['*.js', '!foo.js'])); | ||
// false | ||
``` | ||
**Negation patterns:** | ||
### [.any](index.js#L274) | ||
Behavior is designed to be what users would expect, based on conventions that are already well-established. | ||
Returns true if **any** of the given glob `patterns` match the specified `string`. | ||
* [minimatch](https://github.com/isaacs/minimatch) behavior is used when the pattern is a string, so patterns are **inclusive by default**. | ||
* [multimatch](https://github.com/sindresorhus/multimatch) behavior is used when an array of patterns is passed, so patterns are **exclusive by default**. | ||
**Params** | ||
* `str` **{String|Array}**: The string to test. | ||
* `patterns` **{String|Array}**: One or more glob patterns to use for matching. | ||
* `options` **{Object}**: See available [options](#options) for changing how matches are performed | ||
* `returns` **{Boolean}**: Returns true if any patterns match `str` | ||
**Example** | ||
```js | ||
mm(['a.js', 'b.md', 'c.txt'], '!*.{js,txt}'); | ||
//=> ['b.md'] | ||
var mm = require('micromatch'); | ||
mm.any(string, patterns[, options]); | ||
mm(['a.md', 'b.js', 'c.txt', 'd.json'], ['*.*', '!*.{js,txt}']); | ||
//=> ['a.md', 'd.json'] | ||
console.log(mm.any('a.a', ['b.*', '*.a'])); | ||
//=> true | ||
console.log(mm.any('a.a', 'b.*')); | ||
//=> false | ||
``` | ||
*** | ||
### [.all](index.js#L322) | ||
## API methods | ||
Returns true if **all** of the given `patterns` match the specified string. | ||
**Params** | ||
* `str` **{String|Array}**: The string to test. | ||
* `patterns` **{String|Array}**: One or more glob patterns to use for matching. | ||
* `options` **{Object}**: See available [options](#options) for changing how matches are performed | ||
* `returns` **{Boolean}**: Returns true if any patterns match `str` | ||
**Example** | ||
```js | ||
var mm = require('micromatch'); | ||
``` | ||
mm.all(string, patterns[, options]); | ||
### .match | ||
console.log(mm.all('foo.js', ['foo.js'])); | ||
// true | ||
```js | ||
mm.match(array, globString); | ||
console.log(mm.all('foo.js', ['*.js', '!foo.js'])); | ||
// false | ||
console.log(mm.all('foo.js', ['*.js', 'foo.js'])); | ||
// true | ||
console.log(mm.all('foo.js', ['*.js', 'f*', '*o*', '*o.js'])); | ||
// true | ||
``` | ||
Return an array of files that match the given glob pattern. Useful if you only need to use a single glob pattern. | ||
### [.not](index.js#L354) | ||
Returns a list of strings that _**do not match any**_ of the given `patterns`. | ||
**Params** | ||
* `list` **{Array}**: Array of strings to match. | ||
* `patterns` **{String|Array}**: One or more glob pattern to use for matching. | ||
* `options` **{Object}**: See available [options](#options) for changing how matches are performed | ||
* `returns` **{Array}**: Returns an array of strings that **do not match** the given patterns. | ||
**Example** | ||
```js | ||
mm.match(['ab', 'a/b', 'bb', 'b/c'], '?b'); | ||
//=> ['ab', 'bb'] | ||
var mm = require('micromatch'); | ||
mm.not(list, patterns[, options]); | ||
mm.match(['ab', 'a/b', 'bb', 'b/c'], '*/b'); | ||
//=> ['a/b'] | ||
console.log(mm.not(['a.a', 'b.b', 'c.c'], '*.a')); | ||
//=> ['b.b', 'c.c'] | ||
``` | ||
### .isMatch | ||
### [.contains](index.js#L389) | ||
```js | ||
mm.isMatch(filepath, globString); | ||
``` | ||
Returns true if the given `string` contains the given pattern. Similar to [.isMatch](#isMatch) but the pattern can match any part of the string. | ||
Returns true if a file path matches the given glob pattern. | ||
**Params** | ||
* `str` **{String}**: The string to match. | ||
* `patterns` **{String|Array}**: Glob pattern to use for matching. | ||
* `options` **{Object}**: See available [options](#options) for changing how matches are performed | ||
* `returns` **{Boolean}**: Returns true if the patter matches any part of `str`. | ||
**Example** | ||
```js | ||
mm.isMatch('.verb.md', '*.md'); | ||
//=> false | ||
var mm = require('micromatch'); | ||
mm.contains(string, pattern[, options]); | ||
mm.isMatch('.verb.md', '*.md', {dot: true}); | ||
console.log(mm.contains('aa/bb/cc', '*b')); | ||
//=> true | ||
console.log(mm.contains('aa/bb/cc', '*d')); | ||
//=> false | ||
``` | ||
### .contains | ||
### [.matchKeys](index.js#L445) | ||
Returns true if any part of a file path matches the given glob pattern. Think of this is "has path" versus "is path". | ||
Filter the keys of the given object with the given `glob` pattern and `options`. Does not attempt to match nested keys. If you need this feature, use [glob-object](https://github.com/jonschlinkert/glob-object) instead. | ||
**Params** | ||
* `object` **{Object}**: The object with keys to filter. | ||
* `patterns` **{String|Array}**: One or more glob patterns to use for matching. | ||
* `options` **{Object}**: See available [options](#options) for changing how matches are performed | ||
* `returns` **{Object}**: Returns an object with only keys that match the given patterns. | ||
**Example** | ||
`.isMatch()` would return false for both of the following: | ||
```js | ||
mm.contains('a/b/c', 'a/b'); | ||
//=> true | ||
var mm = require('micromatch'); | ||
mm.matchKeys(object, patterns[, options]); | ||
mm.contains('a/b/c', 'a/*'); | ||
//=> true | ||
var obj = { aa: 'a', ab: 'b', ac: 'c' }; | ||
console.log(mm.matchKeys(obj, '*b')); | ||
//=> { ab: 'b' } | ||
``` | ||
### .matcher | ||
### [.matcher](index.js#L474) | ||
Returns a function for matching using the supplied pattern. e.g. create your own "matcher". The advantage of this method is that the pattern can be compiled outside of a loop. | ||
Returns a memoized matcher function from the given glob `pattern` and `options`. The returned function takes a string to match as its only argument and returns true if the string is a match. | ||
**Pattern** | ||
**Params** | ||
Can be any of the following: | ||
* `pattern` **{String}**: Glob pattern | ||
* `options` **{Object}**: See available [options](#options) for changing how matches are performed. | ||
* `returns` **{Function}**: Returns a matcher function. | ||
* `glob/string` | ||
* `regex` | ||
* `function` | ||
**Example** | ||
```js | ||
var isMatch = mm.matcher('*.md'); | ||
var files = []; | ||
var mm = require('micromatch'); | ||
mm.matcher(pattern[, options]); | ||
['a.md', 'b.txt', 'c.md'].forEach(function(fp) { | ||
if (isMatch(fp)) { | ||
files.push(fp); | ||
} | ||
}); | ||
var isMatch = mm.matcher('*.!(*a)'); | ||
console.log(isMatch('a.a')); | ||
//=> false | ||
console.log(isMatch('a.b')); | ||
//=> true | ||
``` | ||
### .filter | ||
### [.makeRe](index.js#L542) | ||
Returns a function that can be passed to `Array#filter()`. | ||
Create a regular expression from the given glob `pattern`. | ||
**Params** | ||
* `patterns` **{String|Array}**: | ||
* `pattern` **{String}**: A glob pattern to convert to regex. | ||
* `options` **{Object}**: See available [options](#options) for changing how matches are performed. | ||
* `returns` **{RegExp}**: Returns a regex created from the given pattern. | ||
**Examples** | ||
**Example** | ||
Single glob: | ||
```js | ||
var fn = mm.filter('*.md'); | ||
['a.js', 'b.txt', 'c.md'].filter(fn); | ||
//=> ['c.md'] | ||
var mm = require('micromatch'); | ||
mm.makeRe(pattern[, options]); | ||
var fn = mm.filter('[a-c]'); | ||
['a', 'b', 'c', 'd', 'e'].filter(fn); | ||
//=> ['a', 'b', 'c'] | ||
console.log(mm.makeRe('*.js')); | ||
//=> /^(?:(\.[\\\/])?(?!\.)(?=.)[^\/]*?\.js)$/ | ||
``` | ||
Array of glob patterns: | ||
### [.braces](index.js#L585) | ||
Expand the given brace `pattern`. | ||
**Params** | ||
* `pattern` **{String}**: String with brace pattern to expand. | ||
* `options` **{Object}**: Any [options](#options) to change how expansion is performed. See the [braces](https://github.com/micromatch/braces) library for all available options. | ||
* `returns` **{Array}** | ||
**Example** | ||
```js | ||
var arr = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]; | ||
var mm = require('micromatch'); | ||
console.log(mm.braces('foo/{a,b}/bar')); | ||
//=> ['foo/(a|b)/bar'] | ||
var fn = mm.filter(['{1..10}', '![7-9]', '!{3..4}']); | ||
arr.filter(fn); | ||
//=> [1, 2, 5, 6, 10] | ||
console.log(mm.braces('foo/{a,b}/bar', {expand: true})); | ||
//=> ['foo/(a|b)/bar'] | ||
``` | ||
_(Internally this function generates the matching function by using the [matcher](#matcher) method. You can use the [matcher](#matcher) method directly to create your own filter function)_ | ||
### [.create](index.js#L649) | ||
### .any | ||
Parses the given glob `pattern` and returns an array of abstract syntax trees (ASTs), with the compiled `output` and optional source `map` on each AST. | ||
Returns true if a file path matches any of the given patterns. | ||
**Params** | ||
* `pattern` **{String}**: Glob pattern to parse and compile. | ||
* `options` **{Object}**: Any [options](#options) to change how parsing and compiling is performed. | ||
* `returns` **{Object}**: Returns an object with the parsed AST, compiled string and optional source map. | ||
**Example** | ||
```js | ||
mm.any(filepath, patterns, options); | ||
var mm = require('micromatch'); | ||
mm.create(pattern[, options]); | ||
console.log(mm.create('abc/*.js')); | ||
// [{ options: { source: 'string', sourcemap: true }, | ||
// state: {}, | ||
// compilers: | ||
// { ... }, | ||
// output: '(\\.[\\\\\\/])?abc\\/(?!\\.)(?=.)[^\\/]*?\\.js', | ||
// ast: | ||
// { type: 'root', | ||
// errors: [], | ||
// nodes: | ||
// [ ... ], | ||
// dot: false, | ||
// input: 'abc/*.js' }, | ||
// parsingErrors: [], | ||
// map: | ||
// { version: 3, | ||
// sources: [ 'string' ], | ||
// names: [], | ||
// mappings: 'AAAA,GAAG,EAAC,kBAAC,EAAC,EAAE', | ||
// sourcesContent: [ 'abc/*.js' ] }, | ||
// position: { line: 1, column: 28 }, | ||
// content: {}, | ||
// files: {}, | ||
// idx: 6 }] | ||
``` | ||
### [.parse](index.js#L696) | ||
Parse the given `str` with the given `options`. | ||
**Params** | ||
* filepath `{String}`: The file path to test. | ||
* patterns `{String|Array}`: One or more glob patterns | ||
* options: `{Object}`: options to pass to the `.matcher()` method. | ||
* `str` **{String}** | ||
* `options` **{Object}** | ||
* `returns` **{Object}**: Returns an AST | ||
@@ -294,51 +497,64 @@ **Example** | ||
```js | ||
mm.any('abc', ['!*z']); | ||
//=> true | ||
mm.any('abc', ['a*', 'z*']); | ||
//=> true | ||
mm.any('abc', 'a*'); | ||
//=> true | ||
mm.any('abc', ['z*']); | ||
//=> false | ||
var mm = require('micromatch'); | ||
mm.parse(pattern[, options]); | ||
var ast = mm.parse('a/{b,c}/d'); | ||
console.log(ast); | ||
// { type: 'root', | ||
// errors: [], | ||
// input: 'a/{b,c}/d', | ||
// nodes: | ||
// [ { type: 'bos', val: '' }, | ||
// { type: 'text', val: 'a/' }, | ||
// { type: 'brace', | ||
// nodes: | ||
// [ { type: 'brace.open', val: '{' }, | ||
// { type: 'text', val: 'b,c' }, | ||
// { type: 'brace.close', val: '}' } ] }, | ||
// { type: 'text', val: '/d' }, | ||
// { type: 'eos', val: '' } ] } | ||
``` | ||
### .expand | ||
### [.compile](index.js#L749) | ||
Returns an object with a regex-compatible string and tokens. | ||
Compile the given `ast` or string with the given `options`. | ||
**Params** | ||
* `ast` **{Object|String}** | ||
* `options` **{Object}** | ||
* `returns` **{Object}**: Returns an object that has an `output` property with the compiled string. | ||
**Example** | ||
```js | ||
mm.expand('*.js'); | ||
var mm = require('micromatch'); | ||
mm.compile(ast[, options]); | ||
// when `track` is enabled (for debugging), the `history` array is used | ||
// to record each mutation to the glob pattern as it's converted to regex | ||
{ options: { track: false, dot: undefined, makeRe: true, negated: false }, | ||
pattern: '(.*\\/|^)bar\\/(?:(?!(?:^|\\/)\\.).)*?', | ||
history: [], | ||
tokens: | ||
{ path: | ||
{ whole: '**/bar/**', | ||
dirname: '**/bar/', | ||
filename: '**', | ||
basename: '**', | ||
extname: '', | ||
ext: '' }, | ||
is: | ||
{ glob: true, | ||
negated: false, | ||
globstar: true, | ||
dotfile: false, | ||
dotdir: false }, | ||
match: {}, | ||
original: '**/bar/**', | ||
pattern: '**/bar/**', | ||
base: '' } } | ||
var ast = mm.parse('a/{b,c}/d'); | ||
console.log(mm.compile(ast)); | ||
// { options: { source: 'string' }, | ||
// state: {}, | ||
// compilers: | ||
// { eos: [Function], | ||
// noop: [Function], | ||
// bos: [Function], | ||
// brace: [Function], | ||
// 'brace.open': [Function], | ||
// text: [Function], | ||
// 'brace.close': [Function] }, | ||
// output: [ 'a/(b|c)/d' ], | ||
// ast: | ||
// { ... }, | ||
// parsingErrors: [] } | ||
``` | ||
### .makeRe | ||
### [.clearCache](index.js#L770) | ||
Create a regular expression for matching file paths based on the given pattern: | ||
Clear the regex cache. | ||
**Example** | ||
```js | ||
mm.makeRe('*.js'); | ||
//=> /^(?:(?!\.)(?=.)[^/]*?\.js)$/ | ||
mm.clearCache(); | ||
``` | ||
@@ -348,25 +564,46 @@ | ||
### options.unixify | ||
* [basename](#optionsbasename) | ||
* [bash](#optionsbash) | ||
* [cache](#optionscache) | ||
* [dot](#optionsdot) | ||
* [failglob](#optionsfailglob) | ||
* [ignore](#optionsignore) | ||
* [matchBase](#optionsmatchBase) | ||
* [nobrace](#optionsnobrace) | ||
* [nocase](#optionsnocase) | ||
* [nodupes](#optionsnodupes) | ||
* [noext](#optionsnoext) | ||
* [noglobstar](#optionsnoglobstar) | ||
* [nonull](#optionsnonull) | ||
* [nullglob](#optionsnullglob) | ||
* [snapdragon](#optionssnapdragon) | ||
* [sourcemap](#optionssourcemap) | ||
* [unescape](#optionsunescape) | ||
* [unixify](#optionsunixify) | ||
Normalize slashes in file paths and glob patterns to forward slashes. | ||
### options.basename | ||
Type: `{Boolean}` | ||
Allow glob patterns without slashes to match a file path based on its basename. Same behavior as [minimatch](https://github.com/isaacs/minimatch) option `matchBase`. | ||
Default: `undefined` on non-windows, `true` on windows. | ||
**Type**: `Boolean` | ||
### options.dot | ||
**Default**: `false` | ||
Match dotfiles. Same behavior as [minimatch](https://github.com/isaacs/minimatch). | ||
**Example** | ||
Type: `{Boolean}` | ||
```js | ||
mm(['a/b.js', 'a/c.md'], '*.js'); | ||
//=> [] | ||
Default: `false` | ||
mm(['a/b.js', 'a/c.md'], '*.js', {matchBase: true}); | ||
//=> ['a/b.js'] | ||
``` | ||
### options.unescape | ||
### options.bash | ||
Unescape slashes in glob patterns. Use cautiously, especially on windows. | ||
Enabled by default, this option enforces bash-like behavior with stars immediately following a bracket expression. Bash bracket expressions are similar to regex character classes, but unlike regex, a star following a bracket expression **does not repeat the bracketed characters**. Instead, the star is treated the same as an other star. | ||
Type: `{Boolean}` | ||
**Type**: `Boolean` | ||
Default: `undefined` | ||
**Default**: `true` | ||
@@ -376,6 +613,63 @@ **Example** | ||
```js | ||
mm.isMatch('abc', '\\a\\b\\c', {unescape: true}); | ||
//=> true | ||
var files = ['abc', 'ajz']; | ||
console.log(mm(files, '[a-c]*')); | ||
//=> ['abc', 'ajz'] | ||
console.log(mm(files, '[a-c]*', {bash: false})); | ||
``` | ||
### options.cache | ||
Disable regex and function memoization. | ||
**Type**: `Boolean` | ||
**Default**: `undefined` | ||
### options.dot | ||
Match dotfiles. Same behavior as [minimatch](https://github.com/isaacs/minimatch) option `dot`. | ||
**Type**: `Boolean` | ||
**Default**: `false` | ||
### options.failglob | ||
Similar to the `--failglob` behavior in Bash, throws an error when no matches are found. | ||
**Type**: `Boolean` | ||
**Default**: `undefined` | ||
### options.ignore | ||
String or array of glob patterns to match files to ignore. | ||
**Type**: `String|Array` | ||
**Default**: `undefined` | ||
### options.matchBase | ||
Alias for [options.basename](#options-basename). | ||
### options.nobrace | ||
Disable expansion of brace patterns. Same behavior as [minimatch](https://github.com/isaacs/minimatch) option `nobrace`. | ||
**Type**: `Boolean` | ||
**Default**: `undefined` | ||
See [braces](https://github.com/micromatch/braces) for more information about extended brace expansion. | ||
### options.nocase | ||
Use a case-insensitive regex for matching files. Same behavior as [minimatch](https://github.com/isaacs/minimatch). | ||
**Type**: `Boolean` | ||
**Default**: `undefined` | ||
### options.nodupes | ||
@@ -385,5 +679,5 @@ | ||
Type: `{Boolean}` | ||
**Type**: `Boolean` | ||
Default: `undefined` | ||
**Default**: `undefined` | ||
@@ -395,99 +689,154 @@ **Example** | ||
```js | ||
mm.match(['abc', '\\a\\b\\c'], '\\a\\b\\c', {unescape: true}); | ||
//=> ['abc', 'abc'] | ||
mm.match(['a/b/c', 'a/b/c'], 'a/b/c'); | ||
//=> ['a/b/c', 'a/b/c'] | ||
mm.match(['abc', '\\a\\b\\c'], '\\a\\b\\c', {unescape: true, nodupes: true}); | ||
mm.match(['a/b/c', 'a/b/c'], 'a/b/c', {nodupes: true}); | ||
//=> ['abc'] | ||
``` | ||
### options.matchBase | ||
### options.noext | ||
Allow glob patterns without slashes to match a file path based on its basename. . Same behavior as [minimatch](https://github.com/isaacs/minimatch). | ||
Disable extglob support, so that extglobs are regarded as literal characters. | ||
Type: `{Boolean}` | ||
**Type**: `Boolean` | ||
Default: `false` | ||
**Default**: `undefined` | ||
**Example** | ||
**Examples** | ||
```js | ||
mm(['a/b.js', 'a/c.md'], '*.js'); | ||
//=> [] | ||
mm(['a/z', 'a/b', 'a/!(z)'], 'a/!(z)'); | ||
//=> ['a/b', 'a/!(z)'] | ||
mm(['a/b.js', 'a/c.md'], '*.js', {matchBase: true}); | ||
//=> ['a/b.js'] | ||
mm(['a/z', 'a/b', 'a/!(z)'], 'a/!(z)', {noext: true}); | ||
//=> ['a/!(z)'] (matches only as literal characters) | ||
``` | ||
### options.nobraces | ||
### options.nonegate | ||
Don't expand braces in glob patterns. Same behavior as [minimatch](https://github.com/isaacs/minimatch) `nobrace`. | ||
Disallow negation (`!`) patterns, and treat leading `!` as a literal character to match. | ||
Type: `{Boolean}` | ||
**Type**: `Boolean` | ||
Default: `undefined` | ||
**Default**: `undefined` | ||
See [braces](https://github.com/jonschlinkert/braces) for more information about extended brace expansion. | ||
### options.noglobstar | ||
### options.nobrackets | ||
Disable matching with globstars (`**`). | ||
Don't expand POSIX bracket expressions. | ||
**Type**: `Boolean` | ||
Type: `{Boolean}` | ||
**Default**: `undefined` | ||
Default: `undefined` | ||
```js | ||
mm(['a/b', 'a/b/c', 'a/b/c/d'], 'a/**'); | ||
//=> ['a/b', 'a/b/c', 'a/b/c/d'] | ||
See [expand-brackets](https://github.com/jonschlinkert/expand-brackets) for more information about extended bracket expressions. | ||
mm(['a/b', 'a/b/c', 'a/b/c/d'], 'a/**', {noglobstar: true}); | ||
//=> ['a/b'] | ||
``` | ||
### options.noextglob | ||
### options.nonull | ||
Don't expand extended globs. | ||
Alias for [options.nullglob](#options-nullglob). | ||
Type: `{Boolean}` | ||
### options.nullglob | ||
Default: `undefined` | ||
If `true`, when no matches are found the actual (arrayified) glob pattern is returned instead of an empty array. Same behavior as [minimatch](https://github.com/isaacs/minimatch) option `nonull`. | ||
See [extglob](https://github.com/jonschlinkert/extglob) for more information about extended globs. | ||
**Type**: `Boolean` | ||
### options.nocase | ||
**Default**: `undefined` | ||
Use a case-insensitive regex for matching files. Same behavior as [minimatch](https://github.com/isaacs/minimatch). | ||
### options.snapdragon | ||
Type: `{Boolean}` | ||
Pass your own instance of [snapdragon](https://github.com/jonschlinkert/snapdragon), to customize parsers or compilers. | ||
Default: `false` | ||
**Type**: `Object` | ||
### options.nonegate | ||
**Default**: `undefined` | ||
Disallow negation (`!`) patterns. | ||
### options.sourcemap | ||
Type: `{Boolean}` | ||
Generate a source map by enabling the `sourcemap` option with the `.parse`, `.compile`, or `.create` methods. | ||
Default: `false` | ||
_(Note that sourcemaps are currently not enabled for brace patterns)_ | ||
### options.nonull | ||
**Examples** | ||
If `true`, when no matches are found the actual (array-ified) glob pattern is returned instead of an empty array. Same behavior as [minimatch](https://github.com/isaacs/minimatch). | ||
``` js | ||
var mm = require('micromatch'); | ||
var pattern = '*(*(of*(a)x)z)'; | ||
Type: `{Boolean}` | ||
var res = mm.create('abc/*.js', {sourcemap: true}); | ||
console.log(res.map); | ||
// { version: 3, | ||
// sources: [ 'string' ], | ||
// names: [], | ||
// mappings: 'AAAA,GAAG,EAAC,iBAAC,EAAC,EAAE', | ||
// sourcesContent: [ 'abc/*.js' ] } | ||
Default: `false` | ||
var ast = mm.parse('abc/**/*.js'); | ||
var res = mm.compile(ast, {sourcemap: true}); | ||
console.log(res.map); | ||
// { version: 3, | ||
// sources: [ 'string' ], | ||
// names: [], | ||
// mappings: 'AAAA,GAAG,EAAC,2BAAE,EAAC,iBAAC,EAAC,EAAE', | ||
// sourcesContent: [ 'abc/**/*.js' ] } | ||
### options.cache | ||
var ast = mm.parse(pattern); | ||
var res = mm.compile(ast, {sourcemap: true}); | ||
console.log(res.map); | ||
// { version: 3, | ||
// sources: [ 'string' ], | ||
// names: [], | ||
// mappings: 'AAAA,CAAE,CAAE,EAAE,CAAE,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC', | ||
// sourcesContent: [ '*(*(of*(a)x)z)' ] } | ||
``` | ||
Cache the platform (e.g. `win32`) to prevent this from being looked up for every filepath. | ||
### options.unescape | ||
Type: `{Boolean}` | ||
Remove backslashes from returned matches. | ||
Default: `true` | ||
**Type**: `Boolean` | ||
*** | ||
**Default**: `undefined` | ||
## Other features | ||
**Example** | ||
Micromatch also supports the following. | ||
In this example we want to match a literal `*`: | ||
### Extended globbing | ||
```js | ||
mm.match(['abc', 'a\\*c'], 'a\\*c'); | ||
//=> ['a\\*c'] | ||
#### extglobs | ||
mm.match(['abc', 'a\\*c'], 'a\\*c', {unescape: true}); | ||
//=> ['a*c'] | ||
``` | ||
### options.unixify | ||
Convert path separators on returned files to posix/unix-style forward slashes. | ||
**Type**: `Boolean` | ||
**Default**: `true` on windows, `false` everywhere else | ||
**Example** | ||
```js | ||
mm.match(['a\\b\\c'], 'a/**'); | ||
//=> ['a/b/c'] | ||
mm.match(['a\\b\\c'], {unixify: false}); | ||
//=> ['a\\b\\c'] | ||
``` | ||
## Extended globbing | ||
Micromatch also supports extended globbing features. | ||
### extglobs | ||
Extended globbing, as described by the bash man page: | ||
@@ -497,31 +846,31 @@ | ||
| --- | --- | --- | | ||
| `?(pattern-list)` | `(... | ...)?` | Matches zero or one occurrence of the given patterns | | ||
| `*(pattern-list)` | `(... | ...)*` | Matches zero or more occurrences of the given patterns | | ||
| `+(pattern-list)` | `(... | ...)+` | Matches one or more occurrences of the given patterns | | ||
| `@(pattern-list)` | `(... | ...)` <sup>*</sup> | Matches one of the given patterns | | ||
| `!(pattern-list)` | N/A | Matches anything except one of the given patterns | | ||
| `?(pattern)` | `(pattern)?` | Matches zero or one occurrence of the given patterns | | ||
| `*(pattern)` | `(pattern)*` | Matches zero or more occurrences of the given patterns | | ||
| `+(pattern)` | `(pattern)+` | Matches one or more occurrences of the given patterns | | ||
| `@(pattern)` | `(pattern)` <sup>*</sup> | Matches one of the given patterns | | ||
| `!(pattern)` | N/A (equivalent regex is much more complicated) | Matches anything except one of the given patterns | | ||
<sup><strong>*</strong></sup> `@` isn't a RegEx character. | ||
<sup><strong>*</strong></sup> Note that `@` isn't a RegEx character. | ||
Powered by [extglob](https://github.com/jonschlinkert/extglob). Visit that library for the full range of options or to report extglob related issues. | ||
See [extglob](https://github.com/jonschlinkert/extglob) for more information about extended globs. | ||
### braces | ||
#### brace expansion | ||
Brace patterns can be used to match specific ranges or sets of characters. For example, the pattern `*/{1..3}/*` would match any of following strings: | ||
In simple cases, brace expansion appears to work the same way as the logical `OR` operator. For example, `(a|b)` will achieve the same result as `{a,b}`. | ||
``` | ||
foo/1/bar | ||
foo/2/bar | ||
foo/3/bar | ||
baz/1/qux | ||
baz/2/qux | ||
baz/3/qux | ||
``` | ||
Here are some powerful features unique to brace expansion (versus character classes): | ||
Visit [braces](https://github.com/micromatch/braces) to see the full range of features and options related to brace expansion, or to create brace matching or expansion related issues. | ||
* range expansion: `a{1..3}b/*.js` expands to: `['a1b/*.js', 'a2b/*.js', 'a3b/*.js']` | ||
* nesting: `a{c,{d,e}}b/*.js` expands to: `['acb/*.js', 'adb/*.js', 'aeb/*.js']` | ||
### regex character classes | ||
Visit [braces](https://github.com/jonschlinkert/braces) to ask questions and create an issue related to brace-expansion, or to see the full range of features and options related to brace expansion. | ||
Given the list: `['a.js', 'b.js', 'c.js', 'd.js', 'E.js']`: | ||
#### regex character classes | ||
With the exception of brace expansion (`{a,b}`, `{1..5}`, etc), most of the special characters convert directly to regex, so you can expect them to follow the same rules and produce the same results as regex. | ||
For example, given the list: `['a.js', 'b.js', 'c.js', 'd.js', 'E.js']`: | ||
* `[ac].js`: matches both `a` and `c`, returning `['a.js', 'c.js']` | ||
@@ -534,3 +883,3 @@ * `[b-d].js`: matches from `b` to `d`, returning `['b.js', 'c.js', 'd.js']` | ||
#### regex groups | ||
### regex groups | ||
@@ -543,6 +892,8 @@ Given `['a.js', 'b.js', 'c.js', 'd.js', 'E.js']`: | ||
As with regex, parenthese can be nested, so patterns like `((a|b)|c)/b` will work. But it might be easier to achieve your goal using brace expansion. | ||
As with regex, parens can be nested, so patterns like `((a|b)|c)/b` will work. Although brace expansion might be friendlier to use, depending on preference. | ||
#### POSIX bracket expressions | ||
### POSIX bracket expressions | ||
POSIX brackets are intended to be more user-friendly than regex character classes. This of course is in the eye of the beholder. | ||
**Example** | ||
@@ -553,5 +904,8 @@ | ||
//=> true | ||
mm.isMatch('a1', '[[:alpha:][:alpha:]]'); | ||
//=> false | ||
``` | ||
See [expand-brackets](https://github.com/jonschlinkert/expand-brackets) for more information about extended bracket expressions. | ||
See [expand-brackets](https://github.com/jonschlinkert/expand-brackets) for more information about bracket expressions. | ||
@@ -562,129 +916,161 @@ *** | ||
Whenever possible parsing behavior for patterns is based on globbing specifications in Bash 4.3. Patterns that aren't described by Bash follow wildmatch spec (used by git). | ||
### Bash 4.3 parity | ||
## Benchmarks | ||
Whenever possible matching behavior is based on behavior Bash 4.3, which is mostly consistent with minimatch. | ||
Run the [benchmarks](./benchmark): | ||
However, it's suprising how many edge cases and rabbit holes there are with glob matching, and since there is no real glob specification, and micromatch is more accurate than both Bash and minimatch, there are cases where best-guesses were made for behavior. In a few cases where Bash had no answers, we used wildmatch (used by git) as a fallback. | ||
```bash | ||
node benchmark | ||
``` | ||
### Backslashes | ||
As of July 15, 2016: | ||
There is an important, notable difference between minimatch and micromatch _in regards to how backslashes are handled_ in glob patterns. | ||
```bash | ||
#1: basename-braces | ||
micromatch x 26,420 ops/sec ±0.89% (91 runs sampled) | ||
minimatch x 3,507 ops/sec ±0.64% (97 runs sampled) | ||
* Micromatch exclusively and explicitly reserves backslashes for escaping characters in a glob pattern, even on windows. This is consistent with bash behavior. | ||
* Minimatch converts all backslashes to forward slashes, which means you can't use backslashes to escape any characters in your glob patterns. | ||
#2: basename | ||
micromatch x 25,315 ops/sec ±0.82% (93 runs sampled) | ||
minimatch x 4,398 ops/sec ±0.86% (94 runs sampled) | ||
We made this decision for micromatch for a couple of reasons: | ||
#3: braces-no-glob | ||
micromatch x 341,254 ops/sec ±0.78% (93 runs sampled) | ||
minimatch x 30,197 ops/sec ±1.12% (91 runs sampled) | ||
* consistency with bash conventions. | ||
* glob patterns are not filepaths. They are a type of [regular language](https://en.wikipedia.org/wiki/Regular_language) that is converted to a JavaScript regular expression. Thus, when forward slashes are defined in a glob pattern, the resulting regular expression will match windows or POSIX path separators just fine. | ||
#4: braces | ||
micromatch x 54,649 ops/sec ±0.74% (94 runs sampled) | ||
minimatch x 3,095 ops/sec ±0.82% (95 runs sampled) | ||
**A note about joining paths to globs** | ||
#5: immediate | ||
micromatch x 16,719 ops/sec ±0.79% (95 runs sampled) | ||
minimatch x 4,348 ops/sec ±0.86% (96 runs sampled) | ||
Note that when you pass something like `path.join('foo', '*')` to micromatch, you are creating a filepath and expecting it to still work as a glob pattern. This causes problems on windows, since the `path.sep` is `\\`. | ||
#6: large | ||
micromatch x 721 ops/sec ±0.77% (94 runs sampled) | ||
minimatch x 17.73 ops/sec ±1.08% (50 runs sampled) | ||
In other words, since `\\` is reserved as an escape character in globs, on windows `path.join('foo', '*')` would result in `foo\\*`, which tells micromatch to match `*` as a literal character. This is the same behavior as bash. | ||
#7: long | ||
micromatch x 5,051 ops/sec ±0.87% (97 runs sampled) | ||
minimatch x 628 ops/sec ±0.83% (94 runs sampled) | ||
## Contributing | ||
#8: mid | ||
micromatch x 51,280 ops/sec ±0.80% (95 runs sampled) | ||
minimatch x 1,923 ops/sec ±0.84% (95 runs sampled) | ||
All contributions are welcome! Please read [the contributing guide](.github/contributing.md) to get started. | ||
#9: multi-patterns | ||
micromatch x 22,440 ops/sec ±0.97% (94 runs sampled) | ||
minimatch x 2,481 ops/sec ±1.10% (94 runs sampled) | ||
**Bug reports** | ||
#10: no-glob | ||
micromatch x 722,823 ops/sec ±1.30% (87 runs sampled) | ||
minimatch x 52,967 ops/sec ±1.09% (94 runs sampled) | ||
Please create an issue if you encounter a bug or matching behavior that doesn't seem correct. If you find a matching-related issue, please: | ||
#11: range | ||
micromatch x 243,471 ops/sec ±0.79% (94 runs sampled) | ||
minimatch x 11,736 ops/sec ±0.82% (96 runs sampled) | ||
* [research existing issues first](../../issues) (open and closed) | ||
* visit the [GNU Bash documentation](https://www.gnu.org/software/bash/manual/) to see how Bash deals with the pattern | ||
* visit the [minimatch](https://github.com/isaacs/minimatch) documentation to cross-check expected behavior in node.js | ||
* if all else fails, since there is no real specification for globs we will probably need to discuss expected behavior and decide how to resolve it. which means any detail you can provide to help with this discussion would be greatly appreciated. | ||
#12: shallow | ||
micromatch x 190,874 ops/sec ±0.98% (95 runs sampled) | ||
minimatch x 21,699 ops/sec ±0.81% (97 runs sampled) | ||
**Platform issues** | ||
#13: short | ||
micromatch x 496,393 ops/sec ±3.86% (90 runs sampled) | ||
minimatch x 53,765 ops/sec ±0.75% (95 runs sampled) | ||
``` | ||
It's important to us that micromatch work consistently on all platforms. If you encounter any platform-specific matching or path related issues, please let us know (pull requests are also greatly appreciated). | ||
## Tests | ||
## Benchmarks | ||
### Running tests | ||
### Running benchmarks | ||
Install dev dependencies: | ||
```sh | ||
$ npm install -d && npm test | ||
```bash | ||
npm i -d && npm run benchmark | ||
``` | ||
### Coverage | ||
### Latest results | ||
As of July 15, 2016: | ||
As of May 29, 2017 (longer bars are better): | ||
```sh | ||
Statements : 100% (441/441) | ||
Branches : 100% (270/270) | ||
Functions : 100% (54/54) | ||
Lines : 100% (429/429) | ||
``` | ||
# braces-globstar-large-list | ||
micromatch ██████████████████████████████████████████████████████████████████████ (595 ops/sec) | ||
minimatch █ (13.95 ops/sec) | ||
multimatch █ (14.09 ops/sec) | ||
## Contributing | ||
# braces-multiple | ||
micromatch ██████████████████████████████████████████████████████████████████████ (48,362 ops/sec) | ||
minimatch (2.18 ops/sec) | ||
multimatch (2.15 ops/sec) | ||
Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](../../issues/new). | ||
# braces-range | ||
micromatch ██████████████████████████████████████████████████████████████████████ (187,481 ops/sec) | ||
minimatch ████ (12,366 ops/sec) | ||
multimatch ████ (11,841 ops/sec) | ||
Please be sure to run the benchmarks before/after any code changes to judge the impact before you do a PR. thanks! | ||
# braces-set | ||
micromatch ██████████████████████████████████████████████████████████████████████ (24,344 ops/sec) | ||
minimatch ██████ (2,255 ops/sec) | ||
multimatch ██████ (2,199 ops/sec) | ||
## Related | ||
# globstar-large-list | ||
micromatch ██████████████████████████████████████████████████████████████████████ (561 ops/sec) | ||
minimatch ███ (25.43 ops/sec) | ||
multimatch ███ (25.27 ops/sec) | ||
* [braces](https://www.npmjs.com/package/braces): Fastest brace expansion for node.js, with the most complete support for the Bash 4.3 braces… [more](https://github.com/jonschlinkert/braces) | [homepage](https://github.com/jonschlinkert/braces "Fastest brace expansion for node.js, with the most complete support for the Bash 4.3 braces specification.") | ||
# globstar-long-list | ||
micromatch ██████████████████████████████████████████████████████████████████████ (3,257 ops/sec) | ||
minimatch ██████████ (485 ops/sec) | ||
multimatch ██████████ (485 ops/sec) | ||
# globstar-short-list | ||
micromatch ██████████████████████████████████████████████████████████████████████ (359,991 ops/sec) | ||
minimatch ████████ (44,763 ops/sec) | ||
multimatch ███████ (39,977 ops/sec) | ||
# no-glob | ||
micromatch ██████████████████████████████████████████████████████████████████████ (443,740 ops/sec) | ||
minimatch ██████ (44,152 ops/sec) | ||
multimatch ██████ (41,077 ops/sec) | ||
# star-basename | ||
micromatch ██████████████████████████████████████████████████████████████████████ (10,286 ops/sec) | ||
minimatch ████████████████████ (3,059 ops/sec) | ||
multimatch █████████████████████ (3,129 ops/sec) | ||
# star | ||
micromatch ██████████████████████████████████████████████████████████████████████ (9,756 ops/sec) | ||
minimatch █████████████████████ (2,978 ops/sec) | ||
multimatch █████████████████████ (2,970 ops/sec) | ||
``` | ||
## About | ||
### Related projects | ||
* [braces](https://www.npmjs.com/package/braces): Bash-like brace expansion, implemented in JavaScript. Safer than other brace expansion libs, with complete support… [more](https://github.com/micromatch/braces) | [homepage](https://github.com/micromatch/braces "Bash-like brace expansion, implemented in JavaScript. Safer than other brace expansion libs, with complete support for the Bash 4.3 braces specification, without sacrificing speed.") | ||
* [expand-brackets](https://www.npmjs.com/package/expand-brackets): Expand POSIX bracket expressions (character classes) in glob patterns. | [homepage](https://github.com/jonschlinkert/expand-brackets "Expand POSIX bracket expressions (character classes) in glob patterns.") | ||
* [expand-range](https://www.npmjs.com/package/expand-range): Fast, bash-like range expansion. Expand a range of numbers or letters, uppercase or lowercase. See… [more](https://github.com/jonschlinkert/expand-range) | [homepage](https://github.com/jonschlinkert/expand-range "Fast, bash-like range expansion. Expand a range of numbers or letters, uppercase or lowercase. See the benchmarks. Used by micromatch.") | ||
* [extglob](https://www.npmjs.com/package/extglob): Convert extended globs to regex-compatible strings. Add (almost) the expressive power of regular expressions to… [more](https://github.com/jonschlinkert/extglob) | [homepage](https://github.com/jonschlinkert/extglob "Convert extended globs to regex-compatible strings. Add (almost) the expressive power of regular expressions to glob patterns.") | ||
* [fill-range](https://www.npmjs.com/package/fill-range): Fill in a range of numbers or letters, optionally passing an increment or multiplier to… [more](https://github.com/jonschlinkert/fill-range) | [homepage](https://github.com/jonschlinkert/fill-range "Fill in a range of numbers or letters, optionally passing an increment or multiplier to use.") | ||
* [gulp-micromatch](https://www.npmjs.com/package/gulp-micromatch): Filter vinyl files with glob patterns, string, regexp, array, object or matcher function. micromatch stream. | [homepage](https://github.com/tunnckocore/gulp-micromatch#readme "Filter vinyl files with glob patterns, string, regexp, array, object or matcher function. micromatch stream.") | ||
* [is-glob](https://www.npmjs.com/package/is-glob): Returns `true` if the given string looks like a glob pattern or an extglob pattern… [more](https://github.com/jonschlinkert/is-glob) | [homepage](https://github.com/jonschlinkert/is-glob "Returns `true` if the given string looks like a glob pattern or an extglob pattern. This makes it easy to create code that only uses external modules like node-glob when necessary, resulting in much faster code execution and initialization time, and a bet") | ||
* [parse-glob](https://www.npmjs.com/package/parse-glob): Parse a glob pattern into an object of tokens. | [homepage](https://github.com/jonschlinkert/parse-glob "Parse a glob pattern into an object of tokens.") | ||
* [extglob](https://www.npmjs.com/package/extglob): Extended glob support for JavaScript. Adds (almost) the expressive power of regular expressions to glob… [more](https://github.com/jonschlinkert/extglob) | [homepage](https://github.com/jonschlinkert/extglob "Extended glob support for JavaScript. Adds (almost) the expressive power of regular expressions to glob patterns.") | ||
* [fill-range](https://www.npmjs.com/package/fill-range): Fill in a range of numbers or letters, optionally passing an increment or `step` to… [more](https://github.com/jonschlinkert/fill-range) | [homepage](https://github.com/jonschlinkert/fill-range "Fill in a range of numbers or letters, optionally passing an increment or `step` to use, or create a regex-compatible range with `options.toRegex`") | ||
* [nanomatch](https://www.npmjs.com/package/nanomatch): Fast, minimal glob matcher for node.js. Similar to micromatch, minimatch and multimatch, but complete Bash… [more](https://github.com/jonschlinkert/nanomatch) | [homepage](https://github.com/jonschlinkert/nanomatch "Fast, minimal glob matcher for node.js. Similar to micromatch, minimatch and multimatch, but complete Bash 4.3 wildcard support only (no support for exglobs, posix brackets or braces)") | ||
## Contributing | ||
### Contributing | ||
Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](../../issues/new). | ||
## Building docs | ||
Please read the [contributing guide](.github/contributing.md) for advice on opening issues, pull requests, and coding standards. | ||
_(This document was generated by [verb-generate-readme](https://github.com/verbose/verb-generate-readme) (a [verb](https://github.com/verbose/verb) generator), please don't edit the readme directly. Any changes to the readme must be made in [.verb.md](.verb.md).)_ | ||
### Contributors | ||
To generate the readme and API documentation with [verb](https://github.com/verbose/verb): | ||
| **Commits** | **Contributor** | | ||
| --- | --- | | ||
| 346 | [jonschlinkert](https://github.com/jonschlinkert) | | ||
| 12 | [es128](https://github.com/es128) | | ||
| 3 | [paulmillr](https://github.com/paulmillr) | | ||
| 2 | [TrySound](https://github.com/TrySound) | | ||
| 2 | [doowb](https://github.com/doowb) | | ||
| 2 | [MartinKolarik](https://github.com/MartinKolarik) | | ||
| 2 | [tunnckoCore](https://github.com/tunnckoCore) | | ||
| 1 | [amilajack](https://github.com/amilajack) | | ||
| 1 | [DianeLooney](https://github.com/DianeLooney) | | ||
| 1 | [UltCombo](https://github.com/UltCombo) | | ||
| 1 | [tomByrer](https://github.com/tomByrer) | | ||
### Building docs | ||
_(This project's readme.md is generated by [verb](https://github.com/verbose/verb-generate-readme), please don't edit the readme directly. Any changes to the readme must be made in the [.verb.md](.verb.md) readme template.)_ | ||
To generate the readme, run the following command: | ||
```sh | ||
$ npm install -g verb verb-generate-readme && verb | ||
$ npm install -g verbose/verb#dev verb-generate-readme && verb | ||
``` | ||
## Running tests | ||
### Running tests | ||
Install dev dependencies: | ||
Running and reviewing unit tests is a great way to get familiarized with a library and its API. You can install dependencies and run tests with the following command: | ||
```sh | ||
$ npm install -d && npm test | ||
$ npm install && npm test | ||
``` | ||
## Author | ||
### Author | ||
@@ -694,11 +1080,11 @@ **Jon Schlinkert** | ||
* [github/jonschlinkert](https://github.com/jonschlinkert) | ||
* [twitter/jonschlinkert](http://twitter.com/jonschlinkert) | ||
* [twitter/jonschlinkert](https://twitter.com/jonschlinkert) | ||
## License | ||
### License | ||
Copyright © 2016, [Jon Schlinkert](https://github.com/jonschlinkert). | ||
Released under the [MIT license](https://github.com/jonschlinkert/micromatch/blob/master/LICENSE). | ||
Copyright © 2017, [Jon Schlinkert](https://github.com/jonschlinkert). | ||
Released under the [MIT License](LICENSE). | ||
*** | ||
_This file was generated by [verb](https://github.com/verbose/verb), v0.9.0, on July 15, 2016._ | ||
_This file was generated by [verb-generate-readme](https://github.com/verbose/verb-generate-readme), v0.6.0, on May 29, 2017._ |
Sorry, the diff of this file is not supported yet
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
Major refactor
Supply chain riskPackage has recently undergone a major refactor. It may be unstable or indicate significant internal changes. Use caution when updating to versions that include significant changes.
Found 1 instance in 1 package
No repository
Supply chain riskPackage does not have a linked source code repository. Without this field, a package will have no reference to the location of the source code use to generate the package.
Found 1 instance in 1 package
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
No repository
Supply chain riskPackage does not have a linked source code repository. Without this field, a package will have no reference to the location of the source code use to generate the package.
Found 1 instance in 1 package
74913
12
9
1138
1075
1
+ Addeddefine-property@^0.2.5
+ Addedextend-shallow@^2.0.1
+ Addedfragment-cache@^0.2.1
+ Addednanomatch@^1.1.1
+ Addedobject.pick@^1.2.0
+ Addedregex-not@^1.0.0
+ Addedsnapdragon@^0.8.1
+ Addedto-regex@^3.0.1
+ Addedarr-diff@3.0.04.0.0(transitive)
+ Addedarr-union@3.1.0(transitive)
+ Addedarray-unique@0.3.2(transitive)
+ Addedassign-symbols@1.0.0(transitive)
+ Addedatob@2.1.2(transitive)
+ Addedbase@0.11.2(transitive)
+ Addedbraces@2.3.2(transitive)
+ Addedcache-base@1.0.1(transitive)
+ Addedclass-utils@0.3.6(transitive)
+ Addedcollection-visit@1.0.0(transitive)
+ Addedcomponent-emitter@1.3.1(transitive)
+ Addedcopy-descriptor@0.1.1(transitive)
+ Addeddebug@2.6.9(transitive)
+ Addeddecode-uri-component@0.2.2(transitive)
+ Addeddefine-property@0.2.51.0.02.0.2(transitive)
+ Addedexpand-brackets@2.1.4(transitive)
+ Addedextend-shallow@2.0.13.0.2(transitive)
+ Addedextglob@1.1.0(transitive)
+ Addedfill-range@4.0.0(transitive)
+ Addedfragment-cache@0.2.1(transitive)
+ Addedfunction-bind@1.1.2(transitive)
+ Addedget-value@2.0.6(transitive)
+ Addedhas-value@0.3.11.0.0(transitive)
+ Addedhas-values@0.1.41.0.0(transitive)
+ Addedhasown@2.0.2(transitive)
+ Addedis-accessor-descriptor@1.0.1(transitive)
+ Addedis-data-descriptor@1.0.1(transitive)
+ Addedis-descriptor@0.1.71.0.3(transitive)
+ Addedis-extendable@1.0.1(transitive)
+ Addedis-number@3.0.0(transitive)
+ Addedis-plain-object@2.0.4(transitive)
+ Addedis-windows@1.0.2(transitive)
+ Addedisobject@3.0.1(transitive)
+ Addedkind-of@4.0.0(transitive)
+ Addedmap-cache@0.2.2(transitive)
+ Addedmap-visit@1.0.0(transitive)
+ Addedmixin-deep@1.3.2(transitive)
+ Addedms@2.0.0(transitive)
+ Addednanomatch@1.2.13(transitive)
+ Addedobject-copy@0.1.0(transitive)
+ Addedobject-visit@1.0.1(transitive)
+ Addedobject.pick@1.3.0(transitive)
+ Addedpascalcase@0.1.1(transitive)
+ Addedposix-character-classes@0.1.1(transitive)
+ Addedregex-not@0.1.21.0.2(transitive)
+ Addedresolve-url@0.2.1(transitive)
+ Addedret@0.1.15(transitive)
+ Addedsafe-regex@1.1.0(transitive)
+ Addedset-value@2.0.1(transitive)
+ Addedsnapdragon@0.8.2(transitive)
+ Addedsnapdragon-node@2.1.1(transitive)
+ Addedsnapdragon-util@3.0.1(transitive)
+ Addedsource-map@0.5.7(transitive)
+ Addedsource-map-resolve@0.5.3(transitive)
+ Addedsource-map-url@0.4.1(transitive)
+ Addedsplit-string@3.1.0(transitive)
+ Addedstatic-extend@0.1.2(transitive)
+ Addedto-object-path@0.3.0(transitive)
+ Addedto-regex@2.1.03.0.2(transitive)
+ Addedto-regex-range@2.1.1(transitive)
+ Addedunion-value@1.0.1(transitive)
+ Addedunset-value@1.0.0(transitive)
+ Addedurix@0.1.0(transitive)
+ Addeduse@3.1.1(transitive)
- Removedexpand-brackets@^0.1.4
- Removedfilename-regex@^2.0.0
- Removedis-extglob@^1.0.0
- Removedis-glob@^2.0.1
- Removednormalize-path@^2.0.1
- Removedobject.omit@^2.0.0
- Removedparse-glob@^3.0.4
- Removedregex-cache@^0.4.2
- Removedarr-diff@2.0.0(transitive)
- Removedarray-unique@0.2.1(transitive)
- Removedbraces@1.8.5(transitive)
- Removedexpand-brackets@0.1.5(transitive)
- Removedexpand-range@1.8.2(transitive)
- Removedextglob@0.3.2(transitive)
- Removedfilename-regex@2.0.1(transitive)
- Removedfill-range@2.2.4(transitive)
- Removedfor-own@0.1.5(transitive)
- Removedglob-base@0.3.0(transitive)
- Removedglob-parent@2.0.0(transitive)
- Removedis-dotfile@1.0.3(transitive)
- Removedis-equal-shallow@0.1.3(transitive)
- Removedis-extglob@1.0.0(transitive)
- Removedis-glob@2.0.1(transitive)
- Removedis-number@2.1.04.0.0(transitive)
- Removedis-posix-bracket@0.1.1(transitive)
- Removedis-primitive@2.0.0(transitive)
- Removedmath-random@1.0.4(transitive)
- Removednormalize-path@2.1.1(transitive)
- Removedobject.omit@2.0.1(transitive)
- Removedparse-glob@3.0.4(transitive)
- Removedpreserve@0.2.0(transitive)
- Removedrandomatic@3.1.1(transitive)
- Removedregex-cache@0.4.4(transitive)
- Removedremove-trailing-separator@1.1.0(transitive)
Updatedarr-diff@^3.0.0
Updatedarray-unique@^0.3.2
Updatedbraces@^2.0.3
Updatedextglob@^1.1.0
Updatedkind-of@^3.1.0