GithubHelp home page GithubHelp logo

micromatch / anymatch Goto Github PK

View Code? Open in Web Editor NEW
382.0 13.0 39.0 94 KB

:bangbang: Matches strings against configurable strings, globs, regular expressions, and/or functions

License: ISC License

JavaScript 100.00%
matcher glob match fs micromatch minimatch multimatch node nodejs javascript

anymatch's Introduction

micromatch NPM version NPM monthly downloads NPM total downloads Tests

Glob matching for javascript/node.js. A replacement and faster alternative to minimatch and multimatch.

Please consider following this project's author, Jon Schlinkert, and consider starring the project to show your ❤️ and support.

Table of Contents

Details

Install

Install with npm (requires Node.js >=8.6):

$ npm install --save micromatch

Sponsors

Become a Sponsor to add your logo to this README, or any of my other projects


Quickstart

const micromatch = require('micromatch');
// micromatch(list, patterns[, options]);

The main export takes a list of strings and one or more glob patterns:

console.log(micromatch(['foo', 'bar', 'baz', 'qux'], ['f*', 'b*'])) //=> ['foo', 'bar', 'baz']
console.log(micromatch(['foo', 'bar', 'baz', 'qux'], ['*', '!b*'])) //=> ['foo', 'qux']

Use .isMatch() to for boolean matching:

console.log(micromatch.isMatch('foo', 'f*')) //=> true
console.log(micromatch.isMatch('foo', ['b*', 'f*'])) //=> true

Switching from minimatch and multimatch is easy!


Why use micromatch?

