Picomatch

Blazing fast and accurate glob matcher written JavaScript, with no dependen...

README

Picomatch

versiontest statuscoverage statusdownloads


Blazing fast and accurate glob matcher written in JavaScript.
No dependencies and full support for standard and extended Bash glob features, including braces, extglobs, POSIX brackets, and regular expressions.



Why picomatch?


Lightweight - No dependencies
Minimal - Tiny API surface. Main export is a function that takes a glob pattern and returns a matcher function.
Fast - Loads in about 2ms (that's several times faster than a single frame of a HD movie at 60fps)
Performant - Use the returned matcher function to speed up repeat matching (like when watching files)
Accurate matching - Using wildcards (` and ?), globstars (*) for nested directories, advanced globbing with extglobs, braces, and POSIX brackets, and support for escaping special characters with\` or quotes.
Well tested - Thousands of unit tests

See the library comparison to other libraries.



Table of Contents


Click to expand

- API
  .test
  .parse
  .scan
  Braces
  Author

_(TOC generated by verb using markdown-toc)_



Install


Install with npm:

  1. ```sh
  2. npm install --save picomatch
  3. ```

Usage


The main export is a function that takes a glob pattern and an options object and returns a function for matching strings.

  1. ``` js
  2. const pm = require('picomatch');
  3. const isMatch = pm('*.js');

  4. console.log(isMatch('abcd')); //=> false
  5. console.log(isMatch('a.js')); //=> true
  6. console.log(isMatch('a.md')); //=> false
  7. console.log(isMatch('a/b.js')); //=> false
  8. ```

API



Creates a matcher function from one or more glob patterns. The returned function takes a string to match as its first argument, and returns true if the string is a match. The returned matcher function also takes a boolean as the second argument that, when true, returns an object with additional information.

Params

globs {String|Array}: One or more glob patterns.
options {Object=}
returns {Function=}: Returns a matcher function.

Example

  1. ``` js
  2. const picomatch = require('picomatch');
  3. // picomatch(glob[, options]);

  4. const isMatch = picomatch('*.!(*a)');
  5. console.log(isMatch('a.a')); //=> false
  6. console.log(isMatch('a.b')); //=> true
  7. ```


Test input with the given regex. This is used by the main picomatch() function to test the input string.

Params

input {String}: String to test.
regex {RegExp}
returns {Object}: Returns an object with matching info.

Example

  1. ``` js
  2. const picomatch = require('picomatch');
  3. // picomatch.test(input, regex[, options]);

  4. console.log(picomatch.test('foo/bar', /^(?:([^/]*?)\/([^/]*?))$/));
  5. // { isMatch: true, match: [ 'foo/', 'foo', 'bar' ], output: 'foo/bar' }
  6. ```


Match the basename of a filepath.

Params

input {String}: String to test.
glob {RegExp|String}: Glob pattern or regex created by .makeRe.
returns {Boolean}

Example

  1. ``` js
  2. const picomatch = require('picomatch');
  3. // picomatch.matchBase(input, glob[, options]);
  4. console.log(picomatch.matchBase('foo/bar.js', '*.js'); // true
  5. ```


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

Params

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

Example

  1. ``` js
  2. const picomatch = require('picomatch');
  3. // picomatch.isMatch(string, patterns[, options]);

  4. console.log(picomatch.isMatch('a.a', ['b.*', '*.a'])); //=> true
  5. console.log(picomatch.isMatch('a.a', 'b.*')); //=> false
  6. ```


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

Params

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

Example

  1. ``` js
  2. const picomatch = require('picomatch');
  3. const result = picomatch.parse(pattern[, options]);
  4. ```


Scan a glob pattern to separate the pattern into segments.

Params

input {String}: Glob pattern to scan.
options {Object}
returns {Object}: Returns an object with

Example

  1. ``` js
  2. const picomatch = require('picomatch');
  3. // picomatch.scan(input[, options]);

  4. const result = picomatch.scan('!./foo/*.js');
  5. console.log(result);
  6. { prefix: '!./',
  7.   input: '!./foo/*.js',
  8.   start: 3,
  9.   base: 'foo',
  10.   glob: '*.js',
  11.   isBrace: false,
  12.   isBracket: false,
  13.   isGlob: true,
  14.   isExtglob: false,
  15.   isGlobstar: false,
  16.   negated: true }
  17. ```


Compile a regular expression from the state object returned by the
parse() method.

Params

state {Object}
options {Object}
returnOutput {Boolean}: Intended for implementors, this argument allows you to return the raw output from the parser.
returnState {Boolean}: Adds the state to a state property on the returned regex. Useful for implementors and debugging.
returns {RegExp}


Create a regular expression from a parsed glob pattern.

Params

state {String}: The object returned from the .parse method.
options {Object}
returnOutput {Boolean}: Implementors may use this argument to return the compiled output, instead of a regular expression. This is not exposed on the options to prevent end-users from mutating the result.
returnState {Boolean}: Implementors may use this argument to return the state from the parsed glob with the returned regular expression.
returns {RegExp}: Returns a regex created from the given pattern.

Example

  1. ``` js
  2. const picomatch = require('picomatch');
  3. const state = picomatch.parse('*.js');
  4. // picomatch.compileRe(state[, options]);

  5. console.log(picomatch.compileRe(state));
  6. //=> /^(?:(?!\.)(?=.)[^/]*?\.js)$/
  7. ```


Create a regular expression from the given regex source string.

Params

source {String}: Regular expression source string.
options {Object}
returns {RegExp}

Example

  1. ``` js
  2. const picomatch = require('picomatch');
  3. // picomatch.toRegex(source[, options]);

  4. const { output } = picomatch.parse('*.js');
  5. console.log(picomatch.toRegex(output));
  6. //=> /^(?:(?!\.)(?=.)[^/]*?\.js)$/
  7. ```

Options


Picomatch options


The following options may be used with the main picomatch() function or any of the methods on the picomatch API.

**Option****Type****Default**Description**
------------
`basename``boolean``false`If
`bash``boolean``false`Follow
`capture``boolean``undefined`Return
`contains``boolean``undefined`Allows
`cwd``string``process.cwd()`Current
`debug``boolean``undefined`Debug
`dot``boolean``false`Enable
`expandRange``function``undefined`Custom
`failglob``boolean``false`Throws
`fastpaths``boolean``true`To
`flags``string``undefined`Regex
[format](#optionsformat)`function``undefined`Custom
`ignore``array\|string``undefined`One
`keepQuotes``boolean``false`Retain
`literalBrackets``boolean``undefined`When
`matchBase``boolean``false`Alias
`maxLength``boolean``65536`Limit
`nobrace``boolean``false`Disable
`nobracket``boolean``undefined`Disable
`nocase``boolean``false`Make
`nodupes``boolean``true`Deprecated,
`noext``boolean``false`Alias
`noextglob``boolean``false`Disable
`noglobstar``boolean``false`Disable
`nonegate``boolean``false`Disable
`noquantifiers``boolean``false`Disable
[onIgnore](#optionsonIgnore)`function``undefined`Function
[onMatch](#optionsonMatch)`function``undefined`Function
[onResult](#optionsonResult)`function``undefined`Function
`posix``boolean``false`Support
`posixSlashes``boolean``undefined`Convert
`prepend``boolean``undefined`String
`regex``boolean``false`Use
`strictBrackets``boolean``undefined`Throw
`strictSlashes``boolean``undefined`When
`unescape``boolean``undefined`Remove
`unixify``boolean``undefined`Alias

picomatch has automatic detection for regex positive and negative lookbehinds. If the pattern contains a negative lookbehind, you must be using Node.js >= 8.10 or else picomatch will throw an error.

Scan Options


In addition to the main picomatch options, the following options may also be used with the .scan method.

**Option****Type****Default**Description**
------------
`tokens``boolean``false`When
`parts``boolean``false`When

Example

  1. ``` js
  2. const picomatch = require('picomatch');
  3. const result = picomatch.scan('!./foo/*.js', { tokens: true });
  4. console.log(result);
  5. // {
  6. //   prefix: '!./',
  7. //   input: '!./foo/*.js',
  8. //   start: 3,
  9. //   base: 'foo',
  10. //   glob: '*.js',
  11. //   isBrace: false,
  12. //   isBracket: false,
  13. //   isGlob: true,
  14. //   isExtglob: false,
  15. //   isGlobstar: false,
  16. //   negated: true,
  17. //   maxDepth: 2,
  18. //   tokens: [
  19. //     { value: '!./', depth: 0, isGlob: false, negated: true, isPrefix: true },
  20. //     { value: 'foo', depth: 1, isGlob: false },
  21. //     { value: '*.js', depth: 1, isGlob: true }
  22. //   ],
  23. //   slashes: [ 2, 6 ],
  24. //   parts: [ 'foo', '*.js' ]
  25. // }
  26. ```

Options Examples


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 folder

  1. ``` js
  2. const fill = require('fill-range');
  3. const regex = pm.makeRe('foo/{01..25}/bar', {
  4.   expandRange(a, b) {
  5.     return `(${fill(a, b, { toRegex: true })})`;
  6.   }
  7. });

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

  10. console.log(regex.test('foo/00/bar'))  // false
  11. console.log(regex.test('foo/01/bar'))  // true
  12. console.log(regex.test('foo/10/bar')) // true
  13. console.log(regex.test('foo/22/bar')) // true
  14. console.log(regex.test('foo/25/bar')) // true
  15. console.log(regex.test('foo/26/bar')) // false
  16. ```

options.format


Type: function

Default: undefined

Custom function for formatting strings before they're matched.

Example

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

options.onMatch


  1. ``` js
  2. const onMatch = ({ glob, regex, input, output }) => {
  3.   console.log({ glob, regex, input, output });
  4. };

  5. const isMatch = picomatch('*', { onMatch });
  6. isMatch('foo');
  7. isMatch('bar');
  8. isMatch('baz');
  9. ```

options.onIgnore


  1. ``` js
  2. const onIgnore = ({ glob, regex, input, output }) => {
  3.   console.log({ glob, regex, input, output });
  4. };

  5. const isMatch = picomatch('*', { onIgnore, ignore: 'f*' });
  6. isMatch('foo');
  7. isMatch('bar');
  8. isMatch('baz');
  9. ```

options.onResult


  1. ``` js
  2. const onResult = ({ glob, regex, input, output }) => {
  3.   console.log({ glob, regex, input, output });
  4. };

  5. const isMatch = picomatch('*', { onResult, ignore: 'f*' });
  6. isMatch('foo');
  7. isMatch('bar');
  8. isMatch('baz');
  9. ```



Globbing features


Basic globbing (Wildcard matching)
Advanced globbing (extglobs, posix brackets, brace matching)

Basic globbing


**Character****Description**
------
`*`Matches
`**`Matches
`?`Matches
`[abc]`Matches

Matching behavior vs. Bash


Picomatch's matching features and expected results in unit tests are based on Bash's unit tests and the Bash 4.3 specification, with the following exceptions:

Bash will match foo/bar/baz with `. Picomatch only matches nested directories with *`.
Bash greedily matches with negated extglobs. For example, Bash 4.3 says that `!(foo) should match foo and foobar, since the trailing bracktracks to match the preceding pattern. This is very memory-inefficient, and IMHO, also incorrect. Picomatch would return false for both foo and foobar`.

Advanced globbing



Extglobs


**Pattern****Description**
------
`@(pattern)`Match
`*(pattern)`Match
`+(pattern)`Match
`?(pattern)`Match
`!(pattern)`Match

Examples

  1. ``` js
  2. const pm = require('picomatch');

  3. // *(pattern) matches ZERO or more of "pattern"
  4. console.log(pm.isMatch('a', 'a*(z)')); // true
  5. console.log(pm.isMatch('az', 'a*(z)')); // true
  6. console.log(pm.isMatch('azzz', 'a*(z)')); // true

  7. // +(pattern) matches ONE or more of "pattern"
  8. console.log(pm.isMatch('a', 'a+(z)')); // false
  9. console.log(pm.isMatch('az', 'a+(z)')); // true
  10. console.log(pm.isMatch('azzz', 'a+(z)')); // true

  11. // supports multiple extglobs
  12. console.log(pm.isMatch('foo.bar', '!(foo).!(bar)')); // false

  13. // supports nested extglobs
  14. console.log(pm.isMatch('foo.bar', '!(!(foo)).!(!(bar))')); // true
  15. ```

POSIX brackets


POSIX classes are disabled by default. Enable this feature by setting the posix option to true.

Enable POSIX bracket support

  1. ``` js
  2. console.log(pm.makeRe('[[:word:]]+', { posix: true }));
  3. //=> /^(?:(?=.)[A-Za-z0-9_]+\/?)$/
  4. ```

Supported POSIX classes

The following named POSIX bracket expressions are supported:

[:alnum:] - Alphanumeric characters, equ [a-zA-Z0-9]
[:alpha:] - Alphabetical characters, equivalent to [a-zA-Z].
[:ascii:] - ASCII characters, equivalent to [\\x00-\\x7F].
[:blank:] - Space and tab characters, equivalent to [ \\t].
[:cntrl:] - Control characters, equivalent to [\\x00-\\x1F\\x7F].
[:digit:] - Numerical digits, equivalent to [0-9].
[:graph:] - Graph characters, equivalent to [\\x21-\\x7E].
[:lower:] - Lowercase letters, equivalent to [a-z].
[:print:] - Print characters, equivalent to [\\x20-\\x7E ].
* `[:punct:]` - Punctuation and symbols, equivalent to `[\\-!"#$%&\'()\\*+,./:;<=>?@[\\]^_`{|}~]`.
[:space:] - Extended space characters, equivalent to [ \\t\\r\\n\\v\\f].
[:upper:] - Uppercase letters, equivalent to [A-Z].
[:word:] -  Word characters (letters, numbers and underscores), equivalent to [A-Za-z0-9_].
[:xdigit:] - Hexadecimal digits, equivalent to [A-Fa-f0-9].

See the Bash Reference Manual for more information.

Braces


Picomatch does not do brace expansion. For brace expansion and advanced matching with braces, use micromatch instead. Picomatch has very basic support for braces.

Matching special characters as literals


If you wish to match the following special characters in a filepath, and you want to use these characters in your glob pattern, they must be escaped with backslashes or quotes:

Special Characters

Some characters that are used for matching in regular expressions are also regarded as valid file path characters on some platforms.

To match any of the following characters as literals: `$^*+?()[]

Examples:

  1. ``` js
  2. console.log(pm.makeRe('foo/bar \\(1\\)'));
  3. console.log(pm.makeRe('foo/bar \\(1\\)'));
  4. ```



Library Comparisons


The following table shows which features are supported by minimatch, micromatch, picomatch, nanomatch, extglob, braces, and expand-brackets.

**Feature**`minimatch``micromatch``picomatch``nanomatch``extglob``braces``expand-brackets`
------------------------
Wildcard---
Advancing----
Brace---
Brace----
Extglobspartial---
Posix----
Regular--
File-------



Benchmarks


Performance comparison of picomatch and minimatch.

  1. ```
  2. # .makeRe star
  3.   picomatch x 1,993,050 ops/sec ±0.51% (91 runs sampled)
  4.   minimatch x 627,206 ops/sec ±1.96% (87 runs sampled))

  5. # .makeRe star; dot=true
  6.   picomatch x 1,436,640 ops/sec ±0.62% (91 runs sampled)
  7.   minimatch x 525,876 ops/sec ±0.60% (88 runs sampled)

  8. # .makeRe globstar
  9.   picomatch x 1,592,742 ops/sec ±0.42% (90 runs sampled)
  10.   minimatch x 962,043 ops/sec ±1.76% (91 runs sampled)d)

  11. # .makeRe globstars
  12.   picomatch x 1,615,199 ops/sec ±0.35% (94 runs sampled)
  13.   minimatch x 477,179 ops/sec ±1.33% (91 runs sampled)

  14. # .makeRe with leading star
  15.   picomatch x 1,220,856 ops/sec ±0.40% (92 runs sampled)
  16.   minimatch x 453,564 ops/sec ±1.43% (94 runs sampled)

  17. # .makeRe - basic braces
  18.   picomatch x 392,067 ops/sec ±0.70% (90 runs sampled)
  19.   minimatch x 99,532 ops/sec ±2.03% (87 runs sampled))
  20. ```



Philosophies


The goal of this library is to be blazing fast, without compromising on accuracy.

Accuracy

The number one of goal of this library is accuracy. However, it's not unusual for different glob implementations to have different rules for matching behavior, even with simple wildcard matching. It gets increasingly more complicated when combinations of different features are combined, like when extglobs are combined with globstars, braces, slashes, and so on: `!(*/{a,b,/c})`.

Thus, given that there is no canonical glob specification to use as a single source of truth when differences of opinion arise regarding behavior, sometimes we have to implement our best judgement and rely on feedback from users to make improvements.

Performance

Although this library performs well in benchmarks, and in most cases it's faster than other popular libraries we benchmarked against, we will always choose accuracy over performance. It's not helpful to anyone if our library is faster at returning the wrong answer.



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:

  1. ```sh
  2. npm install && npm test
  3. ```

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:

  1. ```sh
  2. npm install -g verbose/verb#dev verb-generate-readme && verb
  3. ```


Author


Jon Schlinkert


License


Copyright © 2017-present, Jon Schlinkert.
Released under the MIT License.