Gathering detailed insights and metrics for picomatch
An interesting fact about npm is that it started as a weekend project by its creator, Isaac Z. Schlueter, in 2009. It was officially launched in January 2010.
Gathering detailed insights and metrics for picomatch
An interesting fact about npm is that it started as a weekend project by its creator, Isaac Z. Schlueter, in 2009. It was officially launched in January 2010.
Blazing fast and accurate glob matcher written JavaScript, with no dependencies and full support for standard and extended Bash glob features, including braces, extglobs, POSIX brackets, and regular expressions. Used by GraphQL, Jest, Astro, Snowpack, Storybook, bulma, Serverless, fdir, Netlify, AWS Amplify, Revogrid, rollup, routify, open-wc, imba, ava, docusaurus, fast-glob, globby, chokidar, anymatch, cloudflare/miniflare, pts, and more than 5 million projects! Please follow picomatch's author: https://github.com/jonschlinkert
npm install picomatch
99.5
Supply Chain
100
Quality
83.2
Maintenance
100
Vulnerability
100
License
969 Stars
252 Commits
56 Forks
13 Watching
5 Branches
26 Contributors
Updated on 22 Nov 2024
JavaScript (100%)
Cumulative downloads
Total Downloads
Last day
8.1%
4,066,632
Compared to previous day
Last week
10%
74,644,838
Compared to previous week
Last month
7.5%
286,351,703
Compared to previous month
Last year
31.5%
2,660,909,082
Compared to previous year
6
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.
*
and ?
), globstars (**
) for nested directories, advanced globbing with extglobs, braces, and POSIX brackets, and support for escaping special characters with \
or quotes.See the library comparison to other libraries.
(TOC generated by verb using markdown-toc)
Install with npm:
1npm install --save picomatch
The main export is a function that takes a glob pattern and an options object and returns a function for matching strings.
1const pm = require('picomatch'); 2const isMatch = pm('*.js'); 3 4console.log(isMatch('abcd')); //=> false 5console.log(isMatch('a.js')); //=> true 6console.log(isMatch('a.md')); //=> false 7console.log(isMatch('a/b.js')); //=> false
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
1const picomatch = require('picomatch'); 2// picomatch(glob[, options]); 3 4const isMatch = picomatch('*.!(*a)'); 5console.log(isMatch('a.a')); //=> false 6console.log(isMatch('a.b')); //=> true
Example without node.js
For environments without node.js
, picomatch/posix
provides you a dependency-free matcher, without automatic OS detection.
1const picomatch = require('picomatch/posix'); 2// the same API, defaulting to posix paths 3const isMatch = picomatch('a/*'); 4console.log(isMatch('a\\b')); //=> false 5console.log(isMatch('a/b')); //=> true 6 7// you can still configure the matcher function to accept windows paths 8const isMatch = picomatch('a/*', { options: windows }); 9console.log(isMatch('a\\b')); //=> true 10console.log(isMatch('a/b')); //=> true
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
1const picomatch = require('picomatch'); 2// picomatch.test(input, regex[, options]); 3 4console.log(picomatch.test('foo/bar', /^(?:([^/]*?)\/([^/]*?))$/)); 5// { isMatch: true, match: [ 'foo/', 'foo', 'bar' ], output: 'foo/bar' }
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
1const picomatch = require('picomatch'); 2// picomatch.matchBase(input, glob[, options]); 3console.log(picomatch.matchBase('foo/bar.js', '*.js'); // true
Returns true if any of the given glob patterns
match the specified string
.
Params
returns
{Boolean}: Returns true if any patterns match str
Example
1const picomatch = require('picomatch'); 2// picomatch.isMatch(string, patterns[, options]); 3 4console.log(picomatch.isMatch('a.a', ['b.*', '*.a'])); //=> true 5console.log(picomatch.isMatch('a.a', 'b.*')); //=> false
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
1const picomatch = require('picomatch'); 2const result = picomatch.parse(pattern[, options]);
Scan a glob pattern to separate the pattern into segments.
Params
input
{String}: Glob pattern to scan.options
{Object}returns
{Object}: Returns an object withExample
1const picomatch = require('picomatch'); 2// picomatch.scan(input[, options]); 3 4const result = picomatch.scan('!./foo/*.js'); 5console.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 }
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
1const picomatch = require('picomatch'); 2const state = picomatch.parse('*.js'); 3// picomatch.compileRe(state[, options]); 4 5console.log(picomatch.compileRe(state)); 6//=> /^(?:(?!\.)(?=.)[^/]*?\.js)$/
Create a regular expression from the given regex source string.
Params
source
{String}: Regular expression source string.options
{Object}returns
{RegExp}Example
1const picomatch = require('picomatch'); 2// picomatch.toRegex(source[, options]); 3 4const { output } = picomatch.parse('*.js'); 5console.log(picomatch.toRegex(output)); 6//=> /^(?:(?!\.)(?=.)[^/]*?\.js)$/
The following options may be used with the main picomatch()
function or any of the methods on the picomatch API.
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 | Enable dotfile matching. By default, dotfiles are ignored unless a . is explicitly defined in the pattern, or options.dot is true |
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. |
failglob | boolean | false | Throws an error if 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 | string | 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. |
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 | Make matching case-insensitive. Equivalent to the regex i flag. Note that this option is overridden by the flags option. |
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 | boolean | 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 backslashes preceding escaped characters in the glob pattern. By default, backslashes are retained. |
unixify | boolean | undefined | Alias for posixSlashes , for backwards compatibility. |
windows | boolean | false | Also accept backslashes as the path separator. |
In addition to the main picomatch options, the following options may also be used with the .scan method.
Option | Type | Default value | Description |
---|---|---|---|
tokens | boolean | false | When true , the returned object will include an array of tokens (objects), representing each path "segment" in the scanned glob pattern |
parts | boolean | false | When true , the returned object will include an array of strings representing each path "segment" in the scanned glob pattern. This is automatically enabled when options.tokens is true |
Example
1const picomatch = require('picomatch'); 2const result = picomatch.scan('!./foo/*.js', { tokens: true }); 3console.log(result); 4// { 5// prefix: '!./', 6// input: '!./foo/*.js', 7// start: 3, 8// base: 'foo', 9// glob: '*.js', 10// isBrace: false, 11// isBracket: false, 12// isGlob: true, 13// isExtglob: false, 14// isGlobstar: false, 15// negated: true, 16// maxDepth: 2, 17// tokens: [ 18// { value: '!./', depth: 0, isGlob: false, negated: true, isPrefix: true }, 19// { value: 'foo', depth: 1, isGlob: false }, 20// { value: '*.js', depth: 1, isGlob: true } 21// ], 22// slashes: [ 2, 6 ], 23// parts: [ 'foo', '*.js' ] 24// }
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
1const fill = require('fill-range'); 2const regex = pm.makeRe('foo/{01..25}/bar', { 3 expandRange(a, b) { 4 return `(${fill(a, b, { toRegex: true })})`; 5 } 6}); 7 8console.log(regex); 9//=> /^(?:foo\/((?:0[1-9]|1[0-9]|2[0-5]))\/bar)$/ 10 11console.log(regex.test('foo/00/bar')) // false 12console.log(regex.test('foo/01/bar')) // true 13console.log(regex.test('foo/10/bar')) // true 14console.log(regex.test('foo/22/bar')) // true 15console.log(regex.test('foo/25/bar')) // true 16console.log(regex.test('foo/26/bar')) // false
Type: function
Default: undefined
Custom function for formatting strings before they're matched.
Example
1// strip leading './' from strings 2const format = str => str.replace(/^\.\//, ''); 3const isMatch = picomatch('foo/*.js', { format }); 4console.log(isMatch('./foo/bar.js')); //=> true
1const onMatch = ({ glob, regex, input, output }) => { 2 console.log({ glob, regex, input, output }); 3}; 4 5const isMatch = picomatch('*', { onMatch }); 6isMatch('foo'); 7isMatch('bar'); 8isMatch('baz');
1const onIgnore = ({ glob, regex, input, output }) => { 2 console.log({ glob, regex, input, output }); 3}; 4 5const isMatch = picomatch('*', { onIgnore, ignore: 'f*' }); 6isMatch('foo'); 7isMatch('bar'); 8isMatch('baz');
1const onResult = ({ glob, regex, input, output }) => { 2 console.log({ glob, regex, input, output }); 3}; 4 5const isMatch = picomatch('*', { onResult, ignore: 'f*' }); 6isMatch('foo'); 7isMatch('bar'); 8isMatch('baz');
Character | Description |
---|---|
* | Matches any character zero or more times, excluding path separators. Does not match path separators or hidden files or directories ("dotfiles"), unless explicitly enabled by setting the dot option to true . |
** | Matches any character zero or more times, including path separators. Note that ** will only match path separators (/ , and \\ with the windows option) when they are the only characters in a path segment. Thus, foo**/bar is equivalent to foo*/bar , and foo/a**b/bar is equivalent to foo/a*b/bar , and more than two consecutive stars in a glob path segment are regarded as a single star. Thus, foo/***/bar is equivalent to foo/*/bar . |
? | Matches any character excluding path separators one time. Does not match path separators or leading dots. |
[abc] | Matches any characters inside the brackets. For example, [abc] would match the characters a , b or c , and nothing else. |
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:
foo/bar/baz
with *
. Picomatch only matches nested directories with **
.!(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
.Pattern | Description |
---|---|
@(pattern) | Match only one consecutive occurrence of pattern |
*(pattern) | Match zero or more consecutive occurrences of pattern |
+(pattern) | Match one or more consecutive occurrences of pattern |
?(pattern) | Match zero or one consecutive occurrences of pattern |
!(pattern) | Match anything but pattern |
Examples
1const pm = require('picomatch'); 2 3// *(pattern) matches ZERO or more of "pattern" 4console.log(pm.isMatch('a', 'a*(z)')); // true 5console.log(pm.isMatch('az', 'a*(z)')); // true 6console.log(pm.isMatch('azzz', 'a*(z)')); // true 7 8// +(pattern) matches ONE or more of "pattern" 9console.log(pm.isMatch('a', 'a+(z)')); // false 10console.log(pm.isMatch('az', 'a+(z)')); // true 11console.log(pm.isMatch('azzz', 'a+(z)')); // true 12 13// supports multiple extglobs 14console.log(pm.isMatch('foo.bar', '!(foo).!(bar)')); // false 15 16// supports nested extglobs 17console.log(pm.isMatch('foo.bar', '!(!(foo)).!(!(bar))')); // true
POSIX classes are disabled by default. Enable this feature by setting the posix
option to true.
Enable POSIX bracket support
1console.log(pm.makeRe('[[:word:]]+', { posix: true })); 2//=> /^(?:(?=.)[A-Za-z0-9_]+\/?)$/
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.
Picomatch does not do brace expansion. For brace expansion and advanced matching with braces, use micromatch instead. Picomatch has very basic support for braces.
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:
1console.log(pm.makeRe('foo/bar \\(1\\)')); 2console.log(pm.makeRe('foo/bar \\(1\\)'));
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 matching (*?+ ) | ✔ | ✔ | ✔ | ✔ | - | - | - |
Advancing globbing | ✔ | ✔ | ✔ | - | - | - | - |
Brace matching | ✔ | ✔ | ✔ | - | - | ✔ | - |
Brace expansion | ✔ | ✔ | - | - | - | ✔ | - |
Extglobs | partial | ✔ | ✔ | - | ✔ | - | - |
Posix brackets | - | ✔ | ✔ | - | - | - | ✔ |
Regular expression syntax | - | ✔ | ✔ | ✔ | ✔ | - | ✔ |
File system operations | - | - | - | - | - | - | - |
Performance comparison of picomatch and minimatch.
(Pay special attention to the last three benchmarks. Minimatch freezes on long ranges.)
# .makeRe star (*)
picomatch x 4,449,159 ops/sec ±0.24% (97 runs sampled)
minimatch x 632,772 ops/sec ±0.14% (98 runs sampled)
# .makeRe star; dot=true (*)
picomatch x 3,500,079 ops/sec ±0.26% (99 runs sampled)
minimatch x 564,916 ops/sec ±0.23% (96 runs sampled)
# .makeRe globstar (**)
picomatch x 3,261,000 ops/sec ±0.27% (98 runs sampled)
minimatch x 1,664,766 ops/sec ±0.20% (100 runs sampled)
# .makeRe globstars (**/**/**)
picomatch x 3,284,469 ops/sec ±0.18% (97 runs sampled)
minimatch x 1,435,880 ops/sec ±0.34% (95 runs sampled)
# .makeRe with leading star (*.txt)
picomatch x 3,100,197 ops/sec ±0.35% (99 runs sampled)
minimatch x 428,347 ops/sec ±0.42% (94 runs sampled)
# .makeRe - basic braces ({a,b,c}*.txt)
picomatch x 443,578 ops/sec ±1.33% (89 runs sampled)
minimatch x 107,143 ops/sec ±0.35% (94 runs sampled)
# .makeRe - short ranges ({a..z}*.txt)
picomatch x 415,484 ops/sec ±0.76% (96 runs sampled)
minimatch x 14,299 ops/sec ±0.26% (96 runs sampled)
# .makeRe - medium ranges ({1..100000}*.txt)
picomatch x 395,020 ops/sec ±0.87% (89 runs sampled)
minimatch x 2 ops/sec ±4.59% (10 runs sampled)
# .makeRe - long ranges ({1..10000000}*.txt)
picomatch x 400,036 ops/sec ±0.83% (90 runs sampled)
minimatch (FATAL ERROR: Ineffective mark-compacts near heap limit Allocation failed - JavaScript heap out of memory)
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.
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 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:
1npm install && npm test
(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:
1npm install -g verbose/verb#dev verb-generate-readme && verb
Jon Schlinkert
Copyright © 2017-present, Jon Schlinkert. Released under the MIT License.
No vulnerabilities found.
Reason
no dangerous workflow patterns detected
Reason
no binaries found in the repo
Reason
license file detected
Details
Reason
0 existing vulnerabilities detected
Reason
security policy file detected
Details
Reason
SAST tool detected but not run on all commits
Details
Reason
Found 11/20 approved changesets -- score normalized to 5
Reason
0 commit(s) and 2 issue activity found in the last 90 days -- score normalized to 1
Reason
detected GitHub workflow tokens with excessive permissions
Details
Reason
dependency not pinned by hash detected -- score normalized to 0
Details
Reason
no effort to earn an OpenSSF best practices badge detected
Reason
project is not fuzzed
Details
Reason
branch protection not enabled on development/release branches
Details
Score
Last Scanned on 2024-11-18
The Open Source Security Foundation is a cross-industry collaboration to improve the security of open source software (OSS). The Scorecard provides security health metrics for open source projects.
Learn More@types/picomatch
TypeScript definitions for picomatch
globbie
Simple directory globbing using picomatch
@npmtuanmap/sed-quo-nemo-rerum
@teamteanpm2024/earum-ipsam-aspernatur
![logo](https://github.com/teamteanpm2024/earum-ipsam-aspernatur/raw/master/img/facebook_cover_photo_2_680.png)