micromatch is a replacement for minimatch and multimatch

  • Supports all of the same matching features as minimatch and multimatch
  • 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.
  • Fast & Performant - Loads in about 5ms and performs fast matches.
  • Glob matching - Using wildcards (* and ?), globstars (**) for nested directories
  • Advanced globbing - Supports extglobs, braces, and POSIX brackets, and support for escaping special characters with \ or quotes.
  • Accurate - Covers more scenarios than minimatch
  • Well tested - More than 5,000 test assertions
  • Windows support - More reliable windows support than minimatch and multimatch.
  • Safe{#braces-is-safe} - Micromatch is not subject to DoS with brace patterns like minimatch and multimatch.

Matching features

  • Support for multiple glob patterns (no need for wrappers like multimatch)
  • Wildcards (**, *.js)
  • Negation ('!a/*.js', '*!(b).js')
  • extglobs (+(x|y), !(a|b))
  • POSIX character classes ([[:alpha:][:digit:]])
  • brace expansion (foo/{1..5}.md, bar/{a,b,c}.js)
  • regex character classes (foo-[1-5].js)
  • regex logical "or" (foo/(abc|xyz).js)

You can mix and match these features to create whatever patterns you need!

Switching to micromatch

(There is one notable difference between micromatch and minimatch in regards to how backslashes are handled. See the notes about backslashes for more information.)

From minimatch

Use micromatch.isMatch() instead of minimatch():

console.log(micromatch.isMatch('foo', 'b*')); //=> false

Use micromatch.match() instead of minimatch.match():

console.log(micromatch.match(['foo', 'bar'], 'b*')); //=> 'bar'

From multimatch

Same signature:

console.log(micromatch(['foo', 'bar', 'baz'], ['f*', '*z'])); //=> ['foo', 'baz']

API

Params

  • list {String|Array}: List of strings to match.
  • patterns {String|Array}: One or more glob patterns to use for matching.
  • options {Object}: See available options
  • returns {Array}: Returns an array of matches

Example

const mm = require('micromatch');
// mm(list, patterns[, options]);

console.log(mm(['a.js', 'a.txt'], ['*.js']));
//=> [ 'a.js' ]

Returns a 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.

Params

  • pattern {String}: Glob pattern
  • options {Object}
  • returns {Function}: Returns a matcher function.

Example

const mm = require('micromatch');
// mm.matcher(pattern[, options]);

const isMatch = mm.matcher('*.!(*a)');
console.log(isMatch('a.a')); //=> false
console.log(isMatch('a.b')); //=> true

Returns true if any of the given glob patterns match the specified string.

Params

  • str {String}: The string to test.
  • patterns {String|Array}: One or more glob patterns to use for matching.
  • [options] {Object}: See available options.
  • returns {Boolean}: Returns true if any patterns match str

Example

const mm = require('micromatch');
// mm.isMatch(string, patterns[, options]);

console.log(mm.isMatch('a.a', ['b.*', '*.a'])); //=> true
console.log(mm.isMatch('a.a', 'b.*')); //=> false

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 for changing how matches are performed
  • returns {Array}: Returns an array of strings that do not match the given patterns.

Example

const mm = require('micromatch');
// mm.not(list, patterns[, options]);

console.log(mm.not(['a.a', 'b.b', 'c.c'], '*.a'));
//=> ['b.b', 'c.c']

Returns true if the given string contains the given pattern. Similar to .isMatch but the pattern can match any part of the string.

Params

  • str {String}: The string to match.
  • patterns {String|Array}: Glob pattern to use for matching.
  • options {Object}: See available options for changing how matches are performed
  • returns {Boolean}: Returns true if any of the patterns matches any part of str.

Example

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

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.

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 for changing how matches are performed
  • returns {Object}: Returns an object with only keys that match the given patterns.

Example

const mm = require('micromatch');
// mm.matchKeys(object, patterns[, options]);

const obj = { aa: 'a', ab: 'b', ac: 'c' };
console.log(mm.matchKeys(obj, '*b'));
//=> { ab: 'b' }

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 for changing how matches are performed
  • returns {Boolean}: Returns true if any patterns matches any of the strings in list

Example

const 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

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 for changing how matches are performed
  • returns {Boolean}: Returns true if all patterns matches all of the strings in list

Example

const 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

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 for changing how matches are performed
  • returns {Boolean}: Returns true if any patterns match str

Example

const mm = require('micromatch');
// mm.all(string, patterns[, options]);

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

Returns an array of matches captured by pattern in string, or null` if the pattern did not match.

Params

  • glob {String}: Glob pattern to use for matching.
  • input {String}: String to match
  • options {Object}: See available options for changing how matches are performed
  • returns {Array|null}: Returns an array of captures if the input matches the glob pattern, otherwise null.

Example

const mm = require('micromatch');
// mm.capture(pattern, string[, options]);

console.log(mm.capture('test/*.js', 'test/foo.js'));
//=> ['foo']
console.log(mm.capture('test/*.js', 'foo/bar.css'));
//=> null

Create a regular expression from the given glob pattern.

Params

  • pattern {String}: A glob pattern to convert to regex.
  • options {Object}
  • returns {RegExp}: Returns a regex created from the given pattern.

Example

const mm = require('micromatch');
// mm.makeRe(pattern[, options]);

console.log(mm.makeRe('*.js'));
//=> /^(?:(\.[\\\/])?(?!\.)(?=.)[^\/]*?\.js)$/

Scan a glob pattern to separate the pattern into segments. Used by the split method.

Params

  • pattern {String}
  • options {Object}
  • returns {Object}: Returns an object with

Example

const mm = require('micromatch');
const state = mm.scan(pattern[, options]);

Parse a glob pattern to create the source string for a regular expression.

Params

  • glob {String}
  • options {Object}
  • returns {Object}: Returns an object with useful properties and output to be used as regex source string.

Example

const mm = require('micromatch');
const state = mm.parse(pattern[, options]);

Process the given brace pattern.

Params

  • pattern {String}: String with brace pattern to process.
  • options {Object}: Any options to change how expansion is performed. See the braces library for all available options.
  • returns {Array}

Example

const { braces } = require('micromatch');
console.log(braces('foo/{a,b,c}/bar'));
//=> [ 'foo/(a|b|c)/bar' ]

console.log(braces('foo/{a,b,c}/bar', { expand: true }));
//=> [ 'foo/a/bar', 'foo/b/bar', 'foo/c/bar' ]

Options

Option Type Default value Description
basename boolean false If set, then patterns without slashes will be matched against the basename of the path if it contains slashes. For example, a?b would match the path /xyz/123/acb, but not /xyz/acb/123.
bash boolean false Follow bash matching rules more strictly - disallows backslashes as escape characters, and treats single stars as globstars (**).
capture boolean undefined Return regex matches in supporting methods.
contains boolean undefined Allows glob to match any part of the given string(s).
cwd string process.cwd() Current working directory. Used by picomatch.split()
debug boolean undefined Debug regular expressions when an error is thrown.
dot boolean false Match dotfiles. Otherwise dotfiles are ignored unless a . is explicitly defined in the pattern.
expandRange function undefined Custom function for expanding ranges in brace patterns, such as {a..z}. The function receives the range values as two arguments, and it must return a string to be used in the generated regex. It's recommended that returned strings be wrapped in parentheses. This option is overridden by the expandBrace option.
failglob boolean false Similar to the failglob behavior in Bash, throws an error when no matches are found. Based on the bash option of the same name.
fastpaths boolean true To speed up processing, full parsing is skipped for a handful common glob patterns. Disable this behavior by setting this option to false.
flags boolean undefined Regex flags to use in the generated regex. If defined, the nocase option will be overridden.
format function undefined Custom function for formatting the returned string. This is useful for removing leading slashes, converting Windows paths to Posix paths, etc.
ignore array|string undefined One or more glob patterns for excluding strings that should not be matched from the result.
keepQuotes boolean false Retain quotes in the generated regex, since quotes may also be used as an alternative to backslashes.
literalBrackets boolean undefined When true, brackets in the glob pattern will be escaped so that only literal brackets will be matched.
lookbehinds boolean true Support regex positive and negative lookbehinds. Note that you must be using Node 8.1.10 or higher to enable regex lookbehinds.
matchBase boolean false Alias for basename
maxLength boolean 65536 Limit the max length of the input string. An error is thrown if the input string is longer than this value.
nobrace boolean false Disable brace matching, so that {a,b} and {1..3} would be treated as literal characters.
nobracket boolean undefined Disable matching with regex brackets.
nocase boolean false Perform case-insensitive matching. Equivalent to the regex i flag. Note that this option is ignored when the flags option is defined.
nodupes boolean true Deprecated, use nounique instead. This option will be removed in a future major release. By default duplicates are removed. Disable uniquification by setting this option to false.
noext boolean false Alias for noextglob
noextglob boolean false Disable support for matching with extglobs (like +(a|b))
noglobstar boolean false Disable support for matching nested directories with globstars (**)
nonegate boolean false Disable support for negating with leading !
noquantifiers boolean false Disable support for regex quantifiers (like a{1,2}) and treat them as brace patterns to be expanded.
onIgnore function undefined Function to be called on ignored items.
onMatch function undefined Function to be called on matched items.
onResult function undefined Function to be called on all items, regardless of whether or not they are matched or ignored.
posix boolean false Support POSIX character classes ("posix brackets").
posixSlashes boolean undefined Convert all slashes in file paths to forward slashes. This does not convert slashes in the glob pattern itself
prepend string undefined String to prepend to the generated regex used for matching.
regex boolean false Use regular expression rules for + (instead of matching literal +), and for stars that follow closing parentheses or brackets (as in )* and ]*).
strictBrackets boolean undefined Throw an error if brackets, braces, or parens are imbalanced.
strictSlashes boolean undefined When true, picomatch won't match trailing slashes with single stars.
unescape boolean undefined Remove preceding backslashes from escaped glob characters before creating the regular expression to perform matches.
unixify boolean undefined Alias for posixSlashes, for backwards compatitibility.

Options Examples

options.basename

Allow glob patterns without slashes to match a file path based on its basename. Same behavior as minimatch option matchBase.

Type: Boolean

Default: false

Example

micromatch(['a/b.js', 'a/c.md'], '*.js');
//=> []

micromatch(['a/b.js', 'a/c.md'], '*.js', { basename: true });
//=> ['a/b.js']

options.bash

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 any other star.

Type: Boolean

Default: true

Example

const files = ['abc', 'ajz'];
console.log(micromatch(files, '[a-c]*'));
//=> ['abc', 'ajz']

console.log(micromatch(files, '[a-c]*', { bash: false }));

options.expandRange

Type: function

Default: undefined

Custom function for expanding ranges in brace patterns. The fill-range library is ideal for this purpose, or you can use custom code to do whatever you need.

Example

The following example shows how to create a glob that matches a numeric folder name between 01 and 25, with leading zeros.

const fill = require('fill-range');
const regex = micromatch.makeRe('foo/{01..25}/bar', {
  expandRange(a, b) {
    return `(${fill(a, b, { toRegex: true })})`;
  }
});

console.log(regex)
//=> /^(?:foo\/((?:0[1-9]|1[0-9]|2[0-5]))\/bar)$/

console.log(regex.test('foo/00/bar')) // false
console.log(regex.test('foo/01/bar')) // true
console.log(regex.test('foo/10/bar')) // true
console.log(regex.test('foo/22/bar')) // true
console.log(regex.test('foo/25/bar')) // true
console.log(regex.test('foo/26/bar')) // false

options.format

Type: function

Default: undefined

Custom function for formatting strings before they're matched.

Example

// strip leading './' from strings
const format = str => str.replace(/^\.\//, '');
const isMatch = picomatch('foo/*.js', { format });
console.log(isMatch('./foo/bar.js')) //=> true

options.ignore

String or array of glob patterns to match files to ignore.

Type: String|Array

Default: undefined

const isMatch = micromatch.matcher('*', { ignore: 'f*' });
console.log(isMatch('foo')) //=> false
console.log(isMatch('bar')) //=> true
console.log(isMatch('baz')) //=> true

options.matchBase

Alias for options.basename.

options.noextglob

Disable extglob support, so that extglobs are regarded as literal characters.

Type: Boolean

Default: undefined

Examples

console.log(micromatch(['a/z', 'a/b', 'a/!(z)'], 'a/!(z)'));
//=> ['a/b', 'a/!(z)']

console.log(micromatch(['a/z', 'a/b', 'a/!(z)'], 'a/!(z)', { noextglob: true }));
//=> ['a/!(z)'] (matches only as literal characters)

options.nonegate

Disallow negation (!) patterns, and treat leading ! as a literal character to match.

Type: Boolean

Default: undefined

options.noglobstar

Disable matching with globstars (**).

Type: Boolean

Default: undefined

micromatch(['a/b', 'a/b/c', 'a/b/c/d'], 'a/**');
//=> ['a/b', 'a/b/c', 'a/b/c/d']

micromatch(['a/b', 'a/b/c', 'a/b/c/d'], 'a/**', {noglobstar: true});
//=> ['a/b']

options.nonull

Alias for options.nullglob.

options.nullglob

If true, when no matches are found the actual (arrayified) glob pattern is returned instead of an empty array. Same behavior as minimatch option nonull.

Type: Boolean

Default: undefined

options.onIgnore

const onIgnore = ({ glob, regex, input, output }) => {
  console.log({ glob, regex, input, output });
  // { glob: '*', regex: /^(?:(?!\.)(?=.)[^\/]*?\/?)$/, input: 'foo', output: 'foo' }
};

const isMatch = micromatch.matcher('*', { onIgnore, ignore: 'f*' });
isMatch('foo');
isMatch('bar');
isMatch('baz');

options.onMatch

const onMatch = ({ glob, regex, input, output }) => {
  console.log({ input, output });
  // { input: 'some\\path', output: 'some/path' }
  // { input: 'some\\path', output: 'some/path' }
  // { input: 'some\\path', output: 'some/path' }
};

const isMatch = micromatch.matcher('**', { onMatch, posixSlashes: true });
isMatch('some\\path');
isMatch('some\\path');
isMatch('some\\path');

options.onResult

const onResult = ({ glob, regex, input, output }) => {
  console.log({ glob, regex, input, output });
};

const isMatch = micromatch('*', { onResult, ignore: 'f*' });
isMatch('foo');
isMatch('bar');
isMatch('baz');

options.posixSlashes

Convert path separators on returned files to posix/unix-style forward slashes. Aliased as unixify for backwards compatibility.

Type: Boolean

Default: true on windows, false everywhere else.

Example

console.log(micromatch.match(['a\\b\\c'], 'a/**'));
//=> ['a/b/c']

console.log(micromatch.match(['a\\b\\c'], { posixSlashes: false }));
//=> ['a\\b\\c']

options.unescape

Remove backslashes from escaped glob characters before creating the regular expression to perform matches.

Type: Boolean

Default: undefined

Example

In this example we want to match a literal *:

console.log(micromatch.match(['abc', 'a\\*c'], 'a\\*c'));
//=> ['a\\*c']

console.log(micromatch.match(['abc', 'a\\*c'], 'a\\*c', { unescape: true }));
//=> ['a*c']


Extended globbing

Micromatch supports the following extended globbing features.

Extglobs

Extended globbing, as described by the bash man page:

pattern regex equivalent description
?(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) * Matches one of the given patterns
!(pattern) N/A (equivalent regex is much more complicated) Matches anything except one of the given patterns

* Note that @ isn't a regex character.

Braces

Brace patterns can be used to match specific ranges or sets of characters.

Example

The pattern {f,b}*/{1..3}/{b,q}* would match any of following strings:

foo/1/bar
foo/2/bar
foo/3/bar
baz/1/qux
baz/2/qux
baz/3/qux

Visit braces to see the full range of features and options related to brace expansion, or to create brace matching or expansion related issues.

Regex character classes

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']
  • [b-d].js: matches from b to d, returning ['b.js', 'c.js', 'd.js']
  • a/[A-Z].js: matches and uppercase letter, returning ['a/E.md']

Learn about regex character classes.

Regex groups

Given ['a.js', 'b.js', 'c.js', 'd.js', 'E.js']:

  • (a|c).js: would match either a or c, returning ['a.js', 'c.js']
  • (b|d).js: would match either b or d, returning ['b.js', 'd.js']
  • (b|[A-Z]).js: would match either b or an uppercase letter, returning ['b.js', 'E.js']

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 brackets are intended to be more user-friendly than regex character classes. This of course is in the eye of the beholder.

Example

console.log(micromatch.isMatch('a1', '[[:alpha:][:digit:]]')) //=> true
console.log(micromatch.isMatch('a1', '[[:alpha:][:alpha:]]')) //=> false

Notes

Bash 4.3 parity

Whenever possible matching behavior is based on behavior Bash 4.3, which is mostly consistent with minimatch.

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.

Backslashes

There is an important, notable difference between minimatch and micromatch in regards to how backslashes are handled in glob patterns.

  • Micromatch exclusively and explicitly reserves backslashes for escaping characters in a glob pattern, even on windows, which is consistent with bash behavior. More importantly, unescaping globs can result in unsafe regular expressions.
  • Minimatch converts all backslashes to forward slashes, which means you can't use backslashes to escape any characters in your glob patterns.

We made this decision for micromatch for a couple of reasons:

  • Consistency with bash conventions.
  • Glob patterns are not filepaths. They are a type of 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.

A note about joining paths to globs

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 \\.

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.

To solve this, you might be inspired to do something like 'foo\\*'.replace(/\\/g, '/'), but this causes another, potentially much more serious, problem.

Benchmarks

Running benchmarks

Install dependencies for running benchmarks:

$ cd bench && npm install

Run the benchmarks:

$ npm run bench

Latest results

As of July 12, 2023 (longer bars are better):

# .makeRe star
  micromatch x 2,232,802 ops/sec ±2.34% (89 runs sampled))
  minimatch x 781,018 ops/sec ±6.74% (92 runs sampled))

# .makeRe star; dot=true
  micromatch x 1,863,453 ops/sec ±0.74% (93 runs sampled)
  minimatch x 723,105 ops/sec ±0.75% (93 runs sampled)

# .makeRe globstar
  micromatch x 1,624,179 ops/sec ±2.22% (91 runs sampled)
  minimatch x 1,117,230 ops/sec ±2.78% (86 runs sampled))

# .makeRe globstars
  micromatch x 1,658,642 ops/sec ±0.86% (92 runs sampled)
  minimatch x 741,224 ops/sec ±1.24% (89 runs sampled))

# .makeRe with leading star
  micromatch x 1,525,014 ops/sec ±1.63% (90 runs sampled)
  minimatch x 561,074 ops/sec ±3.07% (89 runs sampled)

# .makeRe - braces
  micromatch x 172,478 ops/sec ±2.37% (78 runs sampled)
  minimatch x 96,087 ops/sec ±2.34% (88 runs sampled)))

# .makeRe braces - range (expanded)
  micromatch x 26,973 ops/sec ±0.84% (89 runs sampled)
  minimatch x 3,023 ops/sec ±0.99% (90 runs sampled))

# .makeRe braces - range (compiled)
  micromatch x 152,892 ops/sec ±1.67% (83 runs sampled)
  minimatch x 992 ops/sec ±3.50% (89 runs sampled)d))

# .makeRe braces - nested ranges (expanded)
  micromatch x 15,816 ops/sec ±13.05% (80 runs sampled)
  minimatch x 2,953 ops/sec ±1.64% (91 runs sampled)

# .makeRe braces - nested ranges (compiled)
  micromatch x 110,881 ops/sec ±1.85% (82 runs sampled)
  minimatch x 1,008 ops/sec ±1.51% (91 runs sampled)

# .makeRe braces - set (compiled)
  micromatch x 134,930 ops/sec ±3.54% (63 runs sampled))
  minimatch x 43,242 ops/sec ±0.60% (93 runs sampled)

# .makeRe braces - nested sets (compiled)
  micromatch x 94,455 ops/sec ±1.74% (69 runs sampled))
  minimatch x 27,720 ops/sec ±1.84% (93 runs sampled))

Contributing

All contributions are welcome! Please read the contributing guide to get started.

Bug reports

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:

  • research existing issues first (open and closed)
  • visit the GNU Bash documentation to see how Bash deals with the pattern
  • visit the 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.

Platform issues

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).

About

Contributing

Pull requests and stars are always welcome. For bugs and feature requests, please create an issue.

Please read the contributing guide for advice on opening issues, pull requests, and coding standards.

Running Tests

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:

$ npm install && npm test
Building docs

(This project's readme.md is generated by verb, please don't edit the readme directly. Any changes to the readme must be made in the .verb.md readme template.)

To generate the readme, run the following command:

$ npm install -g verbose/verb#dev verb-generate-readme && verb

Related projects

You might also be interested in these projects:

  • braces: Bash-like brace expansion, implemented in JavaScript. Safer than other brace expansion libs, with complete support… more | homepage
  • expand-brackets: Expand POSIX bracket expressions (character classes) in glob patterns. | homepage
  • extglob: Extended glob support for JavaScript. Adds (almost) the expressive power of regular expressions to glob… more | homepage
  • fill-range: Fill in a range of numbers or letters, optionally passing an increment or step to… more | homepage
  • nanomatch: Fast, minimal glob matcher for node.js. Similar to micromatch, minimatch and multimatch, but complete Bash… more | homepage

Contributors

Commits Contributor
515 jonschlinkert
12 es128
9 danez
8 doowb
6 paulmillr
5 mrmlnc
3 DrPizza
2 TrySound
2 mceIdo
2 Glazy
2 MartinKolarik
2 antonyk
2 Tvrqvoise
1 amilajack
1 Cslove
1 devongovett
1 DianeLooney
1 UltCombo
1 frangio
1 joyceerhl
1 juszczykjakub
1 muescha
1 sebdeckers
1 tomByrer
1 fidian
1 curbengh
1 simlu
1 wtgtybhertgeghgtwtg
1 yvele

Author

Jon Schlinkert

License

Copyright © 2023, Jon Schlinkert. Released under the MIT License.


This file was generated by verb-generate-readme, v0.8.0, on July 12, 2023.

anymatch's People

Contributors

bpasero avatar code0x9 avatar es128 avatar genisysram avatar joscha avatar leonardodino avatar nerdstep avatar paulmillr avatar phated avatar shvaikalesh avatar the1mills avatar wormen avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

anymatch's Issues

Can't use Picomatch options with returnIndex in TypeScript

I was trying to do something like this:

const processorIndex = anymatch(this.processorGlobs, relativePath, {
    dot: true,
    returnIndex: true
});

But I get the following error:

error TS2345: Argument of type '{ dot: true; returnIndex: boolean; }' is not assignable to parameter of type 'true | PicomatchOptions'.
  Object literal may only specify known properties, and 'returnIndex' does not exist in type 'PicomatchOptions'.

26             returnIndex: true
               ~~~~~~~~~~~~~~~~~


Found 1 error.

I think the typings should be changed to allow this, e.g.:

-(matchers: AnymatchMatcher, testString: string|any[], returnIndex: true | PicomatchOptions): number;
+(matchers: AnymatchMatcher, testString: string|any[], returnIndex: true | PicomatchOptions & { returnIndex?: boolean }): number;

Accept regexish strings

I am using anymatch to ignore stuff, I often pass the ignore parameter from CLI, all those cli parameters are parsed as string. It'd be nice to have anymatch convert /*.css/ to regex automatically.

Looking for anti-match / not-match ability

Re: paulmillr/chokidar#569

I am looking for a way to only match any file in my project that ends with with .tsx

however, it looks like chokidar only supports and ignored option.

so should mean that I need to ignore anything that does not match /\.tsx$/

can this be achieved with anymatch? Hope the question makes sense, thanks

Can this bump micromatch in a minor or patch?

@jonschlinkert @doowb Can this module bump to micromatch 3.x as a minor or patch bump? I believe it's stated that micromatch shouldn't have had any breaking changes.

I bring this up because I'm noticing a ton of duplication in my dependency graph due to this outdated version of micromatch.

Anymatch 3.1.3 represents a non backward compatible change and thus should increment the MAJOR version number.

Semver dictates that patch versions only fix issues, and do not add new functionality. It dictates that minor version incrementation represents an additional feature, with no breaking changes to existing APIs. It specifies that breaking, non-backward compatible changes should be reserved for updates that increment the major version only.

[email protected] vs [email protected] handle filepaths completely differently. One will strip trailing paths while the other passes the right on through. This breaks the semver spec above.

An example of a major project that was broken by the above change is brunch/brunch.

Please be aware of this when deciding which part of the version number to increment. The purpose of semver is to allow things like bugfixes and critical security updates to be rolled out in patches so that the prefix sigil "^" in package.json can be used with confidence.

If changes like this are rolled out in patch versions, developers will lose confidence in the automatic update structure of npm, and security holes will remain open in places they otherwise would not.

Please enforce semver when rolling out new releases. Its the responsible thing to do.

When there is a midline, the result is wrong.

When there is a midline, the result is wrong.

const anymatch = require('anymatch');
const matchers = ['src/abc/**/*'];
anymatch(matchers, 'src/abc/index.js') // true
anymatch(matchers, 'src/abc_def/index.js') // false
anymatch(matchers, 'src/abc-def/index.js') // should be false,  but the result is true

checking in...

just checking in to make sure you haven't had any problems with micromatch on gulp-watch/chokidar. feel free to close if not

Falsy negated matcher negates falsy positive matcher but probably shouldn't

Given the following example:

anymatch([`**/*.hbs`], 'components/render/render.spec.js') // false
anymatch([`**/*.hbs`, `!**/*.config.hbs`], 'components/render/render.spec.js') // true

I would expect anymatch to return false for the second call but it returns true.

Note that this returned false for both calls in v2.0.0 but returns true for the second in v3.1.1. Not sure if this is an intentional breaking change or not. If it is, how can I accomplish the matching logic given in the example?

resolve slash confusion on win32

when testing against regexes or strings on win32, try the path provided as well as a copy where backslashes are replaced with forward slashes

instanceof RegExp is not reliable

I have an API that runs in nodejs, and regexp matchers fail to run properly. I figured something is making instanceof RegExp to fail. If I do the following from the cli:

node
> anymatch([/conv/], 'conversations') // => true

everything is working as intended, but in the app console:

> anymatch([/conv/], 'conversations') // => false

I managed to isolate the issue to this line:

if (matcher instanceof RegExp) {

it seems like that is producing false even if it is a regexp. So what I did was install another small lib, 'kind-of' and do this on that line and everything works fine again.

// from this ...
if (matcher instanceof RegExp) { //...
// to ...
if (kindOf(matcher) === 'regexp') { //...

This resolves that issue.

I know this issue is not related to the lib per se, but I have tried to isolate code in the API and it seems like there is something deep in some lib in npm that is causing this issue on the RegExp class. It seems time wasting and futile to try and correct it that way, rather than make this lib detect the regexp another way. Will update if I somehow find out what is causing it, coz that in itself is a huge issue that something is messing with the Regexp prototype and causing this issue.
Note that most of the libs used in the backend and frontend are similar, and anymatch runs well in the browser ( we share code in the back and front ends of the whole stack) in which anymatch is used. So this leaves server specific libs faulty, of which there is nothing we are doing to mess with the Regxp prototype.

However, the reason why I am letting you guys know about this is that this lib may suffer with this bug just because of other libs that mess that prototype, meaning it could probably be common in many apps and people just don't know this as the cause. So instead, this lib should just avoid that pitfall and use another way to detect regexps, or just directly do this in this lib:

// shamelessly steal this util function to this lib 😉 beauty of open-source
function isRegexp(val) {
  if (val instanceof RegExp) return true;
  return typeof val.flags === 'string'
    && typeof val.ignoreCase === 'boolean'
    && typeof val.multiline === 'boolean'
    && typeof val.global === 'boolean';
}

// then use it on that offending line
if (isRegexp(matcher)) { //...

From the above code in kind-of, it clearly shows that, yes, they understood that instanceof is not perfect, it will fall through somehow and they then make it brutally get the type by checking known RegExp props. This modification will not impact performance under normal circumstances, just that it will make this lib more RELIABLE, though it will take just a few lines of performance hit when RegExp prototype is not working correctly with instanceof.

pls include example of ignoring directory

Classic use case is to ignore any contents of any node_modules directory, where they may be many of these directories in a project.

For use with chokidar, I simply cannot say whether this:

const opts ={
  ignored: ['node_modules']
}

will ignore just the top-level node_modules dir, or any node_modules dir?
can this be documented with anymatch?

thank you!

Travis Error: Failed resolving git HEAD (https://github.com/jonschlinkert/micromatch

Just got this error in our Travis build from fetching micromatch, a dependency for anymatch (which is required in our build form karma)

npm ERR! Failed resolving git HEAD (https://github.com/jonschlinkert/micromatch) fatal: ambiguous argument '2.3.0': unknown revision or path not in the working tree.

npm ERR! Failed resolving git HEAD (https://github.com/jonschlinkert/micromatch) Use '--' to separate paths from revisions, like this:

npm ERR! Failed resolving git HEAD (https://github.com/jonschlinkert/micromatch) 'git <command> [<revision>...] -- [<file>...]'

npm ERR! Failed resolving git HEAD (https://github.com/jonschlinkert/micromatch) 

This issue probably do not belong here, but I put it here for others to be aware of the issue

Could this be a version mismatch at your end, or is this a result of bad dep version range in a dependency?

Ref: micromatch/micromatch#46

Typescript doesn't like the types shipped with the module

The index.d.ts doesn't seem to play nice with Typescript v3.4.1. It results in the following errors:

Screen Shot 2019-04-16 at 3 58 13 PM

node_modules/anymatch/index.d.ts:5:20 - error TS7051: Parameter has a name but no type. Did you mean 'arg0: string'?

5 type AnymatchFn = (string) => boolean;
                     ~~~~~~

node_modules/anymatch/index.d.ts:8:73 - error TS2314: Generic type 'Array<T>' requires 1 type argument(s).

8 declare function anymatch(matchers: AnymatchMatcher, testString: string|Array, returnIndex?: boolean): boolean;
                                                                          ~~~~~

node_modules/anymatch/index.d.ts:9:75 - error TS2314: Generic type 'Array<T>' requires 1 type argument(s).

9 declare function anymatch(matchers: AnymatchMatcher): (testString: string|Array, returnIndex?: boolean) => number;
                                                                            ~~~~~

No way to configure nocase

micromatch has nocase but anymatch doesn't. Would be nice to support options as a third argument, or second argument for currying…

String with tailing slash won't match self

Example:

> const anymatch = require('anymatch');
undefined
> var aaa = '/api/ad/union/sdk/get_ads/'
undefined
> anymatch([aaa], aaa)
false
> aaa = '/api/ad/union/sdk/getads/'
'/api/ad/union/sdk/getads/'
> anymatch([aaa], aaa)
false
> aaa = '/api/ad/union/sdk/getads'
'/api/ad/union/sdk/getads'
> anymatch([aaa], aaa)
true

dot in testString as pathname or filename, can't match

use case is that, first new a matcher in anymatch, 2nd use the matcher to match teststring.
if teststring is path string and some path or file has dot symbol, will match failed, the example at flow:

const matcher = anymatch(["**/node_modules/**"]);
const str = "abs/node_modules/.path/file.js";
const str2 = "abs/node_modules/.file.js";
const result = matcher(str); // false
const result2 = matcher(str2); // false

then i review the source code of anymatch, and i found a solution:

const matcher = anymatch(["**/node_modules/**"], null, {dot: true});
const str = "abs/node_modules/.path/file.js";
const str2 = "abs/node_modules/.file.js";
const result = matcher(str); // true  // ts checker error
const result2 = matcher(str2); // true // ts checker error

but if this code is in ts, the ide tell me an error of checker at the line that match the test string, because anymatch/index.d.ts dosn't have this override, so we should add a comment to tell checker to ignore this line.

const matcher = anymatch(["**/node_modules/**"], null, {dot: true});
const str = "abs/node_modules/.path/file.js";
const str2 = "abs/node_modules/.file.js";
// @ts-ignore
const result = matcher(str); // true
// @ts-ignore
const result2 = matcher(str2); // true

Matchers with an opening parenthesis do not work.

Matchers with an opening parenthesis do not work.

const anymatch = require('anymatch');

console.log(anymatch('**/node_modules/**', '/absolute/path/to/node_modules/somelib/index.js')); // true

console.log(anymatch('**/node_modules(/**', '/absolute/path/to/node_modules(/somelib/index.js')); // I expect true but get false.

The only difference between the two anymatch() calls is that I added an opening parenthesis after "node_modules".

I have tried escaping the opening parenthesis with a \, but that didn't help.

Updating micromatch to 3.1.10 to prevent vulnerability

Hi,

There is vulneralibity issue with braces 2.3.0. The fix comes with braces version 2.3.1 or later. Micromatch is using braces and they have already updated their version of braces. Micromatch current version when I'm writing this issue is 3.1.10. This contains the updated version of braces. I noticed that you are currently using 3.1.4 of micromatch. Could you update Anymatch's micromatch version to 3.1.10?

More info about braces vulnerability at https://nodesecurity.io/advisories/786

Add an engine section in the package.json

It would be great if it was possible to indicate in the package.json what are the supported versions of this lib. I think right now it is node>=8 but it's not clear.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.