You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1010 lines
38 KiB

2 years ago
  1. # micromatch [![NPM version](https://img.shields.io/npm/v/micromatch.svg?style=flat)](https://www.npmjs.com/package/micromatch) [![NPM monthly downloads](https://img.shields.io/npm/dm/micromatch.svg?style=flat)](https://npmjs.org/package/micromatch) [![NPM total downloads](https://img.shields.io/npm/dt/micromatch.svg?style=flat)](https://npmjs.org/package/micromatch) [![Tests](https://github.com/micromatch/micromatch/actions/workflows/test.yml/badge.svg)](https://github.com/micromatch/micromatch/actions/workflows/test.yml)
  2. > Glob matching for javascript/node.js. A replacement and faster alternative to minimatch and multimatch.
  3. Please consider following this project's author, [Jon Schlinkert](https://github.com/jonschlinkert), and consider starring the project to show your :heart: and support.
  4. ## Table of Contents
  5. <details>
  6. <summary><strong>Details</strong></summary>
  7. - [Install](#install)
  8. - [Quickstart](#quickstart)
  9. - [Why use micromatch?](#why-use-micromatch)
  10. * [Matching features](#matching-features)
  11. - [Switching to micromatch](#switching-to-micromatch)
  12. * [From minimatch](#from-minimatch)
  13. * [From multimatch](#from-multimatch)
  14. - [API](#api)
  15. - [Options](#options)
  16. - [Options Examples](#options-examples)
  17. * [options.basename](#optionsbasename)
  18. * [options.bash](#optionsbash)
  19. * [options.expandRange](#optionsexpandrange)
  20. * [options.format](#optionsformat)
  21. * [options.ignore](#optionsignore)
  22. * [options.matchBase](#optionsmatchbase)
  23. * [options.noextglob](#optionsnoextglob)
  24. * [options.nonegate](#optionsnonegate)
  25. * [options.noglobstar](#optionsnoglobstar)
  26. * [options.nonull](#optionsnonull)
  27. * [options.nullglob](#optionsnullglob)
  28. * [options.onIgnore](#optionsonignore)
  29. * [options.onMatch](#optionsonmatch)
  30. * [options.onResult](#optionsonresult)
  31. * [options.posixSlashes](#optionsposixslashes)
  32. * [options.unescape](#optionsunescape)
  33. - [Extended globbing](#extended-globbing)
  34. * [Extglobs](#extglobs)
  35. * [Braces](#braces)
  36. * [Regex character classes](#regex-character-classes)
  37. * [Regex groups](#regex-groups)
  38. * [POSIX bracket expressions](#posix-bracket-expressions)
  39. - [Notes](#notes)
  40. * [Bash 4.3 parity](#bash-43-parity)
  41. * [Backslashes](#backslashes)
  42. - [Benchmarks](#benchmarks)
  43. * [Running benchmarks](#running-benchmarks)
  44. * [Latest results](#latest-results)
  45. - [Contributing](#contributing)
  46. - [About](#about)
  47. </details>
  48. ## Install
  49. Install with [npm](https://www.npmjs.com/) (requires [Node.js](https://nodejs.org/en/) >=8.6):
  50. ```sh
  51. $ npm install --save micromatch
  52. ```
  53. ## Quickstart
  54. ```js
  55. const micromatch = require('micromatch');
  56. // micromatch(list, patterns[, options]);
  57. ```
  58. The [main export](#micromatch) takes a list of strings and one or more glob patterns:
  59. ```js
  60. console.log(micromatch(['foo', 'bar', 'baz', 'qux'], ['f*', 'b*'])) //=> ['foo', 'bar', 'baz']
  61. console.log(micromatch(['foo', 'bar', 'baz', 'qux'], ['*', '!b*'])) //=> ['foo', 'qux']
  62. ```
  63. Use [.isMatch()](#ismatch) to for boolean matching:
  64. ```js
  65. console.log(micromatch.isMatch('foo', 'f*')) //=> true
  66. console.log(micromatch.isMatch('foo', ['b*', 'f*'])) //=> true
  67. ```
  68. [Switching](#switching-to-micromatch) from minimatch and multimatch is easy!
  69. <br>
  70. ## Why use micromatch?
  71. > micromatch is a [replacement](#switching-to-micromatch) for minimatch and multimatch
  72. * Supports all of the same matching features as [minimatch](https://github.com/isaacs/minimatch) and [multimatch](https://github.com/sindresorhus/multimatch)
  73. * 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.
  74. * **Fast & Performant** - Loads in about 5ms and performs [fast matches](#benchmarks).
  75. * **Glob matching** - Using wildcards (`*` and `?`), globstars (`**`) for nested directories
  76. * **[Advanced globbing](#extended-globbing)** - Supports [extglobs](#extglobs), [braces](#braces-1), and [POSIX brackets](#posix-bracket-expressions), and support for escaping special characters with `\` or quotes.
  77. * **Accurate** - Covers more scenarios [than minimatch](https://github.com/yarnpkg/yarn/pull/3339)
  78. * **Well tested** - More than 5,000 [test assertions](./test)
  79. * **Windows support** - More reliable windows support than minimatch and multimatch.
  80. * **[Safe](https://github.com/micromatch/braces#braces-is-safe)** - Micromatch is not subject to DoS with brace patterns like minimatch and multimatch.
  81. ### Matching features
  82. * Support for multiple glob patterns (no need for wrappers like multimatch)
  83. * Wildcards (`**`, `*.js`)
  84. * Negation (`'!a/*.js'`, `'*!(b).js'`)
  85. * [extglobs](#extglobs) (`+(x|y)`, `!(a|b)`)
  86. * [POSIX character classes](#posix-bracket-expressions) (`[[:alpha:][:digit:]]`)
  87. * [brace expansion](https://github.com/micromatch/braces) (`foo/{1..5}.md`, `bar/{a,b,c}.js`)
  88. * regex character classes (`foo-[1-5].js`)
  89. * regex logical "or" (`foo/(abc|xyz).js`)
  90. You can mix and match these features to create whatever patterns you need!
  91. ## Switching to micromatch
  92. _(There is one notable difference between micromatch and minimatch in regards to how backslashes are handled. See [the notes about backslashes](#backslashes) for more information.)_
  93. ### From minimatch
  94. Use [micromatch.isMatch()](#ismatch) instead of `minimatch()`:
  95. ```js
  96. console.log(micromatch.isMatch('foo', 'b*')); //=> false
  97. ```
  98. Use [micromatch.match()](#match) instead of `minimatch.match()`:
  99. ```js
  100. console.log(micromatch.match(['foo', 'bar'], 'b*')); //=> 'bar'
  101. ```
  102. ### From multimatch
  103. Same signature:
  104. ```js
  105. console.log(micromatch(['foo', 'bar', 'baz'], ['f*', '*z'])); //=> ['foo', 'baz']
  106. ```
  107. ## API
  108. **Params**
  109. * `list` **{String|Array<string>}**: List of strings to match.
  110. * `patterns` **{String|Array<string>}**: One or more glob patterns to use for matching.
  111. * `options` **{Object}**: See available [options](#options)
  112. * `returns` **{Array}**: Returns an array of matches
  113. **Example**
  114. ```js
  115. const mm = require('micromatch');
  116. // mm(list, patterns[, options]);
  117. console.log(mm(['a.js', 'a.txt'], ['*.js']));
  118. //=> [ 'a.js' ]
  119. ```
  120. ### [.matcher](index.js#L104)
  121. 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.
  122. **Params**
  123. * `pattern` **{String}**: Glob pattern
  124. * `options` **{Object}**
  125. * `returns` **{Function}**: Returns a matcher function.
  126. **Example**
  127. ```js
  128. const mm = require('micromatch');
  129. // mm.matcher(pattern[, options]);
  130. const isMatch = mm.matcher('*.!(*a)');
  131. console.log(isMatch('a.a')); //=> false
  132. console.log(isMatch('a.b')); //=> true
  133. ```
  134. ### [.isMatch](index.js#L123)
  135. Returns true if **any** of the given glob `patterns` match the specified `string`.
  136. **Params**
  137. * `str` **{String}**: The string to test.
  138. * `patterns` **{String|Array}**: One or more glob patterns to use for matching.
  139. * `[options]` **{Object}**: See available [options](#options).
  140. * `returns` **{Boolean}**: Returns true if any patterns match `str`
  141. **Example**
  142. ```js
  143. const mm = require('micromatch');
  144. // mm.isMatch(string, patterns[, options]);
  145. console.log(mm.isMatch('a.a', ['b.*', '*.a'])); //=> true
  146. console.log(mm.isMatch('a.a', 'b.*')); //=> false
  147. ```
  148. ### [.not](index.js#L148)
  149. Returns a list of strings that _**do not match any**_ of the given `patterns`.
  150. **Params**
  151. * `list` **{Array}**: Array of strings to match.
  152. * `patterns` **{String|Array}**: One or more glob pattern to use for matching.
  153. * `options` **{Object}**: See available [options](#options) for changing how matches are performed
  154. * `returns` **{Array}**: Returns an array of strings that **do not match** the given patterns.
  155. **Example**
  156. ```js
  157. const mm = require('micromatch');
  158. // mm.not(list, patterns[, options]);
  159. console.log(mm.not(['a.a', 'b.b', 'c.c'], '*.a'));
  160. //=> ['b.b', 'c.c']
  161. ```
  162. ### [.contains](index.js#L188)
  163. Returns true if the given `string` contains the given pattern. Similar to [.isMatch](#isMatch) but the pattern can match any part of the string.
  164. **Params**
  165. * `str` **{String}**: The string to match.
  166. * `patterns` **{String|Array}**: Glob pattern to use for matching.
  167. * `options` **{Object}**: See available [options](#options) for changing how matches are performed
  168. * `returns` **{Boolean}**: Returns true if any of the patterns matches any part of `str`.
  169. **Example**
  170. ```js
  171. var mm = require('micromatch');
  172. // mm.contains(string, pattern[, options]);
  173. console.log(mm.contains('aa/bb/cc', '*b'));
  174. //=> true
  175. console.log(mm.contains('aa/bb/cc', '*d'));
  176. //=> false
  177. ```
  178. ### [.matchKeys](index.js#L230)
  179. Filter the keys of the given object with the given `glob` pattern and `options`. Does not attempt to match nested keys. If you need this feature, use [glob-object](https://github.com/jonschlinkert/glob-object) instead.
  180. **Params**
  181. * `object` **{Object}**: The object with keys to filter.
  182. * `patterns` **{String|Array}**: One or more glob patterns to use for matching.
  183. * `options` **{Object}**: See available [options](#options) for changing how matches are performed
  184. * `returns` **{Object}**: Returns an object with only keys that match the given patterns.
  185. **Example**
  186. ```js
  187. const mm = require('micromatch');
  188. // mm.matchKeys(object, patterns[, options]);
  189. const obj = { aa: 'a', ab: 'b', ac: 'c' };
  190. console.log(mm.matchKeys(obj, '*b'));
  191. //=> { ab: 'b' }
  192. ```
  193. ### [.some](index.js#L259)
  194. Returns true if some of the strings in the given `list` match any of the given glob `patterns`.
  195. **Params**
  196. * `list` **{String|Array}**: The string or array of strings to test. Returns as soon as the first match is found.
  197. * `patterns` **{String|Array}**: One or more glob patterns to use for matching.
  198. * `options` **{Object}**: See available [options](#options) for changing how matches are performed
  199. * `returns` **{Boolean}**: Returns true if any `patterns` matches any of the strings in `list`
  200. **Example**
  201. ```js
  202. const mm = require('micromatch');
  203. // mm.some(list, patterns[, options]);
  204. console.log(mm.some(['foo.js', 'bar.js'], ['*.js', '!foo.js']));
  205. // true
  206. console.log(mm.some(['foo.js'], ['*.js', '!foo.js']));
  207. // false
  208. ```
  209. ### [.every](index.js#L295)
  210. Returns true if every string in the given `list` matches any of the given glob `patterns`.
  211. **Params**
  212. * `list` **{String|Array}**: The string or array of strings to test.
  213. * `patterns` **{String|Array}**: One or more glob patterns to use for matching.
  214. * `options` **{Object}**: See available [options](#options) for changing how matches are performed
  215. * `returns` **{Boolean}**: Returns true if all `patterns` matches all of the strings in `list`
  216. **Example**
  217. ```js
  218. const mm = require('micromatch');
  219. // mm.every(list, patterns[, options]);
  220. console.log(mm.every('foo.js', ['foo.js']));
  221. // true
  222. console.log(mm.every(['foo.js', 'bar.js'], ['*.js']));
  223. // true
  224. console.log(mm.every(['foo.js', 'bar.js'], ['*.js', '!foo.js']));
  225. // false
  226. console.log(mm.every(['foo.js'], ['*.js', '!foo.js']));
  227. // false
  228. ```
  229. ### [.all](index.js#L334)
  230. Returns true if **all** of the given `patterns` match the specified string.
  231. **Params**
  232. * `str` **{String|Array}**: The string to test.
  233. * `patterns` **{String|Array}**: One or more glob patterns to use for matching.
  234. * `options` **{Object}**: See available [options](#options) for changing how matches are performed
  235. * `returns` **{Boolean}**: Returns true if any patterns match `str`
  236. **Example**
  237. ```js
  238. const mm = require('micromatch');
  239. // mm.all(string, patterns[, options]);
  240. console.log(mm.all('foo.js', ['foo.js']));
  241. // true
  242. console.log(mm.all('foo.js', ['*.js', '!foo.js']));
  243. // false
  244. console.log(mm.all('foo.js', ['*.js', 'foo.js']));
  245. // true
  246. console.log(mm.all('foo.js', ['*.js', 'f*', '*o*', '*o.js']));
  247. // true
  248. ```
  249. ### [.capture](index.js#L361)
  250. Returns an array of matches captured by `pattern` in `string, or`null` if the pattern did not match.
  251. **Params**
  252. * `glob` **{String}**: Glob pattern to use for matching.
  253. * `input` **{String}**: String to match
  254. * `options` **{Object}**: See available [options](#options) for changing how matches are performed
  255. * `returns` **{Array|null}**: Returns an array of captures if the input matches the glob pattern, otherwise `null`.
  256. **Example**
  257. ```js
  258. const mm = require('micromatch');
  259. // mm.capture(pattern, string[, options]);
  260. console.log(mm.capture('test/*.js', 'test/foo.js'));
  261. //=> ['foo']
  262. console.log(mm.capture('test/*.js', 'foo/bar.css'));
  263. //=> null
  264. ```
  265. ### [.makeRe](index.js#L387)
  266. Create a regular expression from the given glob `pattern`.
  267. **Params**
  268. * `pattern` **{String}**: A glob pattern to convert to regex.
  269. * `options` **{Object}**
  270. * `returns` **{RegExp}**: Returns a regex created from the given pattern.
  271. **Example**
  272. ```js
  273. const mm = require('micromatch');
  274. // mm.makeRe(pattern[, options]);
  275. console.log(mm.makeRe('*.js'));
  276. //=> /^(?:(\.[\\\/])?(?!\.)(?=.)[^\/]*?\.js)$/
  277. ```
  278. ### [.scan](index.js#L403)
  279. Scan a glob pattern to separate the pattern into segments. Used by the [split](#split) method.
  280. **Params**
  281. * `pattern` **{String}**
  282. * `options` **{Object}**
  283. * `returns` **{Object}**: Returns an object with
  284. **Example**
  285. ```js
  286. const mm = require('micromatch');
  287. const state = mm.scan(pattern[, options]);
  288. ```
  289. ### [.parse](index.js#L419)
  290. Parse a glob pattern to create the source string for a regular expression.
  291. **Params**
  292. * `glob` **{String}**
  293. * `options` **{Object}**
  294. * `returns` **{Object}**: Returns an object with useful properties and output to be used as regex source string.
  295. **Example**
  296. ```js
  297. const mm = require('micromatch');
  298. const state = mm.parse(pattern[, options]);
  299. ```
  300. ### [.braces](index.js#L446)
  301. Process the given brace `pattern`.
  302. **Params**
  303. * `pattern` **{String}**: String with brace pattern to process.
  304. * `options` **{Object}**: Any [options](#options) to change how expansion is performed. See the [braces](https://github.com/micromatch/braces) library for all available options.
  305. * `returns` **{Array}**
  306. **Example**
  307. ```js
  308. const { braces } = require('micromatch');
  309. console.log(braces('foo/{a,b,c}/bar'));
  310. //=> [ 'foo/(a|b|c)/bar' ]
  311. console.log(braces('foo/{a,b,c}/bar', { expand: true }));
  312. //=> [ 'foo/a/bar', 'foo/b/bar', 'foo/c/bar' ]
  313. ```
  314. ## Options
  315. | **Option** | **Type** | **Default value** | **Description** |
  316. | --- | --- | --- | --- |
  317. | `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`. |
  318. | `bash` | `boolean` | `false` | Follow bash matching rules more strictly - disallows backslashes as escape characters, and treats single stars as globstars (`**`). |
  319. | `capture` | `boolean` | `undefined` | Return regex matches in supporting methods. |
  320. | `contains` | `boolean` | `undefined` | Allows glob to match any part of the given string(s). |
  321. | `cwd` | `string` | `process.cwd()` | Current working directory. Used by `picomatch.split()` |
  322. | `debug` | `boolean` | `undefined` | Debug regular expressions when an error is thrown. |
  323. | `dot` | `boolean` | `false` | Match dotfiles. Otherwise dotfiles are ignored unless a `.` is explicitly defined in the pattern. |
  324. | `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. |
  325. | `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. |
  326. | `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`. |
  327. | `flags` | `boolean` | `undefined` | Regex flags to use in the generated regex. If defined, the `nocase` option will be overridden. |
  328. | [format](#optionsformat) | `function` | `undefined` | Custom function for formatting the returned string. This is useful for removing leading slashes, converting Windows paths to Posix paths, etc. |
  329. | `ignore` | `array\|string` | `undefined` | One or more glob patterns for excluding strings that should not be matched from the result. |
  330. | `keepQuotes` | `boolean` | `false` | Retain quotes in the generated regex, since quotes may also be used as an alternative to backslashes. |
  331. | `literalBrackets` | `boolean` | `undefined` | When `true`, brackets in the glob pattern will be escaped so that only literal brackets will be matched. |
  332. | `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. |
  333. | `matchBase` | `boolean` | `false` | Alias for `basename` |
  334. | `maxLength` | `boolean` | `65536` | Limit the max length of the input string. An error is thrown if the input string is longer than this value. |
  335. | `nobrace` | `boolean` | `false` | Disable brace matching, so that `{a,b}` and `{1..3}` would be treated as literal characters. |
  336. | `nobracket` | `boolean` | `undefined` | Disable matching with regex brackets. |
  337. | `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. |
  338. | `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. |
  339. | `noext` | `boolean` | `false` | Alias for `noextglob` |
  340. | `noextglob` | `boolean` | `false` | Disable support for matching with [extglobs](#extglobs) (like `+(a\|b)`) |
  341. | `noglobstar` | `boolean` | `false` | Disable support for matching nested directories with globstars (`**`) |
  342. | `nonegate` | `boolean` | `false` | Disable support for negating with leading `!` |
  343. | `noquantifiers` | `boolean` | `false` | Disable support for regex quantifiers (like `a{1,2}`) and treat them as brace patterns to be expanded. |
  344. | [onIgnore](#optionsonIgnore) | `function` | `undefined` | Function to be called on ignored items. |
  345. | [onMatch](#optionsonMatch) | `function` | `undefined` | Function to be called on matched items. |
  346. | [onResult](#optionsonResult) | `function` | `undefined` | Function to be called on all items, regardless of whether or not they are matched or ignored. |
  347. | `posix` | `boolean` | `false` | Support [POSIX character classes](#posix-bracket-expressions) ("posix brackets"). |
  348. | `posixSlashes` | `boolean` | `undefined` | Convert all slashes in file paths to forward slashes. This does not convert slashes in the glob pattern itself |
  349. | `prepend` | `string` | `undefined` | String to prepend to the generated regex used for matching. |
  350. | `regex` | `boolean` | `false` | Use regular expression rules for `+` (instead of matching literal `+`), and for stars that follow closing parentheses or brackets (as in `)*` and `]*`). |
  351. | `strictBrackets` | `boolean` | `undefined` | Throw an error if brackets, braces, or parens are imbalanced. |
  352. | `strictSlashes` | `boolean` | `undefined` | When true, picomatch won't match trailing slashes with single stars. |
  353. | `unescape` | `boolean` | `undefined` | Remove preceding backslashes from escaped glob characters before creating the regular expression to perform matches. |
  354. | `unixify` | `boolean` | `undefined` | Alias for `posixSlashes`, for backwards compatitibility. |
  355. ## Options Examples
  356. ### options.basename
  357. Allow glob patterns without slashes to match a file path based on its basename. Same behavior as [minimatch](https://github.com/isaacs/minimatch) option `matchBase`.
  358. **Type**: `Boolean`
  359. **Default**: `false`
  360. **Example**
  361. ```js
  362. micromatch(['a/b.js', 'a/c.md'], '*.js');
  363. //=> []
  364. micromatch(['a/b.js', 'a/c.md'], '*.js', { basename: true });
  365. //=> ['a/b.js']
  366. ```
  367. ### options.bash
  368. 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.
  369. **Type**: `Boolean`
  370. **Default**: `true`
  371. **Example**
  372. ```js
  373. const files = ['abc', 'ajz'];
  374. console.log(micromatch(files, '[a-c]*'));
  375. //=> ['abc', 'ajz']
  376. console.log(micromatch(files, '[a-c]*', { bash: false }));
  377. ```
  378. ### options.expandRange
  379. **Type**: `function`
  380. **Default**: `undefined`
  381. Custom function for expanding ranges in brace patterns. The [fill-range](https://github.com/jonschlinkert/fill-range) library is ideal for this purpose, or you can use custom code to do whatever you need.
  382. **Example**
  383. The following example shows how to create a glob that matches a numeric folder name between `01` and `25`, with leading zeros.
  384. ```js
  385. const fill = require('fill-range');
  386. const regex = micromatch.makeRe('foo/{01..25}/bar', {
  387. expandRange(a, b) {
  388. return `(${fill(a, b, { toRegex: true })})`;
  389. }
  390. });
  391. console.log(regex)
  392. //=> /^(?:foo\/((?:0[1-9]|1[0-9]|2[0-5]))\/bar)$/
  393. console.log(regex.test('foo/00/bar')) // false
  394. console.log(regex.test('foo/01/bar')) // true
  395. console.log(regex.test('foo/10/bar')) // true
  396. console.log(regex.test('foo/22/bar')) // true
  397. console.log(regex.test('foo/25/bar')) // true
  398. console.log(regex.test('foo/26/bar')) // false
  399. ```
  400. ### options.format
  401. **Type**: `function`
  402. **Default**: `undefined`
  403. Custom function for formatting strings before they're matched.
  404. **Example**
  405. ```js
  406. // strip leading './' from strings
  407. const format = str => str.replace(/^\.\//, '');
  408. const isMatch = picomatch('foo/*.js', { format });
  409. console.log(isMatch('./foo/bar.js')) //=> true
  410. ```
  411. ### options.ignore
  412. String or array of glob patterns to match files to ignore.
  413. **Type**: `String|Array`
  414. **Default**: `undefined`
  415. ```js
  416. const isMatch = micromatch.matcher('*', { ignore: 'f*' });
  417. console.log(isMatch('foo')) //=> false
  418. console.log(isMatch('bar')) //=> true
  419. console.log(isMatch('baz')) //=> true
  420. ```
  421. ### options.matchBase
  422. Alias for [options.basename](#options-basename).
  423. ### options.noextglob
  424. Disable extglob support, so that [extglobs](#extglobs) are regarded as literal characters.
  425. **Type**: `Boolean`
  426. **Default**: `undefined`
  427. **Examples**
  428. ```js
  429. console.log(micromatch(['a/z', 'a/b', 'a/!(z)'], 'a/!(z)'));
  430. //=> ['a/b', 'a/!(z)']
  431. console.log(micromatch(['a/z', 'a/b', 'a/!(z)'], 'a/!(z)', { noextglob: true }));
  432. //=> ['a/!(z)'] (matches only as literal characters)
  433. ```
  434. ### options.nonegate
  435. Disallow negation (`!`) patterns, and treat leading `!` as a literal character to match.
  436. **Type**: `Boolean`
  437. **Default**: `undefined`
  438. ### options.noglobstar
  439. Disable matching with globstars (`**`).
  440. **Type**: `Boolean`
  441. **Default**: `undefined`
  442. ```js
  443. micromatch(['a/b', 'a/b/c', 'a/b/c/d'], 'a/**');
  444. //=> ['a/b', 'a/b/c', 'a/b/c/d']
  445. micromatch(['a/b', 'a/b/c', 'a/b/c/d'], 'a/**', {noglobstar: true});
  446. //=> ['a/b']
  447. ```
  448. ### options.nonull
  449. Alias for [options.nullglob](#options-nullglob).
  450. ### options.nullglob
  451. If `true`, when no matches are found the actual (arrayified) glob pattern is returned instead of an empty array. Same behavior as [minimatch](https://github.com/isaacs/minimatch) option `nonull`.
  452. **Type**: `Boolean`
  453. **Default**: `undefined`
  454. ### options.onIgnore
  455. ```js
  456. const onIgnore = ({ glob, regex, input, output }) => {
  457. console.log({ glob, regex, input, output });
  458. // { glob: '*', regex: /^(?:(?!\.)(?=.)[^\/]*?\/?)$/, input: 'foo', output: 'foo' }
  459. };
  460. const isMatch = micromatch.matcher('*', { onIgnore, ignore: 'f*' });
  461. isMatch('foo');
  462. isMatch('bar');
  463. isMatch('baz');
  464. ```
  465. ### options.onMatch
  466. ```js
  467. const onMatch = ({ glob, regex, input, output }) => {
  468. console.log({ input, output });
  469. // { input: 'some\\path', output: 'some/path' }
  470. // { input: 'some\\path', output: 'some/path' }
  471. // { input: 'some\\path', output: 'some/path' }
  472. };
  473. const isMatch = micromatch.matcher('**', { onMatch, posixSlashes: true });
  474. isMatch('some\\path');
  475. isMatch('some\\path');
  476. isMatch('some\\path');
  477. ```
  478. ### options.onResult
  479. ```js
  480. const onResult = ({ glob, regex, input, output }) => {
  481. console.log({ glob, regex, input, output });
  482. };
  483. const isMatch = micromatch('*', { onResult, ignore: 'f*' });
  484. isMatch('foo');
  485. isMatch('bar');
  486. isMatch('baz');
  487. ```
  488. ### options.posixSlashes
  489. Convert path separators on returned files to posix/unix-style forward slashes. Aliased as `unixify` for backwards compatibility.
  490. **Type**: `Boolean`
  491. **Default**: `true` on windows, `false` everywhere else.
  492. **Example**
  493. ```js
  494. console.log(micromatch.match(['a\\b\\c'], 'a/**'));
  495. //=> ['a/b/c']
  496. console.log(micromatch.match(['a\\b\\c'], { posixSlashes: false }));
  497. //=> ['a\\b\\c']
  498. ```
  499. ### options.unescape
  500. Remove backslashes from escaped glob characters before creating the regular expression to perform matches.
  501. **Type**: `Boolean`
  502. **Default**: `undefined`
  503. **Example**
  504. In this example we want to match a literal `*`:
  505. ```js
  506. console.log(micromatch.match(['abc', 'a\\*c'], 'a\\*c'));
  507. //=> ['a\\*c']
  508. console.log(micromatch.match(['abc', 'a\\*c'], 'a\\*c', { unescape: true }));
  509. //=> ['a*c']
  510. ```
  511. <br>
  512. <br>
  513. ## Extended globbing
  514. Micromatch supports the following extended globbing features.
  515. ### Extglobs
  516. Extended globbing, as described by the bash man page:
  517. | **pattern** | **regex equivalent** | **description** |
  518. | --- | --- | --- |
  519. | `?(pattern)` | `(pattern)?` | Matches zero or one occurrence of the given patterns |
  520. | `*(pattern)` | `(pattern)*` | Matches zero or more occurrences of the given patterns |
  521. | `+(pattern)` | `(pattern)+` | Matches one or more occurrences of the given patterns |
  522. | `@(pattern)` | `(pattern)` <sup>*</sup> | Matches one of the given patterns |
  523. | `!(pattern)` | N/A (equivalent regex is much more complicated) | Matches anything except one of the given patterns |
  524. <sup><strong>*</strong></sup> Note that `@` isn't a regex character.
  525. ### Braces
  526. Brace patterns can be used to match specific ranges or sets of characters.
  527. **Example**
  528. The pattern `{f,b}*/{1..3}/{b,q}*` would match any of following strings:
  529. ```
  530. foo/1/bar
  531. foo/2/bar
  532. foo/3/bar
  533. baz/1/qux
  534. baz/2/qux
  535. baz/3/qux
  536. ```
  537. Visit [braces](https://github.com/micromatch/braces) to see the full range of features and options related to brace expansion, or to create brace matching or expansion related issues.
  538. ### Regex character classes
  539. Given the list: `['a.js', 'b.js', 'c.js', 'd.js', 'E.js']`:
  540. * `[ac].js`: matches both `a` and `c`, returning `['a.js', 'c.js']`
  541. * `[b-d].js`: matches from `b` to `d`, returning `['b.js', 'c.js', 'd.js']`
  542. * `a/[A-Z].js`: matches and uppercase letter, returning `['a/E.md']`
  543. Learn about [regex character classes](http://www.regular-expressions.info/charclass.html).
  544. ### Regex groups
  545. Given `['a.js', 'b.js', 'c.js', 'd.js', 'E.js']`:
  546. * `(a|c).js`: would match either `a` or `c`, returning `['a.js', 'c.js']`
  547. * `(b|d).js`: would match either `b` or `d`, returning `['b.js', 'd.js']`
  548. * `(b|[A-Z]).js`: would match either `b` or an uppercase letter, returning `['b.js', 'E.js']`
  549. 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.
  550. ### POSIX bracket expressions
  551. POSIX brackets are intended to be more user-friendly than regex character classes. This of course is in the eye of the beholder.
  552. **Example**
  553. ```js
  554. console.log(micromatch.isMatch('a1', '[[:alpha:][:digit:]]')) //=> true
  555. console.log(micromatch.isMatch('a1', '[[:alpha:][:alpha:]]')) //=> false
  556. ```
  557. ***
  558. ## Notes
  559. ### Bash 4.3 parity
  560. Whenever possible matching behavior is based on behavior Bash 4.3, which is mostly consistent with minimatch.
  561. 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.
  562. ### Backslashes
  563. There is an important, notable difference between minimatch and micromatch _in regards to how backslashes are handled_ in glob patterns.
  564. * 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_.
  565. * Minimatch converts all backslashes to forward slashes, which means you can't use backslashes to escape any characters in your glob patterns.
  566. We made this decision for micromatch for a couple of reasons:
  567. * Consistency with bash conventions.
  568. * Glob patterns are not filepaths. They are a type of [regular language](https://en.wikipedia.org/wiki/Regular_language) that is converted to a JavaScript regular expression. Thus, when forward slashes are defined in a glob pattern, the resulting regular expression will match windows or POSIX path separators just fine.
  569. **A note about joining paths to globs**
  570. 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 `\\`.
  571. 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.
  572. To solve this, you might be inspired to do something like `'foo\\*'.replace(/\\/g, '/')`, but this causes another, potentially much more serious, problem.
  573. ## Benchmarks
  574. ### Running benchmarks
  575. Install dependencies for running benchmarks:
  576. ```sh
  577. $ cd bench && npm install
  578. ```
  579. Run the benchmarks:
  580. ```sh
  581. $ npm run bench
  582. ```
  583. ### Latest results
  584. As of March 24, 2022 (longer bars are better):
  585. ```sh
  586. # .makeRe star
  587. micromatch x 2,232,802 ops/sec ±2.34% (89 runs sampled))
  588. minimatch x 781,018 ops/sec ±6.74% (92 runs sampled))
  589. # .makeRe star; dot=true
  590. micromatch x 1,863,453 ops/sec ±0.74% (93 runs sampled)
  591. minimatch x 723,105 ops/sec ±0.75% (93 runs sampled)
  592. # .makeRe globstar
  593. micromatch x 1,624,179 ops/sec ±2.22% (91 runs sampled)
  594. minimatch x 1,117,230 ops/sec ±2.78% (86 runs sampled))
  595. # .makeRe globstars
  596. micromatch x 1,658,642 ops/sec ±0.86% (92 runs sampled)
  597. minimatch x 741,224 ops/sec ±1.24% (89 runs sampled))
  598. # .makeRe with leading star
  599. micromatch x 1,525,014 ops/sec ±1.63% (90 runs sampled)
  600. minimatch x 561,074 ops/sec ±3.07% (89 runs sampled)
  601. # .makeRe - braces
  602. micromatch x 172,478 ops/sec ±2.37% (78 runs sampled)
  603. minimatch x 96,087 ops/sec ±2.34% (88 runs sampled)))
  604. # .makeRe braces - range (expanded)
  605. micromatch x 26,973 ops/sec ±0.84% (89 runs sampled)
  606. minimatch x 3,023 ops/sec ±0.99% (90 runs sampled))
  607. # .makeRe braces - range (compiled)
  608. micromatch x 152,892 ops/sec ±1.67% (83 runs sampled)
  609. minimatch x 992 ops/sec ±3.50% (89 runs sampled)d))
  610. # .makeRe braces - nested ranges (expanded)
  611. micromatch x 15,816 ops/sec ±13.05% (80 runs sampled)
  612. minimatch x 2,953 ops/sec ±1.64% (91 runs sampled)
  613. # .makeRe braces - nested ranges (compiled)
  614. micromatch x 110,881 ops/sec ±1.85% (82 runs sampled)
  615. minimatch x 1,008 ops/sec ±1.51% (91 runs sampled)
  616. # .makeRe braces - set (compiled)
  617. micromatch x 134,930 ops/sec ±3.54% (63 runs sampled))
  618. minimatch x 43,242 ops/sec ±0.60% (93 runs sampled)
  619. # .makeRe braces - nested sets (compiled)
  620. micromatch x 94,455 ops/sec ±1.74% (69 runs sampled))
  621. minimatch x 27,720 ops/sec ±1.84% (93 runs sampled))
  622. ```
  623. ## Contributing
  624. All contributions are welcome! Please read [the contributing guide](.github/contributing.md) to get started.
  625. **Bug reports**
  626. 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:
  627. * [research existing issues first](../../issues) (open and closed)
  628. * visit the [GNU Bash documentation](https://www.gnu.org/software/bash/manual/) to see how Bash deals with the pattern
  629. * visit the [minimatch](https://github.com/isaacs/minimatch) documentation to cross-check expected behavior in node.js
  630. * 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.
  631. **Platform issues**
  632. 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).
  633. ## About
  634. <details>
  635. <summary><strong>Contributing</strong></summary>
  636. Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](../../issues/new).
  637. Please read the [contributing guide](.github/contributing.md) for advice on opening issues, pull requests, and coding standards.
  638. </details>
  639. <details>
  640. <summary><strong>Running Tests</strong></summary>
  641. 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:
  642. ```sh
  643. $ npm install && npm test
  644. ```
  645. </details>
  646. <details>
  647. <summary><strong>Building docs</strong></summary>
  648. _(This project's readme.md is generated by [verb](https://github.com/verbose/verb-generate-readme), please don't edit the readme directly. Any changes to the readme must be made in the [.verb.md](.verb.md) readme template.)_
  649. To generate the readme, run the following command:
  650. ```sh
  651. $ npm install -g verbose/verb#dev verb-generate-readme && verb
  652. ```
  653. </details>
  654. ### Related projects
  655. You might also be interested in these projects:
  656. * [braces](https://www.npmjs.com/package/braces): Bash-like brace expansion, implemented in JavaScript. Safer than other brace expansion libs, with complete support… [more](https://github.com/micromatch/braces) | [homepage](https://github.com/micromatch/braces "Bash-like brace expansion, implemented in JavaScript. Safer than other brace expansion libs, with complete support for the Bash 4.3 braces specification, without sacrificing speed.")
  657. * [expand-brackets](https://www.npmjs.com/package/expand-brackets): Expand POSIX bracket expressions (character classes) in glob patterns. | [homepage](https://github.com/micromatch/expand-brackets "Expand POSIX bracket expressions (character classes) in glob patterns.")
  658. * [extglob](https://www.npmjs.com/package/extglob): Extended glob support for JavaScript. Adds (almost) the expressive power of regular expressions to glob… [more](https://github.com/micromatch/extglob) | [homepage](https://github.com/micromatch/extglob "Extended glob support for JavaScript. Adds (almost) the expressive power of regular expressions to glob patterns.")
  659. * [fill-range](https://www.npmjs.com/package/fill-range): Fill in a range of numbers or letters, optionally passing an increment or `step` to… [more](https://github.com/jonschlinkert/fill-range) | [homepage](https://github.com/jonschlinkert/fill-range "Fill in a range of numbers or letters, optionally passing an increment or `step` to use, or create a regex-compatible range with `options.toRegex`")
  660. * [nanomatch](https://www.npmjs.com/package/nanomatch): Fast, minimal glob matcher for node.js. Similar to micromatch, minimatch and multimatch, but complete Bash… [more](https://github.com/micromatch/nanomatch) | [homepage](https://github.com/micromatch/nanomatch "Fast, minimal glob matcher for node.js. Similar to micromatch, minimatch and multimatch, but complete Bash 4.3 wildcard support only (no support for exglobs, posix brackets or braces)")
  661. ### Contributors
  662. | **Commits** | **Contributor** |
  663. | --- | --- |
  664. | 512 | [jonschlinkert](https://github.com/jonschlinkert) |
  665. | 12 | [es128](https://github.com/es128) |
  666. | 9 | [danez](https://github.com/danez) |
  667. | 8 | [doowb](https://github.com/doowb) |
  668. | 6 | [paulmillr](https://github.com/paulmillr) |
  669. | 5 | [mrmlnc](https://github.com/mrmlnc) |
  670. | 3 | [DrPizza](https://github.com/DrPizza) |
  671. | 2 | [TrySound](https://github.com/TrySound) |
  672. | 2 | [mceIdo](https://github.com/mceIdo) |
  673. | 2 | [Glazy](https://github.com/Glazy) |
  674. | 2 | [MartinKolarik](https://github.com/MartinKolarik) |
  675. | 2 | [antonyk](https://github.com/antonyk) |
  676. | 2 | [Tvrqvoise](https://github.com/Tvrqvoise) |
  677. | 1 | [amilajack](https://github.com/amilajack) |
  678. | 1 | [Cslove](https://github.com/Cslove) |
  679. | 1 | [devongovett](https://github.com/devongovett) |
  680. | 1 | [DianeLooney](https://github.com/DianeLooney) |
  681. | 1 | [UltCombo](https://github.com/UltCombo) |
  682. | 1 | [frangio](https://github.com/frangio) |
  683. | 1 | [joyceerhl](https://github.com/joyceerhl) |
  684. | 1 | [juszczykjakub](https://github.com/juszczykjakub) |
  685. | 1 | [muescha](https://github.com/muescha) |
  686. | 1 | [sebdeckers](https://github.com/sebdeckers) |
  687. | 1 | [tomByrer](https://github.com/tomByrer) |
  688. | 1 | [fidian](https://github.com/fidian) |
  689. | 1 | [curbengh](https://github.com/curbengh) |
  690. | 1 | [simlu](https://github.com/simlu) |
  691. | 1 | [wtgtybhertgeghgtwtg](https://github.com/wtgtybhertgeghgtwtg) |
  692. | 1 | [yvele](https://github.com/yvele) |
  693. ### Author
  694. **Jon Schlinkert**
  695. * [GitHub Profile](https://github.com/jonschlinkert)
  696. * [Twitter Profile](https://twitter.com/jonschlinkert)
  697. * [LinkedIn Profile](https://linkedin.com/in/jonschlinkert)
  698. ### License
  699. Copyright © 2022, [Jon Schlinkert](https://github.com/jonschlinkert).
  700. Released under the [MIT License](LICENSE).
  701. ***
  702. _This file was generated by [verb-generate-readme](https://github.com/verbose/verb-generate-readme), v0.8.0, on March 24, 2022._