7 var util = require('util');
8 var toRegex = require('to-regex');
9 var extend = require('extend-shallow');
15 var compilers = require('./lib/compilers');
16 var parsers = require('./lib/parsers');
17 var cache = require('./lib/cache');
18 var utils = require('./lib/utils');
19 var MAX_LENGTH = 1024 * 64;
22 * The main function takes a list of strings and one or more
23 * glob patterns to use for matching.
26 * var nm = require('nanomatch');
27 * nm(list, patterns[, options]);
29 * console.log(nm(['a.js', 'a.txt'], ['*.js']));
32 * @param {Array} `list` A list of strings to match
33 * @param {String|Array} `patterns` One or more glob patterns to use for matching.
34 * @param {Object} `options` See available [options](#options) for changing how matches are performed
35 * @return {Array} Returns an array of matches
40 function nanomatch(list, patterns, options) {
41 patterns = utils.arrayify(patterns);
42 list = utils.arrayify(list);
44 var len = patterns.length;
45 if (list.length === 0 || len === 0) {
50 return nanomatch.match(list, patterns[0], options);
59 var pattern = patterns[idx];
61 if (typeof pattern === 'string' && pattern.charCodeAt(0) === 33 /* ! */) {
62 omit.push.apply(omit, nanomatch.match(list, pattern.slice(1), options));
65 keep.push.apply(keep, nanomatch.match(list, pattern, options));
69 // minimatch.match parity
70 if (negated && keep.length === 0) {
71 if (options && options.unixify === false) {
74 var unixify = utils.unixify(options);
75 for (var i = 0; i < list.length; i++) {
76 keep.push(unixify(list[i]));
81 var matches = utils.diff(keep, omit);
82 if (!options || options.nodupes !== false) {
83 return utils.unique(matches);
90 * Similar to the main function, but `pattern` must be a string.
93 * var nm = require('nanomatch');
94 * nm.match(list, pattern[, options]);
96 * console.log(nm.match(['a.a', 'a.aa', 'a.b', 'a.c'], '*.a'));
97 * //=> ['a.a', 'a.aa']
99 * @param {Array} `list` Array of strings to match
100 * @param {String} `pattern` Glob pattern to use for matching.
101 * @param {Object} `options` See available [options](#options) for changing how matches are performed
102 * @return {Array} Returns an array of matches
106 nanomatch.match = function(list, pattern, options) {
107 if (Array.isArray(pattern)) {
108 throw new TypeError('expected pattern to be a string');
111 var unixify = utils.unixify(options);
112 var isMatch = memoize('match', pattern, options, nanomatch.matcher);
115 list = utils.arrayify(list);
116 var len = list.length;
119 while (++idx < len) {
121 if (ele === pattern || isMatch(ele)) {
122 matches.push(utils.value(ele, unixify, options));
126 // if no options were passed, uniquify results and return
127 if (typeof options === 'undefined') {
128 return utils.unique(matches);
131 if (matches.length === 0) {
132 if (options.failglob === true) {
133 throw new Error('no matches found for "' + pattern + '"');
135 if (options.nonull === true || options.nullglob === true) {
136 return [options.unescape ? utils.unescape(pattern) : pattern];
140 // if `opts.ignore` was defined, diff ignored list
141 if (options.ignore) {
142 matches = nanomatch.not(matches, options.ignore, options);
145 return options.nodupes !== false ? utils.unique(matches) : matches;
149 * Returns true if the specified `string` matches the given glob `pattern`.
152 * var nm = require('nanomatch');
153 * nm.isMatch(string, pattern[, options]);
155 * console.log(nm.isMatch('a.a', '*.a'));
157 * console.log(nm.isMatch('a.b', '*.a'));
160 * @param {String} `string` String to match
161 * @param {String} `pattern` Glob pattern to use for matching.
162 * @param {Object} `options` See available [options](#options) for changing how matches are performed
163 * @return {Boolean} Returns true if the string matches the glob pattern.
167 nanomatch.isMatch = function(str, pattern, options) {
168 if (typeof str !== 'string') {
169 throw new TypeError('expected a string: "' + util.inspect(str) + '"');
172 if (utils.isEmptyString(str) || utils.isEmptyString(pattern)) {
176 var equals = utils.equalsPattern(options);
181 var isMatch = memoize('isMatch', pattern, options, nanomatch.matcher);
186 * Returns true if some of the elements in the given `list` match any of the
187 * given glob `patterns`.
190 * var nm = require('nanomatch');
191 * nm.some(list, patterns[, options]);
193 * console.log(nm.some(['foo.js', 'bar.js'], ['*.js', '!foo.js']));
195 * console.log(nm.some(['foo.js'], ['*.js', '!foo.js']));
198 * @param {String|Array} `list` The string or array of strings to test. Returns as soon as the first match is found.
199 * @param {String|Array} `patterns` One or more glob patterns to use for matching.
200 * @param {Object} `options` See available [options](#options) for changing how matches are performed
201 * @return {Boolean} Returns true if any patterns match `str`
205 nanomatch.some = function(list, patterns, options) {
206 if (typeof list === 'string') {
210 for (var i = 0; i < list.length; i++) {
211 if (nanomatch(list[i], patterns, options).length === 1) {
220 * Returns true if every element in the given `list` matches
221 * at least one of the given glob `patterns`.
224 * var nm = require('nanomatch');
225 * nm.every(list, patterns[, options]);
227 * console.log(nm.every('foo.js', ['foo.js']));
229 * console.log(nm.every(['foo.js', 'bar.js'], ['*.js']));
231 * console.log(nm.every(['foo.js', 'bar.js'], ['*.js', '!foo.js']));
233 * console.log(nm.every(['foo.js'], ['*.js', '!foo.js']));
236 * @param {String|Array} `list` The string or array of strings to test.
237 * @param {String|Array} `patterns` One or more glob patterns to use for matching.
238 * @param {Object} `options` See available [options](#options) for changing how matches are performed
239 * @return {Boolean} Returns true if any patterns match `str`
243 nanomatch.every = function(list, patterns, options) {
244 if (typeof list === 'string') {
248 for (var i = 0; i < list.length; i++) {
249 if (nanomatch(list[i], patterns, options).length !== 1) {
258 * Returns true if **any** of the given glob `patterns`
259 * match the specified `string`.
262 * var nm = require('nanomatch');
263 * nm.any(string, patterns[, options]);
265 * console.log(nm.any('a.a', ['b.*', '*.a']));
267 * console.log(nm.any('a.a', 'b.*'));
270 * @param {String|Array} `str` The string to test.
271 * @param {String|Array} `patterns` One or more glob patterns to use for matching.
272 * @param {Object} `options` See available [options](#options) for changing how matches are performed
273 * @return {Boolean} Returns true if any patterns match `str`
277 nanomatch.any = function(str, patterns, options) {
278 if (typeof str !== 'string') {
279 throw new TypeError('expected a string: "' + util.inspect(str) + '"');
282 if (utils.isEmptyString(str) || utils.isEmptyString(patterns)) {
286 if (typeof patterns === 'string') {
287 patterns = [patterns];
290 for (var i = 0; i < patterns.length; i++) {
291 if (nanomatch.isMatch(str, patterns[i], options)) {
299 * Returns true if **all** of the given `patterns`
300 * match the specified string.
303 * var nm = require('nanomatch');
304 * nm.all(string, patterns[, options]);
306 * console.log(nm.all('foo.js', ['foo.js']));
309 * console.log(nm.all('foo.js', ['*.js', '!foo.js']));
312 * console.log(nm.all('foo.js', ['*.js', 'foo.js']));
315 * console.log(nm.all('foo.js', ['*.js', 'f*', '*o*', '*o.js']));
318 * @param {String|Array} `str` The string to test.
319 * @param {String|Array} `patterns` One or more glob patterns to use for matching.
320 * @param {Object} `options` See available [options](#options) for changing how matches are performed
321 * @return {Boolean} Returns true if any patterns match `str`
325 nanomatch.all = function(str, patterns, options) {
326 if (typeof str !== 'string') {
327 throw new TypeError('expected a string: "' + util.inspect(str) + '"');
330 if (typeof patterns === 'string') {
331 patterns = [patterns];
334 for (var i = 0; i < patterns.length; i++) {
335 if (!nanomatch.isMatch(str, patterns[i], options)) {
343 * Returns a list of strings that _**do not match any**_ of the given `patterns`.
346 * var nm = require('nanomatch');
347 * nm.not(list, patterns[, options]);
349 * console.log(nm.not(['a.a', 'b.b', 'c.c'], '*.a'));
350 * //=> ['b.b', 'c.c']
352 * @param {Array} `list` Array of strings to match.
353 * @param {String|Array} `patterns` One or more glob pattern to use for matching.
354 * @param {Object} `options` See available [options](#options) for changing how matches are performed
355 * @return {Array} Returns an array of strings that **do not match** the given patterns.
359 nanomatch.not = function(list, patterns, options) {
360 var opts = extend({}, options);
361 var ignore = opts.ignore;
364 list = utils.arrayify(list);
366 var matches = utils.diff(list, nanomatch(list, patterns, opts));
368 matches = utils.diff(matches, nanomatch(list, ignore));
371 return opts.nodupes !== false ? utils.unique(matches) : matches;
375 * Returns true if the given `string` contains the given pattern. Similar
376 * to [.isMatch](#isMatch) but the pattern can match any part of the string.
379 * var nm = require('nanomatch');
380 * nm.contains(string, pattern[, options]);
382 * console.log(nm.contains('aa/bb/cc', '*b'));
384 * console.log(nm.contains('aa/bb/cc', '*d'));
387 * @param {String} `str` The string to match.
388 * @param {String|Array} `patterns` Glob pattern to use for matching.
389 * @param {Object} `options` See available [options](#options) for changing how matches are performed
390 * @return {Boolean} Returns true if the patter matches any part of `str`.
394 nanomatch.contains = function(str, patterns, options) {
395 if (typeof str !== 'string') {
396 throw new TypeError('expected a string: "' + util.inspect(str) + '"');
399 if (typeof patterns === 'string') {
400 if (utils.isEmptyString(str) || utils.isEmptyString(patterns)) {
404 var equals = utils.equalsPattern(patterns, options);
408 var contains = utils.containsPattern(patterns, options);
414 var opts = extend({}, options, {contains: true});
415 return nanomatch.any(str, patterns, opts);
419 * Returns true if the given pattern and options should enable
420 * the `matchBase` option.
425 nanomatch.matchBase = function(pattern, options) {
426 if (pattern && pattern.indexOf('/') !== -1 || !options) return false;
427 return options.basename === true || options.matchBase === true;
431 * Filter the keys of the given object with the given `glob` pattern
432 * and `options`. Does not attempt to match nested keys. If you need this feature,
433 * use [glob-object][] instead.
436 * var nm = require('nanomatch');
437 * nm.matchKeys(object, patterns[, options]);
439 * var obj = { aa: 'a', ab: 'b', ac: 'c' };
440 * console.log(nm.matchKeys(obj, '*b'));
443 * @param {Object} `object` The object with keys to filter.
444 * @param {String|Array} `patterns` One or more glob patterns to use for matching.
445 * @param {Object} `options` See available [options](#options) for changing how matches are performed
446 * @return {Object} Returns an object with only keys that match the given patterns.
450 nanomatch.matchKeys = function(obj, patterns, options) {
451 if (!utils.isObject(obj)) {
452 throw new TypeError('expected the first argument to be an object');
454 var keys = nanomatch(Object.keys(obj), patterns, options);
455 return utils.pick(obj, keys);
459 * Returns a memoized matcher function from the given glob `pattern` and `options`.
460 * The returned function takes a string to match as its only argument and returns
461 * true if the string is a match.
464 * var nm = require('nanomatch');
465 * nm.matcher(pattern[, options]);
467 * var isMatch = nm.matcher('*.!(*a)');
468 * console.log(isMatch('a.a'));
470 * console.log(isMatch('a.b'));
473 * @param {String} `pattern` Glob pattern
474 * @param {Object} `options` See available [options](#options) for changing how matches are performed.
475 * @return {Function} Returns a matcher function.
479 nanomatch.matcher = function matcher(pattern, options) {
480 if (utils.isEmptyString(pattern)) {
486 if (Array.isArray(pattern)) {
487 return compose(pattern, options, matcher);
490 // if pattern is a regex
491 if (pattern instanceof RegExp) {
492 return test(pattern);
495 // if pattern is invalid
496 if (!utils.isString(pattern)) {
497 throw new TypeError('expected pattern to be an array, string or regex');
500 // if pattern is a non-glob string
501 if (!utils.hasSpecialChars(pattern)) {
502 if (options && options.nocase === true) {
503 pattern = pattern.toLowerCase();
505 return utils.matchPath(pattern, options);
508 // if pattern is a glob string
509 var re = nanomatch.makeRe(pattern, options);
511 // if `options.matchBase` or `options.basename` is defined
512 if (nanomatch.matchBase(pattern, options)) {
513 return utils.matchBasename(re, options);
516 function test(regex) {
517 var equals = utils.equalsPattern(options);
518 var unixify = utils.unixify(options);
520 return function(str) {
525 if (regex.test(unixify(str))) {
532 // create matcher function
533 var matcherFn = test(re);
534 // set result object from compiler on matcher function,
535 // as a non-enumerable property. useful for debugging
536 utils.define(matcherFn, 'result', re.result);
541 * Returns an array of matches captured by `pattern` in `string, or
542 * `null` if the pattern did not match.
545 * var nm = require('nanomatch');
546 * nm.capture(pattern, string[, options]);
548 * console.log(nm.capture('test/*.js', 'test/foo.js'));
550 * console.log(nm.capture('test/*.js', 'foo/bar.css'));
553 * @param {String} `pattern` Glob pattern to use for matching.
554 * @param {String} `string` String to match
555 * @param {Object} `options` See available [options](#options) for changing how matches are performed
556 * @return {Boolean} Returns an array of captures if the string matches the glob pattern, otherwise `null`.
560 nanomatch.capture = function(pattern, str, options) {
561 var re = nanomatch.makeRe(pattern, extend({capture: true}, options));
562 var unixify = utils.unixify(options);
565 return function(string) {
566 var match = re.exec(unixify(string));
571 return match.slice(1);
575 var capture = memoize('capture', pattern, options, match);
580 * Create a regular expression from the given glob `pattern`.
583 * var nm = require('nanomatch');
584 * nm.makeRe(pattern[, options]);
586 * console.log(nm.makeRe('*.js'));
587 * //=> /^(?:(\.[\\\/])?(?!\.)(?=.)[^\/]*?\.js)$/
589 * @param {String} `pattern` A glob pattern to convert to regex.
590 * @param {Object} `options` See available [options](#options) for changing how matches are performed.
591 * @return {RegExp} Returns a regex created from the given pattern.
595 nanomatch.makeRe = function(pattern, options) {
596 if (pattern instanceof RegExp) {
600 if (typeof pattern !== 'string') {
601 throw new TypeError('expected pattern to be a string');
604 if (pattern.length > MAX_LENGTH) {
605 throw new Error('expected pattern to be less than ' + MAX_LENGTH + ' characters');
609 var opts = utils.extend({wrap: false}, options);
610 var result = nanomatch.create(pattern, opts);
611 var regex = toRegex(result.output, opts);
612 utils.define(regex, 'result', result);
616 return memoize('makeRe', pattern, options, makeRe);
620 * Parses the given glob `pattern` and returns an object with the compiled `output`
621 * and optional source `map`.
624 * var nm = require('nanomatch');
625 * nm.create(pattern[, options]);
627 * console.log(nm.create('abc/*.js'));
628 * // { options: { source: 'string', sourcemap: true },
632 * // output: '(\\.[\\\\\\/])?abc\\/(?!\\.)(?=.)[^\\/]*?\\.js',
639 * // input: 'abc/*.js' },
640 * // parsingErrors: [],
643 * // sources: [ 'string' ],
645 * // mappings: 'AAAA,GAAG,EAAC,kBAAC,EAAC,EAAE',
646 * // sourcesContent: [ 'abc/*.js' ] },
647 * // position: { line: 1, column: 28 },
652 * @param {String} `pattern` Glob pattern to parse and compile.
653 * @param {Object} `options` Any [options](#options) to change how parsing and compiling is performed.
654 * @return {Object} Returns an object with the parsed AST, compiled string and optional source map.
658 nanomatch.create = function(pattern, options) {
659 if (typeof pattern !== 'string') {
660 throw new TypeError('expected a string');
663 return nanomatch.compile(nanomatch.parse(pattern, options), options);
665 return memoize('create', pattern, options, create);
669 * Parse the given `str` with the given `options`.
672 * var nm = require('nanomatch');
673 * nm.parse(pattern[, options]);
675 * var ast = nm.parse('a/{b,c}/d');
679 * // input: 'a/{b,c}/d',
681 * // [ { type: 'bos', val: '' },
682 * // { type: 'text', val: 'a/' },
683 * // { type: 'brace',
685 * // [ { type: 'brace.open', val: '{' },
686 * // { type: 'text', val: 'b,c' },
687 * // { type: 'brace.close', val: '}' } ] },
688 * // { type: 'text', val: '/d' },
689 * // { type: 'eos', val: '' } ] }
691 * @param {String} `str`
692 * @param {Object} `options`
693 * @return {Object} Returns an AST
697 nanomatch.parse = function(pattern, options) {
698 if (typeof pattern !== 'string') {
699 throw new TypeError('expected a string');
703 var snapdragon = utils.instantiate(null, options);
704 parsers(snapdragon, options);
706 var ast = snapdragon.parse(pattern, options);
707 utils.define(ast, 'snapdragon', snapdragon);
712 return memoize('parse', pattern, options, parse);
716 * Compile the given `ast` or string with the given `options`.
719 * var nm = require('nanomatch');
720 * nm.compile(ast[, options]);
722 * var ast = nm.parse('a/{b,c}/d');
723 * console.log(nm.compile(ast));
724 * // { options: { source: 'string' },
727 * // { eos: [Function],
728 * // noop: [Function],
729 * // bos: [Function],
730 * // brace: [Function],
731 * // 'brace.open': [Function],
732 * // text: [Function],
733 * // 'brace.close': [Function] },
734 * // output: [ 'a/(b|c)/d' ],
737 * // parsingErrors: [] }
739 * @param {Object|String} `ast`
740 * @param {Object} `options`
741 * @return {Object} Returns an object that has an `output` property with the compiled string.
745 nanomatch.compile = function(ast, options) {
746 if (typeof ast === 'string') {
747 ast = nanomatch.parse(ast, options);
751 var snapdragon = utils.instantiate(ast, options);
752 compilers(snapdragon, options);
753 return snapdragon.compile(ast, options);
756 return memoize('compile', ast.input, options, compile);
760 * Clear the regex cache.
768 nanomatch.clearCache = function() {
769 nanomatch.cache.__data__ = {};
773 * Compose a matcher function with the given patterns.
774 * This allows matcher functions to be compiled once and
775 * called multiple times.
778 function compose(patterns, options, matcher) {
781 return memoize('compose', String(patterns), options, function() {
782 return function(file) {
783 // delay composition until it's invoked the first time,
784 // after that it won't be called again
787 for (var i = 0; i < patterns.length; i++) {
788 matchers.push(matcher(patterns[i], options));
792 var len = matchers.length;
794 if (matchers[len](file) === true) {
804 * Memoize a generated regex or function. A unique key is generated
805 * from the `type` (usually method name), the `pattern`, and
806 * user-defined options.
809 function memoize(type, pattern, options, fn) {
810 var key = utils.createKey(type + '=' + pattern, options);
812 if (options && options.cache === false) {
813 return fn(pattern, options);
816 if (cache.has(type, key)) {
817 return cache.get(type, key);
820 var val = fn(pattern, options);
821 cache.set(type, key, val);
826 * Expose compiler, parser and cache on `nanomatch`
829 nanomatch.compilers = compilers;
830 nanomatch.parsers = parsers;
831 nanomatch.cache = cache;
838 module.exports = nanomatch;