fs: implement glob natively

Signed-off-by: avivkeller <me@aviv.sh>
PR-URL: https://github.com/nodejs/node/pull/65392
Refs: https://openjs-foundation.slack.com/archives/C019Y2T6STH/p1787069174254509
Reviewed-By: Matteo Collina <matteo.collina@gmail.com>
Reviewed-By: Yagiz Nizipli <yagiz@nizipli.com>
Reviewed-By: James M Snell <jasnell@gmail.com>
Reviewed-By: Filip Skokan <panva.ip@gmail.com>
Reviewed-By: Benjamin Gruenbaum <benjamingr@gmail.com>
Reviewed-By: Gürgün Dayıoğlu <hey@gurgun.day>
This commit is contained in:
avivkeller committed 2026-09-11 13:15:27 -04:00
1 parent c14304154e
commit a8f2bf007e
108 files changed
+7807 -13968

No files matched your search

-9
View File
@@ -29,7 +29,6 @@ on:
- libffi
- libuv
- llhttp
- minimatch
- nbytes
- nixpkgs-unstable
- nghttp2
@@ -187,14 +186,6 @@ jobs:
cat temp-output
tail -n1 temp-output | grep "NEW_VERSION=" >> "$GITHUB_ENV" || true
rm temp-output
- id: minimatch
subsystem: deps
label: dependencies
run: |
./tools/dep_updaters/update-minimatch.sh > temp-output
cat temp-output
tail -n1 temp-output | grep "NEW_VERSION=" >> "$GITHUB_ENV" || true
rm temp-output
- id: nbytes
subsystem: deps
label: dependencies
-59
View File
@@ -2058,65 +2058,6 @@ The externally maintained libraries used by Node.js are:
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
"""
- minimatch, located at deps/minimatch, is licensed as follows:
"""
# Blue Oak Model License
Version 1.0.0
## Purpose
This license gives everyone as much permission to work with
this software as possible, while protecting contributors
from liability.
## Acceptance
In order to receive this license, you must agree to its
rules. The rules of this license are both obligations
under that agreement and conditions to your license.
You must not do anything with this software that triggers
a rule that you cannot or will not follow.
## Copyright
Each contributor licenses you to do everything with this
software that would otherwise infringe that contributor's
copyright in it.
## Notices
You must ensure that everyone who gets a copy of
any part of this software from you, with or without
changes, also gets the text of this license or a link to
<https://blueoakcouncil.org/license/1.0.0>.
## Excuse
If anyone notifies you in writing that you have not
complied with [Notices](#notices), you can keep your
license by taking all practical steps to comply within 30
days after the notice. If you do not do so, your license
ends immediately.
## Patent
Each contributor licenses you to do everything with this
software that would otherwise infringe any patent claims
they can license or become able to license.
## Reliability
No contributor can revoke this license.
## No Liability
**_As far as the law allows, this software comes as is,
without any warranty or condition, and no contributor
will be liable to anyone for any damages related to this
software or this license, under any kind of legal claim._**
"""
- npm, located at deps/npm, is licensed as follows:
"""
The npm application
+78
View File
@@ -0,0 +1,78 @@
'use strict';
const common = require('../common');
const {
glob,
globSync,
promises: { glob: globAsync },
} = require('fs');
const path = require('path');
const assert = require('node:assert');
const benchmarkDirectory = path.resolve(__dirname, '..', '..');
const configs = {
n: [1e3],
dir: ['lib'],
pattern: ['**/*.js'],
mode: ['sync', 'promise', 'callback'],
options: ['none', 'withFileTypes', 'exclude-pattern', 'exclude-callback'],
};
const bench = common.createBenchmark(main, configs);
function buildOptions(config) {
const options = { cwd: path.resolve(benchmarkDirectory, config.dir) };
switch (config.options) {
case 'none':
break;
case 'withFileTypes':
options.withFileTypes = true;
break;
case 'exclude-pattern':
options.exclude = ['**/internal/**'];
break;
case 'exclude-callback':
// Excludes nothing: measures the per-entry callback overhead alone.
options.exclude = () => false;
break;
default:
throw new Error(`Unknown options: ${config.options}`);
}
return options;
}
async function main(config) {
const { pattern, mode, n } = config;
const options = buildOptions(config);
let noDead;
bench.start();
for (let i = 0; i < n; i++) {
switch (mode) {
case 'sync':
noDead = globSync(pattern, options);
break;
case 'promise':
noDead = await Array.fromAsync(globAsync(pattern, options));
break;
case 'callback':
noDead = await new Promise((resolve, reject) => {
glob(pattern, options, (err, matches) => {
if (err) {
reject(err);
} else {
resolve(matches);
}
});
});
break;
default:
throw new Error(`Unknown mode: ${mode}`);
}
}
bench.end(n);
assert.ok(noDead.length > 0);
}
+16 -22
View File
@@ -14,53 +14,47 @@ const benchmarkDirectory = path.resolve(__dirname, '..', '..');
const configs = {
n: [1e3],
dir: ['lib'],
pattern: ['**/*', '*.js', '**/**.js'],
pattern: ['**/*', '*.js', '**/*.js', '**/*.{js,json}'],
mode: ['sync', 'promise', 'callback'],
maxDepth: ['default', '2'],
recursive: ['true', 'false'],
};
const bench = common.createBenchmark(main, configs);
async function main(config) {
const fullPath = path.resolve(benchmarkDirectory, config.dir);
const { pattern, recursive, mode, maxDepth } = config;
const options = { cwd: fullPath, recursive };
const { pattern, mode, n, maxDepth } = config;
const options = { cwd: path.resolve(benchmarkDirectory, config.dir) };
if (maxDepth !== 'default') {
options.maxDepth = Number(maxDepth);
}
const callback = (resolve, reject) => {
glob(pattern, options, (err, matches) => {
if (err) {
reject(err);
} else {
resolve(matches);
}
});
};
let noDead;
bench.start();
for (let i = 0; i < config.n; i++) {
for (let i = 0; i < n; i++) {
switch (mode) {
case 'sync':
noDead = globSync(pattern, options);
break;
case 'promise':
noDead = [];
for await (const match of globAsync(pattern, options)) {
noDead.push(match);
}
noDead = await Array.fromAsync(globAsync(pattern, options));
break;
case 'callback':
noDead = await new Promise(callback);
noDead = await new Promise((resolve, reject) => {
glob(pattern, options, (err, matches) => {
if (err) {
reject(err);
} else {
resolve(matches);
}
});
});
break;
default:
throw new Error(`Unknown mode: ${mode}`);
}
}
bench.end(config.n);
assert.ok(noDead);
bench.end(n);
assert.ok(noDead.length > 0);
}
+5 -1
View File
@@ -10,8 +10,12 @@ const bench = common.createBenchmark(main, {
'src/foo/bar/biz/baz/index.test.ts',
],
pattern: [
'src/index.ts',
'**/*.ts',
'**/*.{ts,js}',
'src/**/baz/*.test.ts',
'src/**/baz/*.ts',
'src/**/index.@(test|spec).ts',
'test/**/*.ts',
],
n: [1e5],
@@ -24,5 +28,5 @@ function main({ path, pattern, n }) {
a = posix.matchesGlob(path, pattern);
}
bench.end(n);
assert(a + 'a');
assert.strictEqual(typeof a, 'boolean');
}
+5 -1
View File
@@ -11,8 +11,12 @@ const bench = common.createBenchmark(main, {
'src\\foo\\bar\\biz\\baz\\index.test.ts',
],
pattern: [
'src/index.ts',
'**/*.ts',
'**/*.{ts,js}',
'src/**/baz/*.test.ts',
'src/**/baz/*.ts',
'src/**/index.@(test|spec).ts',
'test/**/*.ts',
],
n: [1e5],
@@ -25,5 +29,5 @@ function main({ path, pattern, n }) {
a = win32.matchesGlob(path, pattern);
}
bench.end(n);
assert(a + 'a');
assert.strictEqual(typeof a, 'boolean');
}
-55
View File
@@ -1,55 +0,0 @@
# Blue Oak Model License
Version 1.0.0
## Purpose
This license gives everyone as much permission to work with
this software as possible, while protecting contributors
from liability.
## Acceptance
In order to receive this license, you must agree to its
rules. The rules of this license are both obligations
under that agreement and conditions to your license.
You must not do anything with this software that triggers
a rule that you cannot or will not follow.
## Copyright
Each contributor licenses you to do everything with this
software that would otherwise infringe that contributor's
copyright in it.
## Notices
You must ensure that everyone who gets a copy of
any part of this software from you, with or without
changes, also gets the text of this license or a link to
<https://blueoakcouncil.org/license/1.0.0>.
## Excuse
If anyone notifies you in writing that you have not
complied with [Notices](#notices), you can keep your
license by taking all practical steps to comply within 30
days after the notice. If you do not do so, your license
ends immediately.
## Patent
Each contributor licenses you to do everything with this
software that would otherwise infringe any patent claims
they can license or become able to license.
## Reliability
No contributor can revoke this license.
## No Liability
**_As far as the law allows, this software comes as is,
without any warranty or condition, and no contributor
will be liable to anyone for any damages related to this
software or this license, under any kind of legal claim._**
-528
View File
@@ -1,528 +0,0 @@
# minimatch
A minimal matching utility.
This is the matching library used internally by npm.
It works by converting glob expressions into JavaScript `RegExp`
objects.
## Important Security Consideration!
> [!WARNING]
> This library uses JavaScript regular expressions. Please read
> the following warning carefully, and be thoughtful about what
> you provide to this library in production systems.
_Any_ library in JavaScript that deals with matching string
patterns using regular expressions will be subject to
[ReDoS](https://owasp.org/www-community/attacks/Regular_expression_Denial_of_Service_-_ReDoS)
if the pattern is generated using untrusted input.
Efforts have been made to mitigate risk as much as is feasible in
such a library, providing maximum recursion depths and so forth,
but these measures can only ultimately protect against accidents,
not malice. A dedicated attacker can _always_ find patterns that
cannot be defended against by a bash-compatible glob pattern
matching system that uses JavaScript regular expressions.
To be extremely clear:
> [!WARNING]
> **If you create a system where you take user input, and use
> that input as the source of a Regular Expression pattern, in
> this or any extant glob matcher in JavaScript, you will be
> pwned.**
A future version of this library _may_ use a different matching
algorithm which does not exhibit backtracking problems. If and
when that happens, it will likely be a sweeping change, and those
improvements will **not** be backported to legacy versions.
In the near term, it is not reasonable to continue to play
whack-a-mole with security advisories, and so any future ReDoS
reports will be considered "working as intended", and resolved
entirely by this warning.
## Usage
```js
// hybrid module, load with require() or import
import { minimatch } from 'minimatch'
// or:
const { minimatch } = require('minimatch')
minimatch('bar.foo', '*.foo') // true!
minimatch('bar.foo', '*.bar') // false!
minimatch('bar.foo', '*.+(bar|foo)', { debug: true }) // true, and noisy!
```
## Features
Supports these glob features:
- Brace Expansion
- Extended glob matching
- "Globstar" `**` matching
- [Posix character
classes](https://www.gnu.org/software/bash/manual/html_node/Pattern-Matching.html),
like `[[:alpha:]]`, supporting the full range of Unicode
characters. For example, `[[:alpha:]]` will match against
`'é'`, though `[a-zA-Z]` will not. Collating symbol and set
matching is not supported, so `[[=e=]]` will _not_ match `'é'`
and `[[.ch.]]` will not match `'ch'` in locales where `ch` is
considered a single character.
See:
- `man sh`
- `man bash` [Pattern
Matching](https://www.gnu.org/software/bash/manual/html_node/Pattern-Matching.html)
- `man 3 fnmatch`
- `man 5 gitignore`
## Windows
**Please only use forward-slashes in glob expressions.**
Though windows uses either `/` or `\` as its path separator, only `/`
characters are used by this glob implementation. You must use
forward-slashes **only** in glob expressions. Back-slashes in patterns
will always be interpreted as escape characters, not path separators.
Note that `\` or `/` _will_ be interpreted as path separators in paths on
Windows, and will match against `/` in glob expressions.
So just always use `/` in patterns.
### UNC Paths
On Windows, UNC paths like `//?/c:/...` or
`//ComputerName/Share/...` are handled specially.
- Patterns starting with a double-slash followed by some
non-slash characters will preserve their double-slash. As a
result, a pattern like `//*` will match `//x`, but not `/x`.
- Patterns staring with `//?/<drive letter>:` will _not_ treat
the `?` as a wildcard character. Instead, it will be treated
as a normal string.
- Patterns starting with `//?/<drive letter>:/...` will match
file paths starting with `<drive letter>:/...`, and vice versa,
as if the `//?/` was not present. This behavior only is
present when the drive letters are a case-insensitive match to
one another. The remaining portions of the path/pattern are
compared case sensitively, unless `nocase:true` is set.
Note that specifying a UNC path using `\` characters as path
separators is always allowed in the file path argument, but only
allowed in the pattern argument when `windowsPathsNoEscape: true`
is set in the options.
## Minimatch Class
Create a minimatch object by instantiating the `minimatch.Minimatch` class.
```javascript
var Minimatch = require('minimatch').Minimatch
var mm = new Minimatch(pattern, options)
```
### Properties
- `pattern` The original pattern the minimatch object represents.
- `options` The options supplied to the constructor.
- `set` A 2-dimensional array of regexp or string expressions.
Each row in the
array corresponds to a brace-expanded pattern. Each item in the row
corresponds to a single path-part. For example, the pattern
`{a,b/c}/d` would expand to a set of patterns like:
[ [ a, d ]
, [ b, c, d ] ]
If a portion of the pattern doesn't have any "magic" in it
(that is, it's something like `"foo"` rather than `fo*o?`), then it
will be left as a string rather than converted to a regular
expression.
- `regexp` Created by the `makeRe` method. A single regular expression
expressing the entire pattern. This is useful in cases where you wish
to use the pattern somewhat like `fnmatch(3)` with `FNM_PATH` enabled.
- `negate` True if the pattern is negated.
- `comment` True if the pattern is a comment.
- `empty` True if the pattern is `""`.
### Methods
- `makeRe()` Generate the `regexp` member if necessary, and return it.
Will return `false` if the pattern is invalid.
- `match(fname)` Return true if the filename matches the pattern, or
false otherwise.
- `matchOne(fileArray, patternArray, partial)` Take a `/`-split
filename, and match it against a single row in the `regExpSet`. This
method is mainly for internal use, but is exposed so that it can be
used by a glob-walker that needs to avoid excessive filesystem calls.
- `hasMagic()` Returns true if the parsed pattern contains any
magic characters. Returns false if all comparator parts are
string literals. If the `magicalBraces` option is set on the
constructor, then it will consider brace expansions which are
not otherwise magical to be magic. If not set, then a pattern
like `a{b,c}d` will return `false`, because neither `abd` nor
`acd` contain any special glob characters.
This does **not** mean that the pattern string can be used as a
literal filename, as it may contain magic glob characters that
are escaped. For example, the pattern `\\*` or `[*]` would not
be considered to have magic, as the matching portion parses to
the literal string `'*'` and would match a path named `'*'`,
not `'\\*'` or `'[*]'`. The `minimatch.unescape()` method may
be used to remove escape characters.
All other methods are internal, and will be called as necessary.
### minimatch(path, pattern, options)
Main export. Tests a path against the pattern using the options.
```javascript
var isJS = minimatch(file, '*.js', { matchBase: true })
```
### minimatch.filter(pattern, options)
Returns a function that tests its
supplied argument, suitable for use with `Array.filter`. Example:
```javascript
var javascripts = fileList.filter(
minimatch.filter('*.js', { matchBase: true }),
)
```
### minimatch.escape(pattern, options = {})
Escape all magic characters in a glob pattern, so that it will
only ever match literal strings.
If the `windowsPathsNoEscape` option is used, then characters are
escaped by wrapping in `[]`, because a magic character wrapped in
a character class can only be satisfied by that exact character.
Slashes (and backslashes in `windowsPathsNoEscape` mode) cannot
be escaped or unescaped.
### minimatch.unescape(pattern, options = {})
Un-escape a glob string that may contain some escaped characters.
If the `windowsPathsNoEscape` option is used, then square-brace
escapes are removed, but not backslash escapes. For example, it
will turn the string `'[*]'` into `*`, but it will not turn
`'\\*'` into `'*'`, because `\` is a path separator in
`windowsPathsNoEscape` mode.
When `windowsPathsNoEscape` is not set, then both brace escapes
and backslash escapes are removed.
Slashes (and backslashes in `windowsPathsNoEscape` mode) cannot
be escaped or unescaped.
### minimatch.match(list, pattern, options)
Match against the list of
files, in the style of fnmatch or glob. If nothing is matched, and
options.nonull is set, then return a list containing the pattern itself.
```javascript
var javascripts = minimatch.match(fileList, '*.js', { matchBase: true })
```
### minimatch.makeRe(pattern, options)
Make a regular expression object from the pattern.
## Options
All options are `false` by default.
### debug
Dump a ton of stuff to stderr.
### nobrace
Do not expand `{a,b}` and `{1..3}` brace sets.
### noglobstar
Disable `**` matching against multiple folder names.
### dot
Allow patterns to match filenames starting with a period, even if
the pattern does not explicitly have a period in that spot.
Note that by default, `a/**/b` will **not** match `a/.d/b`, unless `dot`
is set.
### noext
Disable "extglob" style patterns like `+(a|b)`.
### nocase
Perform a case-insensitive match.
### nocaseMagicOnly
When used with `{nocase: true}`, create regular expressions that
are case-insensitive, but leave string match portions untouched.
Has no effect when used without `{nocase: true}`.
Useful when some other form of case-insensitive matching is used,
or if the original string representation is useful in some other
way.
### nonull
When a match is not found by `minimatch.match`, return a list containing
the pattern itself if this option is set. When not set, an empty list
is returned if there are no matches.
### magicalBraces
This only affects the results of the `Minimatch.hasMagic` method.
If the pattern contains brace expansions, such as `a{b,c}d`, but
no other magic characters, then the `Minimatch.hasMagic()` method
will return `false` by default. When this option set, it will
return `true` for brace expansion as well as other magic glob
characters.
### matchBase
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`.
### nocomment
Suppress the behavior of treating `#` at the start of a pattern as a
comment.
### nonegate
Suppress the behavior of treating a leading `!` character as negation.
### flipNegate
Returns from negate expressions the same as if they were not negated.
(Ie, true on a hit, false on a miss.)
### partial
Compare a partial path to a pattern. As long as the parts of the path that
are present are not contradicted by the pattern, it will be treated as a
match. This is useful in applications where you're walking through a
folder structure, and don't yet have the full path, but want to ensure that
you do not walk down paths that can never be a match.
For example,
```js
minimatch('/a/b', '/a/*/c/d', { partial: true }) // true, might be /a/b/c/d
minimatch('/a/b', '/**/d', { partial: true }) // true, might be /a/b/.../d
minimatch('/x/y/z', '/a/**/z', { partial: true }) // false, because x !== a
```
### windowsPathsNoEscape
Use `\\` as a path separator _only_, and _never_ as an escape
character. If set, all `\\` characters are replaced with `/` in
the pattern. Note that this makes it **impossible** to match
against paths containing literal glob pattern characters, but
allows matching with patterns constructed using `path.join()` and
`path.resolve()` on Windows platforms, mimicking the (buggy!)
behavior of earlier versions on Windows. Please use with
caution, and be mindful of [the caveat about Windows
paths](#windows).
For legacy reasons, this is also set if
`options.allowWindowsEscape` is set to the exact value `false`.
### windowsNoMagicRoot
When a pattern starts with a UNC path or drive letter, and in
`nocase:true` mode, do not convert the root portions of the
pattern into a case-insensitive regular expression, and instead
leave them as strings.
This is the default when the platform is `win32` and
`nocase:true` is set.
### preserveMultipleSlashes
By default, multiple `/` characters (other than the leading `//`
in a UNC path, see "UNC Paths" above) are treated as a single
`/`.
That is, a pattern like `a///b` will match the file path `a/b`.
Set `preserveMultipleSlashes: true` to suppress this behavior.
### optimizationLevel
A number indicating the level of optimization that should be done
to the pattern prior to parsing and using it for matches.
Globstar parts `**` are always converted to `*` when `noglobstar`
is set, and multiple adjacent `**` parts are converted into a
single `**` (ie, `a/**/**/b` will be treated as `a/**/b`, as this
is equivalent in all cases).
- `0` - Make no further changes. In this mode, `.` and `..` are
maintained in the pattern, meaning that they must also appear
in the same position in the test path string. Eg, a pattern
like `a/*/../c` will match the string `a/b/../c` but not the
string `a/c`.
- `1` - (default) Remove cases where a double-dot `..` follows a
pattern portion that is not `**`, `.`, `..`, or empty `''`. For
example, the pattern `./a/b/../*` is converted to `./a/*`, and
so it will match the path string `./a/c`, but not the path
string `./a/b/../c`. Dots and empty path portions in the
pattern are preserved.
- `2` (or higher) - Much more aggressive optimizations, suitable
for use with file-walking cases:
- Remove cases where a double-dot `..` follows a pattern
portion that is not `**`, `.`, or empty `''`. Remove empty
and `.` portions of the pattern, where safe to do so (ie,
anywhere other than the last position, the first position, or
the second position in a pattern starting with `/`, as this
may indicate a UNC path on Windows).
- Convert patterns containing `<pre>/**/../<p>/<rest>` into the
equivalent `<pre>/{..,**}/<p>/<rest>`, where `<p>` is a
a pattern portion other than `.`, `..`, `**`, or empty
`''`.
- Dedupe patterns where a `**` portion is present in one and
omitted in another, and it is not the final path portion, and
they are otherwise equivalent. So `{a/**/b,a/b}` becomes
`a/**/b`, because `**` matches against an empty path portion.
- Dedupe patterns where a `*` portion is present in one, and a
non-dot pattern other than `**`, `.`, `..`, or `''` is in the
same position in the other. So `a/{*,x}/b` becomes `a/*/b`,
because `*` can match against `x`.
While these optimizations improve the performance of
file-walking use cases such as [glob](http://npm.im/glob) (ie,
the reason this module exists), there are cases where it will
fail to match a literal string that would have been matched in
optimization level 1 or 0.
Specifically, while the `Minimatch.match()` method will
optimize the file path string in the same ways, resulting in
the same matches, it will fail when tested with the regular
expression provided by `Minimatch.makeRe()`, unless the path
string is first processed with
`minimatch.levelTwoFileOptimize()` or similar.
### platform
When set to `win32`, this will trigger all windows-specific
behaviors (special handling for UNC paths, and treating `\` as
separators in file paths for comparison.)
Defaults to the value of `process.platform`.
### maxGlobstarRecursion
Max number of non-adjacent `**` patterns to recursively walk
down.
The default of `200` is almost certainly high enough for most
purposes, and can handle absurdly excessive patterns.
If the limit is exceeded (which would require very excessively
long patterns and paths containing lots of `**` patterns!), then
it is treated as non-matching, even if the path would normally
match the pattern provided.
That is, this is an intentional false negative, deemed an
acceptable break in correctness for security and performance.
### maxExtglobRecursion
Max depth to traverse for nested extglobs like `*(a|b|c)`
Default is 2, which is quite low, but any higher value swiftly
results in punishing performance impacts. Note that this is _not_
relevant when the globstar types can be safely coalesced into a
single set.
For example, `*(a|@(b|c)|d)` would be flattened into
`*(a|b|c|d)`. Thus, many common extglobs will retain good
performance and never hit this limit, even if they are
excessively deep and complicated.
If the limit is hit, then the extglob characters are simply not
parsed, and the pattern effectively switches into `noextglob:
true` mode for the contents of that nested sub-pattern. This will
typically _not_ result in a match, but is considered a valid
trade-off for security and performance.
## Comparisons to other fnmatch/glob implementations
While strict compliance with the existing standards is a
worthwhile goal, some discrepancies exist between minimatch and
other implementations. Some are intentional, and some are
unavoidable.
If the pattern starts with a `!` character, then it is negated. Set the
`nonegate` flag to suppress this behavior, and treat leading `!`
characters normally. This is perhaps relevant if you wish to start the
pattern with a negative extglob pattern like `!(a|B)`. Multiple `!`
characters at the start of a pattern will negate the pattern multiple
times.
If a pattern starts with `#`, then it is treated as a comment, and
will not match anything. Use `\#` to match a literal `#` at the
start of a line, or set the `nocomment` flag to suppress this behavior.
The double-star character `**` is supported by default, unless the
`noglobstar` flag is set. This is supported in the manner of bsdglob
and bash 4.1, where `**` only has special significance if it is the only
thing in a path part. That is, `a/**/b` will match `a/x/y/b`, but
`a/**b` will not.
If an escaped pattern has no matches, and the `nonull` flag is set,
then minimatch.match returns the pattern as-provided, rather than
interpreting the character escapes. For example,
`minimatch.match([], "\\*a\\?")` will return `"\\*a\\?"` rather than
`"*a?"`. This is akin to setting the `nullglob` option in bash, except
that it does not resolve escaped pattern characters.
If brace expansion is not disabled, then it is performed before any
other interpretation of the glob pattern. Thus, a pattern like
`+(a|{b),c)}`, which would not be valid in bash or zsh, is expanded
**first** into the set of `+(a|b)` and `+(a|c)`, and those patterns are
checked for validity. Since those two are valid, matching proceeds.
Negated extglob patterns are handled as closely as possible to
Bash semantics, but there are some cases with negative extglobs
which are exceedingly difficult to express in a JavaScript
regular expression. In particular the negated pattern
`<start>!(<pattern>*|)*` will in bash match anything that does
not start with `<start><pattern>`. However,
`<start>!(<pattern>*)*` _will_ match paths starting with
`<start><pattern>`, because the empty string can match against
the negated portion. In this library, `<start>!(<pattern>*|)*`
will _not_ match any pattern starting with `<start>`, due to a
difference in precisely which patterns are considered "greedy" in
Regular Expressions vs bash path expansion. This may be fixable,
but not without incurring some complexity and performance costs,
and the trade-off seems to not be worth pursuing.
Note that `fnmatch(3)` in libc is an extremely naive string comparison
matcher, which does not do anything special for slashes. This library is
designed to be used in glob searching and file walkers, and so it does do
special things with `/`. Thus, `foo*` will not match `foo/bar` in this
library, even though it would in `fnmatch(3)`.
@@ -1,2 +0,0 @@
export declare const assertValidPattern: (pattern: unknown) => void;
//# sourceMappingURL=assert-valid-pattern.d.ts.map
@@ -1 +0,0 @@
{"version":3,"file":"assert-valid-pattern.d.ts","sourceRoot":"","sources":["../../src/assert-valid-pattern.ts"],"names":[],"mappings":"AACA,eAAO,MAAM,kBAAkB,EAAE,CAAC,OAAO,EAAE,OAAO,KAAK,IAUtD,CAAA"}
-14
View File
@@ -1,14 +0,0 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.assertValidPattern = void 0;
const MAX_PATTERN_LENGTH = 1024 * 64;
const assertValidPattern = (pattern) => {
if (typeof pattern !== 'string') {
throw new TypeError('invalid pattern');
}
if (pattern.length > MAX_PATTERN_LENGTH) {
throw new TypeError('pattern is too long');
}
};
exports.assertValidPattern = assertValidPattern;
//# sourceMappingURL=assert-valid-pattern.js.map
@@ -1 +0,0 @@
{"version":3,"file":"assert-valid-pattern.js","sourceRoot":"","sources":["../../src/assert-valid-pattern.ts"],"names":[],"mappings":";;;AAAA,MAAM,kBAAkB,GAAG,IAAI,GAAG,EAAE,CAAA;AAC7B,MAAM,kBAAkB,GAA+B,CAC5D,OAAgB,EACW,EAAE;IAC7B,IAAI,OAAO,OAAO,KAAK,QAAQ,EAAE,CAAC;QAChC,MAAM,IAAI,SAAS,CAAC,iBAAiB,CAAC,CAAA;IACxC,CAAC;IAED,IAAI,OAAO,CAAC,MAAM,GAAG,kBAAkB,EAAE,CAAC;QACxC,MAAM,IAAI,SAAS,CAAC,qBAAqB,CAAC,CAAA;IAC5C,CAAC;AACH,CAAC,CAAA;AAVY,QAAA,kBAAkB,sBAU9B","sourcesContent":["const MAX_PATTERN_LENGTH = 1024 * 64\nexport const assertValidPattern: (pattern: unknown) => void = (\n pattern: unknown,\n): asserts pattern is string => {\n if (typeof pattern !== 'string') {\n throw new TypeError('invalid pattern')\n }\n\n if (pattern.length > MAX_PATTERN_LENGTH) {\n throw new TypeError('pattern is too long')\n }\n}\n"]}
-22
View File
@@ -1,22 +0,0 @@
import type { MinimatchOptions, MMRegExp } from './index.js';
export type ExtglobType = '!' | '?' | '+' | '*' | '@';
export declare class AST {
#private;
type: ExtglobType | null;
id: number;
get depth(): number;
constructor(type: ExtglobType | null, parent?: AST, options?: MinimatchOptions);
get hasMagic(): boolean | undefined;
toString(): string;
push(...parts: (string | AST)[]): void;
toJSON(): unknown[];
isStart(): boolean;
isEnd(): boolean;
copyIn(part: AST | string): void;
clone(parent: AST): AST;
static fromGlob(pattern: string, options?: MinimatchOptions): AST;
toMMPattern(): MMRegExp | string;
get options(): MinimatchOptions;
toRegExpSource(allowDot?: boolean): [re: string, body: string, hasMagic: boolean, uflag: boolean];
}
//# sourceMappingURL=ast.d.ts.map
-1
View File
@@ -1 +0,0 @@
{"version":3,"file":"ast.d.ts","sourceRoot":"","sources":["../../src/ast.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,gBAAgB,EAAE,QAAQ,EAAE,MAAM,YAAY,CAAA;AAwC5D,MAAM,MAAM,WAAW,GAAG,GAAG,GAAG,GAAG,GAAG,GAAG,GAAG,GAAG,GAAG,GAAG,CAAA;AAgJrD,qBAAa,GAAG;;IACd,IAAI,EAAE,WAAW,GAAG,IAAI,CAAA;IAexB,EAAE,SAAO;IAET,IAAI,KAAK,IAAI,MAAM,CAElB;gBAgBC,IAAI,EAAE,WAAW,GAAG,IAAI,EACxB,MAAM,CAAC,EAAE,GAAG,EACZ,OAAO,GAAE,gBAAqB;IAahC,IAAI,QAAQ,IAAI,OAAO,GAAG,SAAS,CAUlC;IAGD,QAAQ,IAAI,MAAM;IAkDlB,IAAI,CAAC,GAAG,KAAK,EAAE,CAAC,MAAM,GAAG,GAAG,CAAC,EAAE;IAe/B,MAAM;IAkBN,OAAO,IAAI,OAAO;IAgBlB,KAAK,IAAI,OAAO;IAYhB,MAAM,CAAC,IAAI,EAAE,GAAG,GAAG,MAAM;IAKzB,KAAK,CAAC,MAAM,EAAE,GAAG;IAsQjB,MAAM,CAAC,QAAQ,CAAC,OAAO,EAAE,MAAM,EAAE,OAAO,GAAE,gBAAqB;IAQ/D,WAAW,IAAI,QAAQ,GAAG,MAAM;IA2BhC,IAAI,OAAO,qBAEV;IAuED,cAAc,CACZ,QAAQ,CAAC,EAAE,OAAO,GACjB,CAAC,EAAE,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,EAAE,QAAQ,EAAE,OAAO,EAAE,KAAK,EAAE,OAAO,CAAC;CA6OjE"}
-845
View File
@@ -1,845 +0,0 @@
"use strict";
// parse a single path portion
var _a;
Object.defineProperty(exports, "__esModule", { value: true });
exports.AST = void 0;
const brace_expressions_js_1 = require("./brace-expressions.js");
const unescape_js_1 = require("./unescape.js");
const types = new Set(['!', '?', '+', '*', '@']);
const isExtglobType = (c) => types.has(c);
const isExtglobAST = (c) => isExtglobType(c.type);
// Map of which extglob types can adopt the children of a nested extglob
//
// anything but ! can adopt a matching type:
// +(a|+(b|c)|d) => +(a|b|c|d)
// *(a|*(b|c)|d) => *(a|b|c|d)
// @(a|@(b|c)|d) => @(a|b|c|d)
// ?(a|?(b|c)|d) => ?(a|b|c|d)
//
// * can adopt anything, because 0 or repetition is allowed
// *(a|?(b|c)|d) => *(a|b|c|d)
// *(a|+(b|c)|d) => *(a|b|c|d)
// *(a|@(b|c)|d) => *(a|b|c|d)
//
// + can adopt @, because 1 or repetition is allowed
// +(a|@(b|c)|d) => +(a|b|c|d)
//
// + and @ CANNOT adopt *, because 0 would be allowed
// +(a|*(b|c)|d) => would match "", on *(b|c)
// @(a|*(b|c)|d) => would match "", on *(b|c)
//
// + and @ CANNOT adopt ?, because 0 would be allowed
// +(a|?(b|c)|d) => would match "", on ?(b|c)
// @(a|?(b|c)|d) => would match "", on ?(b|c)
//
// ? can adopt @, because 0 or 1 is allowed
// ?(a|@(b|c)|d) => ?(a|b|c|d)
//
// ? and @ CANNOT adopt * or +, because >1 would be allowed
// ?(a|*(b|c)|d) => would match bbb on *(b|c)
// @(a|*(b|c)|d) => would match bbb on *(b|c)
// ?(a|+(b|c)|d) => would match bbb on +(b|c)
// @(a|+(b|c)|d) => would match bbb on +(b|c)
//
// ! CANNOT adopt ! (nothing else can either)
// !(a|!(b|c)|d) => !(a|b|c|d) would fail to match on b (not not b|c)
//
// ! can adopt @
// !(a|@(b|c)|d) => !(a|b|c|d)
//
// ! CANNOT adopt *
// !(a|*(b|c)|d) => !(a|b|c|d) would match on bbb, not allowed
//
// ! CANNOT adopt +
// !(a|+(b|c)|d) => !(a|b|c|d) would match on bbb, not allowed
//
// ! CANNOT adopt ?
// x!(a|?(b|c)|d) => x!(a|b|c|d) would fail to match "x"
const adoptionMap = new Map([
['!', ['@']],
['?', ['?', '@']],
['@', ['@']],
['*', ['*', '+', '?', '@']],
['+', ['+', '@']],
]);
// nested extglobs that can be adopted in, but with the addition of
// a blank '' element.
const adoptionWithSpaceMap = new Map([
['!', ['?']],
['@', ['?']],
['+', ['?', '*']],
]);
// union of the previous two maps
const adoptionAnyMap = new Map([
['!', ['?', '@']],
['?', ['?', '@']],
['@', ['?', '@']],
['*', ['*', '+', '?', '@']],
['+', ['+', '@', '?', '*']],
]);
// Extglobs that can take over their parent if they are the only child
// the key is parent, value maps child to resulting extglob parent type
// '@' is omitted because it's a special case. An `@` extglob with a single
// member can always be usurped by that subpattern.
const usurpMap = new Map([
['!', new Map([['!', '@']])],
[
'?',
new Map([
['*', '*'],
['+', '*'],
]),
],
[
'@',
new Map([
['!', '!'],
['?', '?'],
['@', '@'],
['*', '*'],
['+', '+'],
]),
],
[
'+',
new Map([
['?', '*'],
['*', '*'],
]),
],
]);
// Patterns that get prepended to bind to the start of either the
// entire string, or just a single path portion, to prevent dots
// and/or traversal patterns, when needed.
// Exts don't need the ^ or / bit, because the root binds that already.
const startNoTraversal = '(?!(?:^|/)\\.\\.?(?:$|/))';
const startNoDot = '(?!\\.)';
// characters that indicate a start of pattern needs the "no dots" bit,
// because a dot *might* be matched. ( is not in the list, because in
// the case of a child extglob, it will handle the prevention itself.
const addPatternStart = new Set(['[', '.']);
// cases where traversal is A-OK, no dot prevention needed
const justDots = new Set(['..', '.']);
const reSpecials = new Set('().*{}+?[]^$\\!');
const regExpEscape = (s) => s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&');
// any single thing other than /
const qmark = '[^/]';
// * => any number of characters
const star = qmark + '*?';
// use + when we need to ensure that *something* matches, because the * is
// the only thing in the path portion.
const starNoEmpty = qmark + '+?';
// remove the \ chars that we added if we end up doing a nonmagic compare
// const deslash = (s: string) => s.replace(/\\(.)/g, '$1')
let ID = 0;
class AST {
type;
#root;
#hasMagic;
#uflag = false;
#parts = [];
#parent;
#parentIndex;
#negs;
#filledNegs = false;
#options;
#toString;
// set to true if it's an extglob with no children
// (which really means one child of '')
#emptyExt = false;
id = ++ID;
get depth() {
return (this.#parent?.depth ?? -1) + 1;
}
[Symbol.for('nodejs.util.inspect.custom')]() {
return {
'@@type': 'AST',
id: this.id,
type: this.type,
root: this.#root.id,
parent: this.#parent?.id,
depth: this.depth,
partsLength: this.#parts.length,
parts: this.#parts,
};
}
constructor(type, parent, options = {}) {
this.type = type;
// extglobs are inherently magical
if (type)
this.#hasMagic = true;
this.#parent = parent;
this.#root = this.#parent ? this.#parent.#root : this;
this.#options = this.#root === this ? options : this.#root.#options;
this.#negs = this.#root === this ? [] : this.#root.#negs;
if (type === '!' && !this.#root.#filledNegs)
this.#negs.push(this);
this.#parentIndex = this.#parent ? this.#parent.#parts.length : 0;
}
get hasMagic() {
/* c8 ignore start */
if (this.#hasMagic !== undefined)
return this.#hasMagic;
/* c8 ignore stop */
for (const p of this.#parts) {
if (typeof p === 'string')
continue;
if (p.type || p.hasMagic)
return (this.#hasMagic = true);
}
// note: will be undefined until we generate the regexp src and find out
return this.#hasMagic;
}
// reconstructs the pattern
toString() {
return (this.#toString !== undefined ? this.#toString
: !this.type ?
(this.#toString = this.#parts.map(p => String(p)).join(''))
: (this.#toString =
this.type +
'(' +
this.#parts.map(p => String(p)).join('|') +
')'));
}
#fillNegs() {
/* c8 ignore start */
if (this !== this.#root)
throw new Error('should only call on root');
if (this.#filledNegs)
return this;
/* c8 ignore stop */
// call toString() once to fill this out
this.toString();
this.#filledNegs = true;
let n;
while ((n = this.#negs.pop())) {
if (n.type !== '!')
continue;
// walk up the tree, appending everthing that comes AFTER parentIndex
let p = n;
let pp = p.#parent;
while (pp) {
for (let i = p.#parentIndex + 1; !pp.type && i < pp.#parts.length; i++) {
for (const part of n.#parts) {
/* c8 ignore start */
if (typeof part === 'string') {
throw new Error('string part in extglob AST??');
}
/* c8 ignore stop */
part.copyIn(pp.#parts[i]);
}
}
p = pp;
pp = p.#parent;
}
}
return this;
}
push(...parts) {
for (const p of parts) {
if (p === '')
continue;
/* c8 ignore start */
if (typeof p !== 'string' &&
!(p instanceof _a && p.#parent === this)) {
throw new Error('invalid part: ' + p);
}
/* c8 ignore stop */
this.#parts.push(p);
}
}
toJSON() {
const ret = this.type === null ?
this.#parts
.slice()
.map(p => (typeof p === 'string' ? p : p.toJSON()))
: [this.type, ...this.#parts.map(p => p.toJSON())];
if (this.isStart() && !this.type)
ret.unshift([]);
if (this.isEnd() &&
(this === this.#root ||
(this.#root.#filledNegs && this.#parent?.type === '!'))) {
ret.push({});
}
return ret;
}
isStart() {
if (this.#root === this)
return true;
// if (this.type) return !!this.#parent?.isStart()
if (!this.#parent?.isStart())
return false;
if (this.#parentIndex === 0)
return true;
// if everything AHEAD of this is a negation, then it's still the "start"
const p = this.#parent;
for (let i = 0; i < this.#parentIndex; i++) {
const pp = p.#parts[i];
if (!(pp instanceof _a && pp.type === '!')) {
return false;
}
}
return true;
}
isEnd() {
if (this.#root === this)
return true;
if (this.#parent?.type === '!')
return true;
if (!this.#parent?.isEnd())
return false;
if (!this.type)
return this.#parent?.isEnd();
// if not root, it'll always have a parent
/* c8 ignore start */
const pl = this.#parent ? this.#parent.#parts.length : 0;
/* c8 ignore stop */
return this.#parentIndex === pl - 1;
}
copyIn(part) {
if (typeof part === 'string')
this.push(part);
else
this.push(part.clone(this));
}
clone(parent) {
const c = new _a(this.type, parent);
for (const p of this.#parts) {
c.copyIn(p);
}
return c;
}
static #parseAST(str, ast, pos, opt, extDepth) {
const maxDepth = opt.maxExtglobRecursion ?? 2;
let escaping = false;
let inBrace = false;
let braceStart = -1;
let braceNeg = false;
if (ast.type === null) {
// outside of a extglob, append until we find a start
let i = pos;
let acc = '';
while (i < str.length) {
const c = str.charAt(i++);
// still accumulate escapes at this point, but we do ignore
// starts that are escaped
if (escaping || c === '\\') {
escaping = !escaping;
acc += c;
continue;
}
if (inBrace) {
if (i === braceStart + 1) {
if (c === '^' || c === '!') {
braceNeg = true;
}
}
else if (c === ']' && !(i === braceStart + 2 && braceNeg)) {
inBrace = false;
}
acc += c;
continue;
}
else if (c === '[') {
inBrace = true;
braceStart = i;
braceNeg = false;
acc += c;
continue;
}
// we don't have to check for adoption here, because that's
// done at the other recursion point.
const doRecurse = !opt.noext &&
isExtglobType(c) &&
str.charAt(i) === '(' &&
extDepth <= maxDepth;
if (doRecurse) {
ast.push(acc);
acc = '';
const ext = new _a(c, ast);
i = _a.#parseAST(str, ext, i, opt, extDepth + 1);
ast.push(ext);
continue;
}
acc += c;
}
ast.push(acc);
return i;
}
// some kind of extglob, pos is at the (
// find the next | or )
let i = pos + 1;
let part = new _a(null, ast);
const parts = [];
let acc = '';
while (i < str.length) {
const c = str.charAt(i++);
// still accumulate escapes at this point, but we do ignore
// starts that are escaped
if (escaping || c === '\\') {
escaping = !escaping;
acc += c;
continue;
}
if (inBrace) {
if (i === braceStart + 1) {
if (c === '^' || c === '!') {
braceNeg = true;
}
}
else if (c === ']' && !(i === braceStart + 2 && braceNeg)) {
inBrace = false;
}
acc += c;
continue;
}
else if (c === '[') {
inBrace = true;
braceStart = i;
braceNeg = false;
acc += c;
continue;
}
const doRecurse = !opt.noext &&
isExtglobType(c) &&
str.charAt(i) === '(' &&
/* c8 ignore start - the maxDepth is sufficient here */
(extDepth <= maxDepth || (ast && ast.#canAdoptType(c)));
/* c8 ignore stop */
if (doRecurse) {
const depthAdd = ast && ast.#canAdoptType(c) ? 0 : 1;
part.push(acc);
acc = '';
const ext = new _a(c, part);
part.push(ext);
i = _a.#parseAST(str, ext, i, opt, extDepth + depthAdd);
continue;
}
if (c === '|') {
part.push(acc);
acc = '';
parts.push(part);
part = new _a(null, ast);
continue;
}
if (c === ')') {
if (acc === '' && ast.#parts.length === 0) {
ast.#emptyExt = true;
}
part.push(acc);
acc = '';
ast.push(...parts, part);
return i;
}
acc += c;
}
// unfinished extglob
// if we got here, it was a malformed extglob! not an extglob, but
// maybe something else in there.
ast.type = null;
ast.#hasMagic = undefined;
ast.#parts = [str.substring(pos - 1)];
return i;
}
#canAdoptWithSpace(child) {
return this.#canAdopt(child, adoptionWithSpaceMap);
}
#canAdopt(child, map = adoptionMap) {
if (!child ||
typeof child !== 'object' ||
child.type !== null ||
child.#parts.length !== 1 ||
this.type === null) {
return false;
}
const gc = child.#parts[0];
if (!gc || typeof gc !== 'object' || gc.type === null) {
return false;
}
return this.#canAdoptType(gc.type, map);
}
#canAdoptType(c, map = adoptionAnyMap) {
return !!map.get(this.type)?.includes(c);
}
#adoptWithSpace(child, index) {
const gc = child.#parts[0];
const blank = new _a(null, gc, this.options);
blank.#parts.push('');
gc.push(blank);
this.#adopt(child, index);
}
#adopt(child, index) {
const gc = child.#parts[0];
this.#parts.splice(index, 1, ...gc.#parts);
for (const p of gc.#parts) {
if (typeof p === 'object')
p.#parent = this;
}
this.#toString = undefined;
}
#canUsurpType(c) {
const m = usurpMap.get(this.type);
return !!m?.has(c);
}
#canUsurp(child) {
if (!child ||
typeof child !== 'object' ||
child.type !== null ||
child.#parts.length !== 1 ||
this.type === null ||
this.#parts.length !== 1) {
return false;
}
const gc = child.#parts[0];
if (!gc || typeof gc !== 'object' || gc.type === null) {
return false;
}
return this.#canUsurpType(gc.type);
}
#usurp(child) {
const m = usurpMap.get(this.type);
const gc = child.#parts[0];
const nt = m?.get(gc.type);
/* c8 ignore start - impossible */
if (!nt)
return false;
/* c8 ignore stop */
this.#parts = gc.#parts;
for (const p of this.#parts) {
if (typeof p === 'object') {
p.#parent = this;
}
}
this.type = nt;
this.#toString = undefined;
this.#emptyExt = false;
}
static fromGlob(pattern, options = {}) {
const ast = new _a(null, undefined, options);
_a.#parseAST(pattern, ast, 0, options, 0);
return ast;
}
// returns the regular expression if there's magic, or the unescaped
// string if not.
toMMPattern() {
// should only be called on root
/* c8 ignore start */
if (this !== this.#root)
return this.#root.toMMPattern();
/* c8 ignore stop */
const glob = this.toString();
const [re, body, hasMagic, uflag] = this.toRegExpSource();
// if we're in nocase mode, and not nocaseMagicOnly, then we do
// still need a regular expression if we have to case-insensitively
// match capital/lowercase characters.
const anyMagic = hasMagic ||
this.#hasMagic ||
(this.#options.nocase &&
!this.#options.nocaseMagicOnly &&
glob.toUpperCase() !== glob.toLowerCase());
if (!anyMagic) {
return body;
}
const flags = (this.#options.nocase ? 'i' : '') + (uflag ? 'u' : '');
return Object.assign(new RegExp(`^${re}$`, flags), {
_src: re,
_glob: glob,
});
}
get options() {
return this.#options;
}
// returns the string match, the regexp source, whether there's magic
// in the regexp (so a regular expression is required) and whether or
// not the uflag is needed for the regular expression (for posix classes)
// TODO: instead of injecting the start/end at this point, just return
// the BODY of the regexp, along with the start/end portions suitable
// for binding the start/end in either a joined full-path makeRe context
// (where we bind to (^|/), or a standalone matchPart context (where
// we bind to ^, and not /). Otherwise slashes get duped!
//
// In part-matching mode, the start is:
// - if not isStart: nothing
// - if traversal possible, but not allowed: ^(?!\.\.?$)
// - if dots allowed or not possible: ^
// - if dots possible and not allowed: ^(?!\.)
// end is:
// - if not isEnd(): nothing
// - else: $
//
// In full-path matching mode, we put the slash at the START of the
// pattern, so start is:
// - if first pattern: same as part-matching mode
// - if not isStart(): nothing
// - if traversal possible, but not allowed: /(?!\.\.?(?:$|/))
// - if dots allowed or not possible: /
// - if dots possible and not allowed: /(?!\.)
// end is:
// - if last pattern, same as part-matching mode
// - else nothing
//
// Always put the (?:$|/) on negated tails, though, because that has to be
// there to bind the end of the negated pattern portion, and it's easier to
// just stick it in now rather than try to inject it later in the middle of
// the pattern.
//
// We can just always return the same end, and leave it up to the caller
// to know whether it's going to be used joined or in parts.
// And, if the start is adjusted slightly, can do the same there:
// - if not isStart: nothing
// - if traversal possible, but not allowed: (?:/|^)(?!\.\.?$)
// - if dots allowed or not possible: (?:/|^)
// - if dots possible and not allowed: (?:/|^)(?!\.)
//
// But it's better to have a simpler binding without a conditional, for
// performance, so probably better to return both start options.
//
// Then the caller just ignores the end if it's not the first pattern,
// and the start always gets applied.
//
// But that's always going to be $ if it's the ending pattern, or nothing,
// so the caller can just attach $ at the end of the pattern when building.
//
// So the todo is:
// - better detect what kind of start is needed
// - return both flavors of starting pattern
// - attach $ at the end of the pattern when creating the actual RegExp
//
// Ah, but wait, no, that all only applies to the root when the first pattern
// is not an extglob. If the first pattern IS an extglob, then we need all
// that dot prevention biz to live in the extglob portions, because eg
// +(*|.x*) can match .xy but not .yx.
//
// So, return the two flavors if it's #root and the first child is not an
// AST, otherwise leave it to the child AST to handle it, and there,
// use the (?:^|/) style of start binding.
//
// Even simplified further:
// - Since the start for a join is eg /(?!\.) and the start for a part
// is ^(?!\.), we can just prepend (?!\.) to the pattern (either root
// or start or whatever) and prepend ^ or / at the Regexp construction.
toRegExpSource(allowDot) {
const dot = allowDot ?? !!this.#options.dot;
if (this.#root === this) {
this.#flatten();
this.#fillNegs();
}
if (!isExtglobAST(this)) {
const noEmpty = this.isStart() &&
this.isEnd() &&
!this.#parts.some(s => typeof s !== 'string');
const src = this.#parts
.map(p => {
const [re, _, hasMagic, uflag] = typeof p === 'string' ?
_a.#parseGlob(p, this.#hasMagic, noEmpty)
: p.toRegExpSource(allowDot);
this.#hasMagic = this.#hasMagic || hasMagic;
this.#uflag = this.#uflag || uflag;
return re;
})
.join('');
let start = '';
if (this.isStart()) {
if (typeof this.#parts[0] === 'string') {
// this is the string that will match the start of the pattern,
// so we need to protect against dots and such.
// '.' and '..' cannot match unless the pattern is that exactly,
// even if it starts with . or dot:true is set.
const dotTravAllowed = this.#parts.length === 1 && justDots.has(this.#parts[0]);
if (!dotTravAllowed) {
const aps = addPatternStart;
// check if we have a possibility of matching . or ..,
// and prevent that.
const needNoTrav =
// dots are allowed, and the pattern starts with [ or .
(dot && aps.has(src.charAt(0))) ||
// the pattern starts with \., and then [ or .
(src.startsWith('\\.') && aps.has(src.charAt(2))) ||
// the pattern starts with \.\., and then [ or .
(src.startsWith('\\.\\.') && aps.has(src.charAt(4)));
// no need to prevent dots if it can't match a dot, or if a
// sub-pattern will be preventing it anyway.
const needNoDot = !dot && !allowDot && aps.has(src.charAt(0));
start =
needNoTrav ? startNoTraversal
: needNoDot ? startNoDot
: '';
}
}
}
// append the "end of path portion" pattern to negation tails
let end = '';
if (this.isEnd() &&
this.#root.#filledNegs &&
this.#parent?.type === '!') {
end = '(?:$|\\/)';
}
const final = start + src + end;
return [
final,
(0, unescape_js_1.unescape)(src),
(this.#hasMagic = !!this.#hasMagic),
this.#uflag,
];
}
// We need to calculate the body *twice* if it's a repeat pattern
// at the start, once in nodot mode, then again in dot mode, so a
// pattern like *(?) can match 'x.y'
const repeated = this.type === '*' || this.type === '+';
// some kind of extglob
const start = this.type === '!' ? '(?:(?!(?:' : '(?:';
let body = this.#partsToRegExp(dot);
if (this.isStart() && this.isEnd() && !body && this.type !== '!') {
// invalid extglob, has to at least be *something* present, if it's
// the entire path portion.
const s = this.toString();
const me = this;
me.#parts = [s];
me.type = null;
me.#hasMagic = undefined;
return [s, (0, unescape_js_1.unescape)(this.toString()), false, false];
}
let bodyDotAllowed = !repeated || allowDot || dot || !startNoDot ?
''
: this.#partsToRegExp(true);
if (bodyDotAllowed === body) {
bodyDotAllowed = '';
}
if (bodyDotAllowed) {
body = `(?:${body})(?:${bodyDotAllowed})*?`;
}
// an empty !() is exactly equivalent to a starNoEmpty
let final = '';
if (this.type === '!' && this.#emptyExt) {
final = (this.isStart() && !dot ? startNoDot : '') + starNoEmpty;
}
else {
const close = this.type === '!' ?
// !() must match something,but !(x) can match ''
'))' +
(this.isStart() && !dot && !allowDot ? startNoDot : '') +
star +
')'
: this.type === '@' ? ')'
: this.type === '?' ? ')?'
: this.type === '+' && bodyDotAllowed ? ')'
: this.type === '*' && bodyDotAllowed ? `)?`
: `)${this.type}`;
final = start + body + close;
}
return [
final,
(0, unescape_js_1.unescape)(body),
(this.#hasMagic = !!this.#hasMagic),
this.#uflag,
];
}
#flatten() {
if (!isExtglobAST(this)) {
for (const p of this.#parts) {
if (typeof p === 'object') {
p.#flatten();
}
}
}
else {
// do up to 10 passes to flatten as much as possible
let iterations = 0;
let done = false;
do {
done = true;
for (let i = 0; i < this.#parts.length; i++) {
const c = this.#parts[i];
if (typeof c === 'object') {
c.#flatten();
if (this.#canAdopt(c)) {
done = false;
this.#adopt(c, i);
}
else if (this.#canAdoptWithSpace(c)) {
done = false;
this.#adoptWithSpace(c, i);
}
else if (this.#canUsurp(c)) {
done = false;
this.#usurp(c);
}
}
}
} while (!done && ++iterations < 10);
}
this.#toString = undefined;
}
#partsToRegExp(dot) {
return this.#parts
.map(p => {
// extglob ASTs should only contain parent ASTs
/* c8 ignore start */
if (typeof p === 'string') {
throw new Error('string type in extglob ast??');
}
/* c8 ignore stop */
// can ignore hasMagic, because extglobs are already always magic
const [re, _, _hasMagic, uflag] = p.toRegExpSource(dot);
this.#uflag = this.#uflag || uflag;
return re;
})
.filter(p => !(this.isStart() && this.isEnd()) || !!p)
.join('|');
}
static #parseGlob(glob, hasMagic, noEmpty = false) {
let escaping = false;
let re = '';
let uflag = false;
// multiple stars that aren't globstars coalesce into one *
let inStar = false;
for (let i = 0; i < glob.length; i++) {
const c = glob.charAt(i);
if (escaping) {
escaping = false;
re += (reSpecials.has(c) ? '\\' : '') + c;
continue;
}
if (c === '*') {
if (inStar)
continue;
inStar = true;
re += noEmpty && /^[*]+$/.test(glob) ? starNoEmpty : star;
hasMagic = true;
continue;
}
else {
inStar = false;
}
if (c === '\\') {
if (i === glob.length - 1) {
re += '\\\\';
}
else {
escaping = true;
}
continue;
}
if (c === '[') {
const [src, needUflag, consumed, magic] = (0, brace_expressions_js_1.parseClass)(glob, i);
if (consumed) {
re += src;
uflag = uflag || needUflag;
i += consumed - 1;
hasMagic = hasMagic || magic;
continue;
}
}
if (c === '?') {
re += qmark;
hasMagic = true;
continue;
}
re += regExpEscape(c);
}
return [re, (0, unescape_js_1.unescape)(glob), !!hasMagic, uflag];
}
}
exports.AST = AST;
_a = AST;
//# sourceMapping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AK,KAAK,IAAI,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,IAAI,CAAC,KAAK,CAAC,QAAQ,CAAA;QACnE,IAAI,CAAC,KAAK,GAAG,IAAI,CAAC,KAAK,KAAK,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC,KAAK,CAAC,KAAK,CAAA;QACxD,IAAI,IAAI,KAAK,GAAG,IAAI,CAAC,IAAI,CAAC,KAAK,CAAC,WAAW;YAAE,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,CAAA;QAClE,IAAI,CAAC,YAAY,GAAG,IAAI,CAAC,OAAO,CAAC,CAAC,CAAC,IAAI,CAAC,OAAO,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,CAAA;IACnE,CAAC;IAED,IAAI,QAAQ;QACV,qBAAqB;QACrB,IAAI,IAAI,CAAC,SAAS,KAAK,SAAS;YAAE,OAAO,IAAI,CAAC,SAAS,CAAA;QACvD,oBAAoB;QACpB,KAAK,MAAM,CAAC,IAAI,IAAI,CAAC,MAAM,EAAE,CAAC;YAC5B,IAAI,OAAO,CAAC,KAAK,QAAQ;gBAAE,SAAQ;YACnC,IAAI,CAAC,CAAC,IAAI,IAAI,CAAC,CAAC,QAAQ;gBAAE,OAAO,CAAC,IAAI,CAAC,SAAS,GAAG,IAAI,CAAC,CAAA;QAC1D,CAAC;QACD,wEAAwE;QACxE,OAAO,IAAI,CAAC,SAAS,CAAA;Line truncated
-8
View File
@@ -1,8 +0,0 @@
export type ParseClassResult = [
src: string,
uFlag: boolean,
consumed: number,
hasMagic: boolean
];
export declare const parseClass: (glob: string, position: number) => ParseClassResult;
//# sourceMappingURL=brace-expressions.d.ts.map
@@ -1 +0,0 @@
{"version":3,"file":"brace-expressions.d.ts","sourceRoot":"","sources":["../../src/brace-expressions.ts"],"names":[],"mappings":"AAgCA,MAAM,MAAM,gBAAgB,GAAG;IAC7B,GAAG,EAAE,MAAM;IACX,KAAK,EAAE,OAAO;IACd,QAAQ,EAAE,MAAM;IAChB,QAAQ,EAAE,OAAO;CAClB,CAAA;AAQD,eAAO,MAAM,UAAU,GACrB,MAAM,MAAM,EACZ,UAAU,MAAM,KACf,gBA2HF,CAAA"}
-150
View File
@@ -1,150 +0,0 @@
"use strict";
// translate the various posix character classes into unicode properties
// this works across all unicode locales
Object.defineProperty(exports, "__esModule", { value: true });
exports.parseClass = void 0;
// { <posix class>: [<translation>, /u flag required, negated]
const posixClasses = {
'[:alnum:]': ['\\p{L}\\p{Nl}\\p{Nd}', true],
'[:alpha:]': ['\\p{L}\\p{Nl}', true],
'[:ascii:]': ['\\x' + '00-\\x' + '7f', false],
'[:blank:]': ['\\p{Zs}\\t', true],
'[:cntrl:]': ['\\p{Cc}', true],
'[:digit:]': ['\\p{Nd}', true],
'[:graph:]': ['\\p{Z}\\p{C}', true, true],
'[:lower:]': ['\\p{Ll}', true],
'[:print:]': ['\\p{C}', true],
'[:punct:]': ['\\p{P}', true],
'[:space:]': ['\\p{Z}\\t\\r\\n\\v\\f', true],
'[:upper:]': ['\\p{Lu}', true],
'[:word:]': ['\\p{L}\\p{Nl}\\p{Nd}\\p{Pc}', true],
'[:xdigit:]': ['A-Fa-f0-9', false],
};
// only need to escape a few things inside of brace expressions
// escapes: [ \ ] -
const braceEscape = (s) => s.replace(/[[\]\\-]/g, '\\$&');
// escape all regexp magic characters
const regexpEscape = (s) => s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&');
// everything has already been escaped, we just have to join
const rangesToString = (ranges) => ranges.join('');
// takes a glob string at a posix brace expression, and returns
// an equivalent regular expression source, and boolean indicating
// whether the /u flag needs to be applied, and the number of chars
// consumed to parse the character class.
// This also removes out of order ranges, and returns ($.) if the
// entire class just no good.
const parseClass = (glob, position) => {
const pos = position;
/* c8 ignore start */
if (glob.charAt(pos) !== '[') {
throw new Error('not in a brace expression');
}
/* c8 ignore stop */
const ranges = [];
const negs = [];
let i = pos + 1;
let sawStart = false;
let uflag = false;
let escaping = false;
let negate = false;
let endPos = pos;
let rangeStart = '';
WHILE: while (i < glob.length) {
const c = glob.charAt(i);
if ((c === '!' || c === '^') && i === pos + 1) {
negate = true;
i++;
continue;
}
if (c === ']' && sawStart && !escaping) {
endPos = i + 1;
break;
}
sawStart = true;
if (c === '\\') {
if (!escaping) {
escaping = true;
i++;
continue;
}
// escaped \ char, fall through and treat like normal char
}
if (c === '[' && !escaping) {
// either a posix class, a collation equivalent, or just a [
for (const [cls, [unip, u, neg]] of Object.entries(posixClasses)) {
if (glob.startsWith(cls, i)) {
// invalid, [a-[] is fine, but not [a-[:alpha]]
if (rangeStart) {
return ['$.', false, glob.length - pos, true];
}
i += cls.length;
if (neg)
negs.push(unip);
else
ranges.push(unip);
uflag = uflag || u;
continue WHILE;
}
}
}
// now it's just a normal character, effectively
escaping = false;
if (rangeStart) {
// throw this range away if it's not valid, but others
// can still match.
if (c > rangeStart) {
ranges.push(braceEscape(rangeStart) + '-' + braceEscape(c));
}
else if (c === rangeStart) {
ranges.push(braceEscape(c));
}
rangeStart = '';
i++;
continue;
}
// now might be the start of a range.
// can be either c-d or c-] or c<more...>] or c] at this point
if (glob.startsWith('-]', i + 1)) {
ranges.push(braceEscape(c + '-'));
i += 2;
continue;
}
if (glob.startsWith('-', i + 1)) {
rangeStart = c;
i += 2;
continue;
}
// not the start of a range, just a single character
ranges.push(braceEscape(c));
i++;
}
if (endPos < i) {
// didn't see the end of the class, not a valid class,
// but might still be valid as a literal match.
return ['', false, 0, false];
}
// if we got no ranges and no negates, then we have a range that
// cannot possibly match anything, and that poisons the whole glob
if (!ranges.length && !negs.length) {
return ['$.', false, glob.length - pos, true];
}
// if we got one positive range, and it's a single character, then that's
// not actually a magic pattern, it's just that one literal character.
// we should not treat that as "magic", we should just return the literal
// character. [_] is a perfectly valid way to escape glob magic chars.
if (negs.length === 0 &&
ranges.length === 1 &&
/^\\?.$/.test(ranges[0]) &&
!negate) {
const r = ranges[0].length === 2 ? ranges[0].slice(-1) : ranges[0];
return [regexpEscape(r), false, endPos - pos, false];
}
const sranges = '[' + (negate ? '^' : '') + rangesToString(ranges) + ']';
const snegs = '[' + (negate ? '' : '^') + rangesToString(negs) + ']';
const comb = ranges.length && negs.length ? '(' + sranges + '|' + snegs + ')'
: ranges.length ? sranges
: snegs;
return [comb, uflag, endPos - pos, true];
};
exports.parseClass = parseClass;
//# sourceMappingURL=brace-expressions.js.map
-1
View File
@@ -1 +0,0 @@
{"version":3,"file":"brace-expressions.js","sourceRoot":"","sources":["../../src/brace-expressions.ts"],"names":[],"mappings":";AAAA,wEAAwE;AACxE,wCAAwC;;;AAExC,8DAA8D;AAC9D,MAAM,YAAY,GAChB;IACE,WAAW,EAAE,CAAC,sBAAsB,EAAE,IAAI,CAAC;IAC3C,WAAW,EAAE,CAAC,eAAe,EAAE,IAAI,CAAC;IACpC,WAAW,EAAE,CAAC,KAAK,GAAG,QAAQ,GAAG,IAAI,EAAE,KAAK,CAAC;IAC7C,WAAW,EAAE,CAAC,YAAY,EAAE,IAAI,CAAC;IACjC,WAAW,EAAE,CAAC,SAAS,EAAE,IAAI,CAAC;IAC9B,WAAW,EAAE,CAAC,SAAS,EAAE,IAAI,CAAC;IAC9B,WAAW,EAAE,CAAC,cAAc,EAAE,IAAI,EAAE,IAAI,CAAC;IACzC,WAAW,EAAE,CAAC,SAAS,EAAE,IAAI,CAAC;IAC9B,WAAW,EAAE,CAAC,QAAQ,EAAE,IAAI,CAAC;IAC7B,WAAW,EAAE,CAAC,QAAQ,EAAE,IAAI,CAAC;IAC7B,WAAW,EAAE,CAAC,uBAAuB,EAAE,IAAI,CAAC;IAC5C,WAAW,EAAE,CAAC,SAAS,EAAE,IAAI,CAAC;IAC9B,UAAU,EAAE,CAAC,6BAA6B,EAAE,IAAI,CAAC;IACjD,YAAY,EAAE,CAAC,WAAW,EAAE,KAAK,CAAC;CACnC,CAAA;AAEH,+DAA+D;AAC/D,mBAAmB;AACnB,MAAM,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{ MinimatchOptions } from './index.js';
/**
* Escape all magic characters in a glob pattern.
*
* If the {@link MinimatchOptions.windowsPathsNoEscape}
* option is used, then characters are escaped by wrapping in `[]`, because
* a magic character wrapped in a character class can only be satisfied by
* that exact character. In this mode, `\` is _not_ escaped, because it is
* not interpreted as a magic character, but instead as a path separator.
*
* If the {@link MinimatchOptions.magicalBraces} option is used,
* then braces (`{` and `}`) will be escaped.
*/
export declare const escape: (s: string, { windowsPathsNoEscape, magicalBraces, }?: Pick<MinimatchOptions, "windowsPathsNoEscape" | "magicalBraces">) => string;
//# sourceMappingURL=escape.d.ts.map
-1
View File
@@ -1 +0,0 @@
{"version":3,"file":"escape.d.ts","sourceRoot":"","sources":["../../src/escape.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,YAAY,CAAA;AAElD;;;;;;;;;;;GAWG;AACH,eAAO,MAAM,MAAM,GACjB,GAAG,MAAM,EACT,2CAGG,IAAI,CAAC,gBAAgB,EAAE,sBAAsB,GAAG,eAAe,CAAM,WAazE,CAAA"}
-30
View File
@@ -1,30 +0,0 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.escape = void 0;
/**
* Escape all magic characters in a glob pattern.
*
* If the {@link MinimatchOptions.windowsPathsNoEscape}
* option is used, then characters are escaped by wrapping in `[]`, because
* a magic character wrapped in a character class can only be satisfied by
* that exact character. In this mode, `\` is _not_ escaped, because it is
* not interpreted as a magic character, but instead as a path separator.
*
* If the {@link MinimatchOptions.magicalBraces} option is used,
* then braces (`{` and `}`) will be escaped.
*/
const escape = (s, { windowsPathsNoEscape = false, magicalBraces = false, } = {}) => {
// don't need to escape +@! because we escape the parens
// that make those magic, and escaping ! as [!] isn't valid,
// because [!]] is a valid glob class meaning not ']'.
if (magicalBraces) {
return windowsPathsNoEscape ?
s.replace(/[?*()[\]{}]/g, '[$&]')
: s.replace(/[?*()[\]\\{}]/g, '\\$&');
}
return windowsPathsNoEscape ?
s.replace(/[?*()[\]]/g, '[$&]')
: s.replace(/[?*()[\]\\]/g, '\\$&');
};
exports.escape = escape;
//# sourceMappingURL=escape.js.map
-1
View File
@@ -1 +0,0 @@
{"version":3,"file":"escape.js","sourceRoot":"","sources":["../../src/escape.ts"],"names":[],"mappings":";;;AAEA;;;;;;;;;;;GAWG;AACI,MAAM,MAAM,GAAG,CACpB,CAAS,EACT,EACE,oBAAoB,GAAG,KAAK,EAC5B,aAAa,GAAG,KAAK,MAC+C,EAAE,EACxE,EAAE;IACF,wDAAwD;IACxD,4DAA4D;IAC5D,sDAAsD;IACtD,IAAI,aAAa,EAAE,CAAC;QAClB,OAAO,oBAAoB,CAAC,CAAC;YACzB,CAAC,CAAC,OAAO,CAAC,cAAc,EAAE,MAAM,CAAC;YACnC,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,gBAAgB,EAAE,MAAM,CAAC,CAAA;IACzC,CAAC;IACD,OAAO,oBAAoB,CAAC,CAAC;QACzB,CAAC,CAAC,OAAO,CAAC,YAAY,EAAE,MAAM,CAAC;QACjC,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,cAAc,EAAE,MAAM,CAAC,CAAA;AACvC,CAAC,CAAA;AAlBY,QAAA,MAAM,UAkBlB","sourcesContent":["import type { MinimatchOptions } from './index.js'\n\n/**\n * Escape all magic characters in a glob pattern.\n *\n * If the {@link MinimatchOptions.windowsPathsNoEscape}\n * option is used, then characters are escaped by wrapping in `[]`, because\n * a magic character wrapped in a character class can only be satisfied by\n * that exact character. In this mode, `\\` is _not_ escaped, because it is\n * not interpreted as a magic character, but instead as a path separator.\n *\n * If the {@link MinimatchOptions.magicalBraces} option is used,\n * then braces (`{` and `}`) will be escaped.\n */\nexport const escape = (\n s: string,\n {\n windowsPathsNoEscape = false,\n magicalBraces = false,\n }: Pick<MinimatchOptions, 'windowsPathsNoEscape' | 'magicalBraces'> = {},\n) => {\n // don't need to escape +@! because we escape the parens\n // that make those magic, and escaping ! as [!] isn't valid,\n // because [!]] is a valid glob class meaning not ']'.\n if (magicalBraces) {\n return windowsPathsNoEscape ?\n s.replace(/[?*()[\\]{}]/g, '[$&]')\n : s.replace(/[?*()[\\]\\\\{}]/g, '\\\\$&')\n }\n return windowsPathsNoEscape ?\n s.replace(/[?*()[\\]]/g, '[$&]')\n : s.replace(/[?*()[\\]\\\\]/g, '\\\\$&')\n}\n"]}
-174
View File
@@ -1,174 +0,0 @@
import { AST } from './ast.js';
export type Platform = 'aix' | 'android' | 'darwin' | 'freebsd' | 'haiku' | 'linux' | 'openbsd' | 'sunos' | 'win32' | 'cygwin' | 'netbsd';
export interface MinimatchOptions {
/** do not expand `{x,y}` style braces */
nobrace?: boolean;
/** do not treat patterns starting with `#` as a comment */
nocomment?: boolean;
/** do not treat patterns starting with `!` as a negation */
nonegate?: boolean;
/** print LOTS of debugging output */
debug?: boolean;
/** treat `**` the same as `*` */
noglobstar?: boolean;
/** do not expand extglobs like `+(a|b)` */
noext?: boolean;
/** return the pattern if nothing matches */
nonull?: boolean;
/** treat `\\` as a path separator, not an escape character */
windowsPathsNoEscape?: boolean;
/**
* inverse of {@link MinimatchOptions.windowsPathsNoEscape}
* @deprecated
*/
allowWindowsEscape?: boolean;
/**
* Compare a partial path to a pattern. As long as the parts
* of the path that are present are not contradicted by the
* pattern, it will be treated as a match. This is useful in
* applications where you're walking through a folder structure,
* and don't yet have the full path, but want to ensure that you
* do not walk down paths that can never be a match.
*/
partial?: boolean;
/** allow matches that start with `.` even if the pattern does not */
dot?: boolean;
/** ignore case */
nocase?: boolean;
/** ignore case only in wildcard patterns */
nocaseMagicOnly?: boolean;
/** consider braces to be "magic" for the purpose of `hasMagic` */
magicalBraces?: boolean;
/**
* 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`.
*/
matchBase?: boolean;
/** invert the results of negated matches */
flipNegate?: boolean;
/** do not collapse multiple `/` into a single `/` */
preserveMultipleSlashes?: boolean;
/**
* A number indicating the level of optimization that should be done
* to the pattern prior to parsing and using it for matches.
*/
optimizationLevel?: number;
/** operating system platform */
platform?: Platform;
/**
* When a pattern starts with a UNC path or drive letter, and in
* `nocase:true` mode, do not convert the root portions of the
* pattern into a case-insensitive regular expression, and instead
* leave them as strings.
*
* This is the default when the platform is `win32` and
* `nocase:true` is set.
*/
windowsNoMagicRoot?: boolean;
/**
* max number of `{...}` patterns to expand. Default 100_000.
*/
braceExpandMax?: number;
/**
* Max number of non-adjacent `**` patterns to recursively walk down.
*
* The default of 200 is almost certainly high enough for most purposes,
* and can handle absurdly excessive patterns.
*/
maxGlobstarRecursion?: number;
/**
* Max depth to traverse for nested extglobs like `*(a|b|c)`
*
* Default is 2, which is quite low, but any higher value
* swiftly results in punishing performance impacts. Note
* that this is *not* relevant when the globstar types can
* be safely coalesced into a single set.
*
* For example, `*(a|@(b|c)|d)` would be flattened into
* `*(a|b|c|d)`. Thus, many common extglobs will retain good
* performance and never hit this limit, even if they are
* excessively deep and complicated.
*
* If the limit is hit, then the extglob characters are simply
* not parsed, and the pattern effectively switches into
* `noextglob: true` mode for the contents of that nested
* sub-pattern. This will typically _not_ result in a match,
* but is considered a valid trade-off for security and
* performance.
*/
maxExtglobRecursion?: number;
}
export declare const minimatch: {
(p: string, pattern: string, options?: MinimatchOptions): boolean;
sep: Sep;
GLOBSTAR: typeof GLOBSTAR;
filter: (pattern: string, options?: MinimatchOptions) => (p: string) => boolean;
defaults: (def: MinimatchOptions) => typeof minimatch;
braceExpand: (pattern: string, options?: MinimatchOptions) => string[];
makeRe: (pattern: string, options?: MinimatchOptions) => false | MMRegExp;
match: (list: string[], pattern: string, options?: MinimatchOptions) => string[];
AST: typeof AST;
Minimatch: typeof Minimatch;
escape: (s: string, { windowsPathsNoEscape, magicalBraces, }?: Pick<MinimatchOptions, "windowsPathsNoEscape" | "magicalBraces">) => string;
unescape: (s: string, { windowsPathsNoEscape, magicalBraces, }?: Pick<MinimatchOptions, "windowsPathsNoEscape" | "magicalBraces">) => string;
};
export type Sep = '\\' | '/';
export declare const sep: Sep;
export declare const GLOBSTAR: unique symbol;
export declare const filter: (pattern: string, options?: MinimatchOptions) => (p: string) => boolean;
export declare const defaults: (def: MinimatchOptions) => typeof minimatch;
export declare const braceExpand: (pattern: string, options?: MinimatchOptions) => string[];
export declare const makeRe: (pattern: string, options?: MinimatchOptions) => false | MMRegExp;
export declare const match: (list: string[], pattern: string, options?: MinimatchOptions) => string[];
export type MMRegExp = RegExp & {
_src?: string;
_glob?: string;
};
export type ParseReturnFiltered = string | MMRegExp | typeof GLOBSTAR;
export type ParseReturn = ParseReturnFiltered | false;
export declare class Minimatch {
#private;
options: MinimatchOptions;
set: ParseReturnFiltered[][];
pattern: string;
windowsPathsNoEscape: boolean;
nonegate: boolean;
negate: boolean;
comment: boolean;
empty: boolean;
preserveMultipleSlashes: boolean;
partial: boolean;
globSet: string[];
globParts: string[][];
nocase: boolean;
isWindows: boolean;
platform: Platform;
windowsNoMagicRoot: boolean;
maxGlobstarRecursion: number;
regexp: false | null | MMRegExp;
constructor(pattern: string, options?: MinimatchOptions);
hasMagic(): boolean;
debug(..._: unknown[]): void;
make(): void;
preprocess(globParts: string[][]): string[][];
adjascentGlobstarOptimize(globParts: string[][]): string[][];
levelOneOptimize(globParts: string[][]): string[][];
levelTwoFileOptimize(parts: string | string[]): string[];
firstPhasePreProcess(globParts: string[][]): string[][];
secondPhasePreProcess(globParts: string[][]): string[][];
partsMatch(a: string[], b: string[], emptyGSMatch?: boolean): false | string[];
parseNegate(): void;
matchOne(file: string[], pattern: ParseReturn[], partial?: boolean): boolean;
braceExpand(): string[];
parse(pattern: string): ParseReturn;
makeRe(): false | MMRegExp;
slashSplit(p: string): string[];
match(f: string, partial?: boolean): boolean;
static defaults(def: MinimatchOptions): typeof Minimatch;
}
export { AST } from './ast.js';
export { escape } from './escape.js';
export { unescape } from './unescape.js';
//# sourceMappingURL=index.d.ts.map
-1
View File
@@ -1 +0,0 @@
{"version":3,"file":"index.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,EAAE,EAAE;IAkBxD,UAAU,CACR,CAAC,EAAE,MAAM,EAAE,EACX,CAAC,EAAE,MAAM,EAAE,EACX,YAAY,GAAE,OAAe,GAC5B,KAAK,GAAG,MAAM,EAAE;IA+CnB,WAAW;IAqBX,QAAQ,CACN,IAAI,EAAE,MAAM,EAAE,EACd,OAAO,EAAE,WAAW,EAAE,EACtB,OAAO,GAAE,OAAe;IAiX1B,WAAW;IAIX,KAAK,CAAC,OAAO,EAAE,MAAM,GAAG,WAAW;IA6CnC,MAAM;IAuGN,UAAU,CAAC,CAAC,EAAE,MAAM;IAepB,KAAK,CAAC,CAAC,EAAE,MAAM,EAAE,OAAO,UAAe;IAgEvC,MAAM,CAAC,QAAQ,CAAC,GAAG,EAAE,gBAAgB;CAGtC;AAED,OAAO,EAAE,GAAG,EAAE,MAAM,UAAU,CAAA;AAC9B,OAAO,EAAE,MAAM,EAAE,MAAM,aAAa,CAAA;AACpC,OAAO,EAAE,QAAQ,EAAE,MAAM,eAAe,CAAA"}
File diff suppressed because it is too large. Load diff
-1
View File
@@ -1 +0,0 @@
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":";;;AAAA,qDAAwC;AACxC,uEAA8D;AAE9D,qCAA8B;AAC9B,2CAAoC;AACpC,+CAAwC;AAqHjC,MAAM,SAAS,GAAG,CACvB,CAAS,EACT,OAAe,EACf,UAA4B,EAAE,EAC9B,EAAE;IACF,IAAA,4CAAkB,EAAC,OAAO,CAAC,CAAA;IAE3B,oCAAoC;IACpC,IAAI,CAAC,OAAO,CAAC,SAAS,IAAI,OAAO,CAAC,MAAM,CAAC,CAAC,CAAC,KAAK,GAAG,EAAE,CAAC;QACpD,OAAO,KAAK,CAAA;IACd,CAAC;IAED,OAAO,IAAI,SAAS,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,CAAA;AACjD,CAAC,CAAA;AAbY,QAAA,SAAS,aAarB;AAED,wDAAwD;AAC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;AAEzB,MAAM,GAAG,GAAG,CAAC,CAAmB,EAAE,IAAsB,EAAE,EAAE,EAAE,CAC5D,MAAM,CAAC,MAAM,CAAC,EAAE,EAAE,CAAC,EAAE,CAAC,CAAC,CAAA;AAElB,MAAM,QAAQ,GAAG,CAAC,GAAqB,EAAoB,EAAE;IAClE,IAAI,CAAC,GAAG,IAAI,OAAO,GAAG,KAAK,QAAQ,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,MAAM,EAAE,CAAC;QAChE,OAAO,iBAAS,CAAA;IAClB,CAAC;IAED,MAAM,IAAI,GAAG,iBAAS,Line truncated
-3
View File
@@ -1,3 +0,0 @@
{
"type": "commonjs"
}
-22
View File
@@ -1,22 +0,0 @@
import type { MinimatchOptions } from './index.js';
/**
* Un-escape a string that has been escaped with {@link escape}.
*
* If the {@link MinimatchOptions.windowsPathsNoEscape} option is used, then
* square-bracket escapes are removed, but not backslash escapes.
*
* For example, it will turn the string `'[*]'` into `*`, but it will not
* turn `'\\*'` into `'*'`, because `\` is a path separator in
* `windowsPathsNoEscape` mode.
*
* When `windowsPathsNoEscape` is not set, then both square-bracket escapes and
* backslash escapes are removed.
*
* Slashes (and backslashes in `windowsPathsNoEscape` mode) cannot be escaped
* or unescaped.
*
* When `magicalBraces` is not set, escapes of braces (`{` and `}`) will not be
* unescaped.
*/
export declare const unescape: (s: string, { windowsPathsNoEscape, magicalBraces, }?: Pick<MinimatchOptions, "windowsPathsNoEscape" | "magicalBraces">) => string;
//# sourceMappingURL=unescape.d.ts.map
-1
View File
@@ -1 +0,0 @@
{"version":3,"file":"unescape.d.ts","sourceRoot":"","sources":["../../src/unescape.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,YAAY,CAAA;AAElD;;;;;;;;;;;;;;;;;;GAkBG;AAEH,eAAO,MAAM,QAAQ,GACnB,GAAG,MAAM,EACT,2CAGG,IAAI,CAAC,gBAAgB,EAAE,sBAAsB,GAAG,eAAe,CAAM,WAczE,CAAA"}
-38
View File
@@ -1,38 +0,0 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.unescape = void 0;
/**
* Un-escape a string that has been escaped with {@link escape}.
*
* If the {@link MinimatchOptions.windowsPathsNoEscape} option is used, then
* square-bracket escapes are removed, but not backslash escapes.
*
* For example, it will turn the string `'[*]'` into `*`, but it will not
* turn `'\\*'` into `'*'`, because `\` is a path separator in
* `windowsPathsNoEscape` mode.
*
* When `windowsPathsNoEscape` is not set, then both square-bracket escapes and
* backslash escapes are removed.
*
* Slashes (and backslashes in `windowsPathsNoEscape` mode) cannot be escaped
* or unescaped.
*
* When `magicalBraces` is not set, escapes of braces (`{` and `}`) will not be
* unescaped.
*/
const unescape = (s, { windowsPathsNoEscape = false, magicalBraces = true, } = {}) => {
if (magicalBraces) {
return windowsPathsNoEscape ?
s.replace(/\[([^/\\])\]/g, '$1')
: s
.replace(/((?!\\).|^)\[([^/\\])\]/g, '$1$2')
.replace(/\\([^/])/g, '$1');
}
return windowsPathsNoEscape ?
s.replace(/\[([^/\\{}])\]/g, '$1')
: s
.replace(/((?!\\).|^)\[([^/\\{}])\]/g, '$1$2')
.replace(/\\([^/{}])/g, '$1');
};
exports.unescape = unescape;
//# sourceMappingURL=unescape.js.map
-1
View File
@@ -1 +0,0 @@
{"version":3,"file":"unescape.js","sourceRoot":"","sources":["../../src/unescape.ts"],"names":[],"mappings":";;;AAEA;;;;;;;;;;;;;;;;;;GAkBG;AAEI,MAAM,QAAQ,GAAG,CACtB,CAAS,EACT,EACE,oBAAoB,GAAG,KAAK,EAC5B,aAAa,GAAG,IAAI,MACgD,EAAE,EACxE,EAAE;IACF,IAAI,aAAa,EAAE,CAAC;QAClB,OAAO,oBAAoB,CAAC,CAAC;YACzB,CAAC,CAAC,OAAO,CAAC,eAAe,EAAE,IAAI,CAAC;YAClC,CAAC,CAAC,CAAC;iBACE,OAAO,CAAC,0BAA0B,EAAE,MAAM,CAAC;iBAC3C,OAAO,CAAC,WAAW,EAAE,IAAI,CAAC,CAAA;IACnC,CAAC;IACD,OAAO,oBAAoB,CAAC,CAAC;QACzB,CAAC,CAAC,OAAO,CAAC,iBAAiB,EAAE,IAAI,CAAC;QACpC,CAAC,CAAC,CAAC;aACE,OAAO,CAAC,4BAA4B,EAAE,MAAM,CAAC;aAC7C,OAAO,CAAC,aAAa,EAAE,IAAI,CAAC,CAAA;AACrC,CAAC,CAAA;AAnBY,QAAA,QAAQ,YAmBpB","sourcesContent":["import type { MinimatchOptions } from './index.js'\n\n/**\n * Un-escape a string that has been escaped with {@link escape}.\n *\n * If the {@link MinimatchOptions.windowsPathsNoEscape} option is used, then\n * square-bracket escapes are removed, but not backslash escapes.\n *\n * For example, it will turn the string `'[*]'` into `*`, but it will not\n * turn `'\\\\*'` into `'*'`, because `\\` is a path separator in\n * `windowsPathsNoEscape` mode.\n *\n * When `windowsPathsNoEscape` is not set, then both square-bracket escapes and\n * backslash escapes are removed.\n *\n * Slashes (and backslashes in `windowsPathsNoEscape` mode) cannot be escaped\n * or unescaped.\n *\n * When `magicalBraces` is not set, escapes of braces (`{` and `}`) will not be\n * unescaped.\n */\n\nexport const unescape = (\n s: string,\n {\n windowsPathsNoEscape = false,\n magicalBraces = true,\n }: Pick<MinimatchOptions, 'windowsPathsNoEscape' | 'magicalBraces'> = {},\n) => {\n if (magicalBraces) {\n return windowsPathsNoEscape ?\n s.replace(/\\[([^/\\\\])\\]/g, '$1')\n : s\n .replace(/((?!\\\\).|^)\\[([^/\\\\])\\]/g, '$1$2')\n .replace(/\\\\([^/])/g, '$1')\n }\n return windowsPathsNoEscape ?\n s.replace(/\\[([^/\\\\{}])\\]/g, '$1')\n : s\n .replace(/((?!\\\\).|^)\\[([^/\\\\{}])\\]/g, '$1$2')\n .replace(/\\\\([^/{}])/g, '$1')\n}\n"]}
-2
View File
@@ -1,2 +0,0 @@
export declare const assertValidPattern: (pattern: unknown) => void;
//# sourceMappingURL=assert-valid-pattern.d.ts.map
-1
View File
@@ -1 +0,0 @@
{"version":3,"file":"assert-valid-pattern.d.ts","sourceRoot":"","sources":["../../src/assert-valid-pattern.ts"],"names":[],"mappings":"AACA,eAAO,MAAM,kBAAkB,EAAE,CAAC,OAAO,EAAE,OAAO,KAAK,IAUtD,CAAA"}
-10
View File
@@ -1,10 +0,0 @@
const MAX_PATTERN_LENGTH = 1024 * 64;
export const assertValidPattern = (pattern) => {
if (typeof pattern !== 'string') {
throw new TypeError('invalid pattern');
}
if (pattern.length > MAX_PATTERN_LENGTH) {
throw new TypeError('pattern is too long');
}
};
//# sourceMappingURL=assert-valid-pattern.js.map
-1
View File
@@ -1 +0,0 @@
{"version":3,"file":"assert-valid-pattern.js","sourceRoot":"","sources":["../../src/assert-valid-pattern.ts"],"names":[],"mappings":"AAAA,MAAM,kBAAkB,GAAG,IAAI,GAAG,EAAE,CAAA;AACpC,MAAM,CAAC,MAAM,kBAAkB,GAA+B,CAC5D,OAAgB,EACW,EAAE;IAC7B,IAAI,OAAO,OAAO,KAAK,QAAQ,EAAE,CAAC;QAChC,MAAM,IAAI,SAAS,CAAC,iBAAiB,CAAC,CAAA;IACxC,CAAC;IAED,IAAI,OAAO,CAAC,MAAM,GAAG,kBAAkB,EAAE,CAAC;QACxC,MAAM,IAAI,SAAS,CAAC,qBAAqB,CAAC,CAAA;IAC5C,CAAC;AACH,CAAC,CAAA","sourcesContent":["const MAX_PATTERN_LENGTH = 1024 * 64\nexport const assertValidPattern: (pattern: unknown) => void = (\n pattern: unknown,\n): asserts pattern is string => {\n if (typeof pattern !== 'string') {\n throw new TypeError('invalid pattern')\n }\n\n if (pattern.length > MAX_PATTERN_LENGTH) {\n throw new TypeError('pattern is too long')\n }\n}\n"]}
-22
View File
@@ -1,22 +0,0 @@
import type { MinimatchOptions, MMRegExp } from './index.js';
export type ExtglobType = '!' | '?' | '+' | '*' | '@';
export declare class AST {
#private;
type: ExtglobType | null;
id: number;
get depth(): number;
constructor(type: ExtglobType | null, parent?: AST, options?: MinimatchOptions);
get hasMagic(): boolean | undefined;
toString(): string;
push(...parts: (string | AST)[]): void;
toJSON(): unknown[];
isStart(): boolean;
isEnd(): boolean;
copyIn(part: AST | string): void;
clone(parent: AST): AST;
static fromGlob(pattern: string, options?: MinimatchOptions): AST;
toMMPattern(): MMRegExp | string;
get options(): MinimatchOptions;
toRegExpSource(allowDot?: boolean): [re: string, body: string, hasMagic: boolean, uflag: boolean];
}
//# sourceMappingURL=ast.d.ts.map
-1
View File
@@ -1 +0,0 @@
{"version":3,"file":"ast.d.ts","sourceRoot":"","sources":["../../src/ast.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,gBAAgB,EAAE,QAAQ,EAAE,MAAM,YAAY,CAAA;AAwC5D,MAAM,MAAM,WAAW,GAAG,GAAG,GAAG,GAAG,GAAG,GAAG,GAAG,GAAG,GAAG,GAAG,CAAA;AAgJrD,qBAAa,GAAG;;IACd,IAAI,EAAE,WAAW,GAAG,IAAI,CAAA;IAexB,EAAE,SAAO;IAET,IAAI,KAAK,IAAI,MAAM,CAElB;gBAgBC,IAAI,EAAE,WAAW,GAAG,IAAI,EACxB,MAAM,CAAC,EAAE,GAAG,EACZ,OAAO,GAAE,gBAAqB;IAahC,IAAI,QAAQ,IAAI,OAAO,GAAG,SAAS,CAUlC;IAGD,QAAQ,IAAI,MAAM;IAkDlB,IAAI,CAAC,GAAG,KAAK,EAAE,CAAC,MAAM,GAAG,GAAG,CAAC,EAAE;IAe/B,MAAM;IAkBN,OAAO,IAAI,OAAO;IAgBlB,KAAK,IAAI,OAAO;IAYhB,MAAM,CAAC,IAAI,EAAE,GAAG,GAAG,MAAM;IAKzB,KAAK,CAAC,MAAM,EAAE,GAAG;IAsQjB,MAAM,CAAC,QAAQ,CAAC,OAAO,EAAE,MAAM,EAAE,OAAO,GAAE,gBAAqB;IAQ/D,WAAW,IAAI,QAAQ,GAAG,MAAM;IA2BhC,IAAI,OAAO,qBAEV;IAuED,cAAc,CACZ,QAAQ,CAAC,EAAE,OAAO,GACjB,CAAC,EAAE,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,EAAE,QAAQ,EAAE,OAAO,EAAE,KAAK,EAAE,OAAO,CAAC;CA6OjE"}
-841
View File
@@ -1,841 +0,0 @@
// parse a single path portion
var _a;
import { parseClass } from './brace-expressions.js';
import { unescape } from './unescape.js';
const types = new Set(['!', '?', '+', '*', '@']);
const isExtglobType = (c) => types.has(c);
const isExtglobAST = (c) => isExtglobType(c.type);
// Map of which extglob types can adopt the children of a nested extglob
//
// anything but ! can adopt a matching type:
// +(a|+(b|c)|d) => +(a|b|c|d)
// *(a|*(b|c)|d) => *(a|b|c|d)
// @(a|@(b|c)|d) => @(a|b|c|d)
// ?(a|?(b|c)|d) => ?(a|b|c|d)
//
// * can adopt anything, because 0 or repetition is allowed
// *(a|?(b|c)|d) => *(a|b|c|d)
// *(a|+(b|c)|d) => *(a|b|c|d)
// *(a|@(b|c)|d) => *(a|b|c|d)
//
// + can adopt @, because 1 or repetition is allowed
// +(a|@(b|c)|d) => +(a|b|c|d)
//
// + and @ CANNOT adopt *, because 0 would be allowed
// +(a|*(b|c)|d) => would match "", on *(b|c)
// @(a|*(b|c)|d) => would match "", on *(b|c)
//
// + and @ CANNOT adopt ?, because 0 would be allowed
// +(a|?(b|c)|d) => would match "", on ?(b|c)
// @(a|?(b|c)|d) => would match "", on ?(b|c)
//
// ? can adopt @, because 0 or 1 is allowed
// ?(a|@(b|c)|d) => ?(a|b|c|d)
//
// ? and @ CANNOT adopt * or +, because >1 would be allowed
// ?(a|*(b|c)|d) => would match bbb on *(b|c)
// @(a|*(b|c)|d) => would match bbb on *(b|c)
// ?(a|+(b|c)|d) => would match bbb on +(b|c)
// @(a|+(b|c)|d) => would match bbb on +(b|c)
//
// ! CANNOT adopt ! (nothing else can either)
// !(a|!(b|c)|d) => !(a|b|c|d) would fail to match on b (not not b|c)
//
// ! can adopt @
// !(a|@(b|c)|d) => !(a|b|c|d)
//
// ! CANNOT adopt *
// !(a|*(b|c)|d) => !(a|b|c|d) would match on bbb, not allowed
//
// ! CANNOT adopt +
// !(a|+(b|c)|d) => !(a|b|c|d) would match on bbb, not allowed
//
// ! CANNOT adopt ?
// x!(a|?(b|c)|d) => x!(a|b|c|d) would fail to match "x"
const adoptionMap = new Map([
['!', ['@']],
['?', ['?', '@']],
['@', ['@']],
['*', ['*', '+', '?', '@']],
['+', ['+', '@']],
]);
// nested extglobs that can be adopted in, but with the addition of
// a blank '' element.
const adoptionWithSpaceMap = new Map([
['!', ['?']],
['@', ['?']],
['+', ['?', '*']],
]);
// union of the previous two maps
const adoptionAnyMap = new Map([
['!', ['?', '@']],
['?', ['?', '@']],
['@', ['?', '@']],
['*', ['*', '+', '?', '@']],
['+', ['+', '@', '?', '*']],
]);
// Extglobs that can take over their parent if they are the only child
// the key is parent, value maps child to resulting extglob parent type
// '@' is omitted because it's a special case. An `@` extglob with a single
// member can always be usurped by that subpattern.
const usurpMap = new Map([
['!', new Map([['!', '@']])],
[
'?',
new Map([
['*', '*'],
['+', '*'],
]),
],
[
'@',
new Map([
['!', '!'],
['?', '?'],
['@', '@'],
['*', '*'],
['+', '+'],
]),
],
[
'+',
new Map([
['?', '*'],
['*', '*'],
]),
],
]);
// Patterns that get prepended to bind to the start of either the
// entire string, or just a single path portion, to prevent dots
// and/or traversal patterns, when needed.
// Exts don't need the ^ or / bit, because the root binds that already.
const startNoTraversal = '(?!(?:^|/)\\.\\.?(?:$|/))';
const startNoDot = '(?!\\.)';
// characters that indicate a start of pattern needs the "no dots" bit,
// because a dot *might* be matched. ( is not in the list, because in
// the case of a child extglob, it will handle the prevention itself.
const addPatternStart = new Set(['[', '.']);
// cases where traversal is A-OK, no dot prevention needed
const justDots = new Set(['..', '.']);
const reSpecials = new Set('().*{}+?[]^$\\!');
const regExpEscape = (s) => s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&');
// any single thing other than /
const qmark = '[^/]';
// * => any number of characters
const star = qmark + '*?';
// use + when we need to ensure that *something* matches, because the * is
// the only thing in the path portion.
const starNoEmpty = qmark + '+?';
// remove the \ chars that we added if we end up doing a nonmagic compare
// const deslash = (s: string) => s.replace(/\\(.)/g, '$1')
let ID = 0;
export class AST {
type;
#root;
#hasMagic;
#uflag = false;
#parts = [];
#parent;
#parentIndex;
#negs;
#filledNegs = false;
#options;
#toString;
// set to true if it's an extglob with no children
// (which really means one child of '')
#emptyExt = false;
id = ++ID;
get depth() {
return (this.#parent?.depth ?? -1) + 1;
}
[Symbol.for('nodejs.util.inspect.custom')]() {
return {
'@@type': 'AST',
id: this.id,
type: this.type,
root: this.#root.id,
parent: this.#parent?.id,
depth: this.depth,
partsLength: this.#parts.length,
parts: this.#parts,
};
}
constructor(type, parent, options = {}) {
this.type = type;
// extglobs are inherently magical
if (type)
this.#hasMagic = true;
this.#parent = parent;
this.#root = this.#parent ? this.#parent.#root : this;
this.#options = this.#root === this ? options : this.#root.#options;
this.#negs = this.#root === this ? [] : this.#root.#negs;
if (type === '!' && !this.#root.#filledNegs)
this.#negs.push(this);
this.#parentIndex = this.#parent ? this.#parent.#parts.length : 0;
}
get hasMagic() {
/* c8 ignore start */
if (this.#hasMagic !== undefined)
return this.#hasMagic;
/* c8 ignore stop */
for (const p of this.#parts) {
if (typeof p === 'string')
continue;
if (p.type || p.hasMagic)
return (this.#hasMagic = true);
}
// note: will be undefined until we generate the regexp src and find out
return this.#hasMagic;
}
// reconstructs the pattern
toString() {
return (this.#toString !== undefined ? this.#toString
: !this.type ?
(this.#toString = this.#parts.map(p => String(p)).join(''))
: (this.#toString =
this.type +
'(' +
this.#parts.map(p => String(p)).join('|') +
')'));
}
#fillNegs() {
/* c8 ignore start */
if (this !== this.#root)
throw new Error('should only call on root');
if (this.#filledNegs)
return this;
/* c8 ignore stop */
// call toString() once to fill this out
this.toString();
this.#filledNegs = true;
let n;
while ((n = this.#negs.pop())) {
if (n.type !== '!')
continue;
// walk up the tree, appending everthing that comes AFTER parentIndex
let p = n;
let pp = p.#parent;
while (pp) {
for (let i = p.#parentIndex + 1; !pp.type && i < pp.#parts.length; i++) {
for (const part of n.#parts) {
/* c8 ignore start */
if (typeof part === 'string') {
throw new Error('string part in extglob AST??');
}
/* c8 ignore stop */
part.copyIn(pp.#parts[i]);
}
}
p = pp;
pp = p.#parent;
}
}
return this;
}
push(...parts) {
for (const p of parts) {
if (p === '')
continue;
/* c8 ignore start */
if (typeof p !== 'string' &&
!(p instanceof _a && p.#parent === this)) {
throw new Error('invalid part: ' + p);
}
/* c8 ignore stop */
this.#parts.push(p);
}
}
toJSON() {
const ret = this.type === null ?
this.#parts
.slice()
.map(p => (typeof p === 'string' ? p : p.toJSON()))
: [this.type, ...this.#parts.map(p => p.toJSON())];
if (this.isStart() && !this.type)
ret.unshift([]);
if (this.isEnd() &&
(this === this.#root ||
(this.#root.#filledNegs && this.#parent?.type === '!'))) {
ret.push({});
}
return ret;
}
isStart() {
if (this.#root === this)
return true;
// if (this.type) return !!this.#parent?.isStart()
if (!this.#parent?.isStart())
return false;
if (this.#parentIndex === 0)
return true;
// if everything AHEAD of this is a negation, then it's still the "start"
const p = this.#parent;
for (let i = 0; i < this.#parentIndex; i++) {
const pp = p.#parts[i];
if (!(pp instanceof _a && pp.type === '!')) {
return false;
}
}
return true;
}
isEnd() {
if (this.#root === this)
return true;
if (this.#parent?.type === '!')
return true;
if (!this.#parent?.isEnd())
return false;
if (!this.type)
return this.#parent?.isEnd();
// if not root, it'll always have a parent
/* c8 ignore start */
const pl = this.#parent ? this.#parent.#parts.length : 0;
/* c8 ignore stop */
return this.#parentIndex === pl - 1;
}
copyIn(part) {
if (typeof part === 'string')
this.push(part);
else
this.push(part.clone(this));
}
clone(parent) {
const c = new _a(this.type, parent);
for (const p of this.#parts) {
c.copyIn(p);
}
return c;
}
static #parseAST(str, ast, pos, opt, extDepth) {
const maxDepth = opt.maxExtglobRecursion ?? 2;
let escaping = false;
let inBrace = false;
let braceStart = -1;
let braceNeg = false;
if (ast.type === null) {
// outside of a extglob, append until we find a start
let i = pos;
let acc = '';
while (i < str.length) {
const c = str.charAt(i++);
// still accumulate escapes at this point, but we do ignore
// starts that are escaped
if (escaping || c === '\\') {
escaping = !escaping;
acc += c;
continue;
}
if (inBrace) {
if (i === braceStart + 1) {
if (c === '^' || c === '!') {
braceNeg = true;
}
}
else if (c === ']' && !(i === braceStart + 2 && braceNeg)) {
inBrace = false;
}
acc += c;
continue;
}
else if (c === '[') {
inBrace = true;
braceStart = i;
braceNeg = false;
acc += c;
continue;
}
// we don't have to check for adoption here, because that's
// done at the other recursion point.
const doRecurse = !opt.noext &&
isExtglobType(c) &&
str.charAt(i) === '(' &&
extDepth <= maxDepth;
if (doRecurse) {
ast.push(acc);
acc = '';
const ext = new _a(c, ast);
i = _a.#parseAST(str, ext, i, opt, extDepth + 1);
ast.push(ext);
continue;
}
acc += c;
}
ast.push(acc);
return i;
}
// some kind of extglob, pos is at the (
// find the next | or )
let i = pos + 1;
let part = new _a(null, ast);
const parts = [];
let acc = '';
while (i < str.length) {
const c = str.charAt(i++);
// still accumulate escapes at this point, but we do ignore
// starts that are escaped
if (escaping || c === '\\') {
escaping = !escaping;
acc += c;
continue;
}
if (inBrace) {
if (i === braceStart + 1) {
if (c === '^' || c === '!') {
braceNeg = true;
}
}
else if (c === ']' && !(i === braceStart + 2 && braceNeg)) {
inBrace = false;
}
acc += c;
continue;
}
else if (c === '[') {
inBrace = true;
braceStart = i;
braceNeg = false;
acc += c;
continue;
}
const doRecurse = !opt.noext &&
isExtglobType(c) &&
str.charAt(i) === '(' &&
/* c8 ignore start - the maxDepth is sufficient here */
(extDepth <= maxDepth || (ast && ast.#canAdoptType(c)));
/* c8 ignore stop */
if (doRecurse) {
const depthAdd = ast && ast.#canAdoptType(c) ? 0 : 1;
part.push(acc);
acc = '';
const ext = new _a(c, part);
part.push(ext);
i = _a.#parseAST(str, ext, i, opt, extDepth + depthAdd);
continue;
}
if (c === '|') {
part.push(acc);
acc = '';
parts.push(part);
part = new _a(null, ast);
continue;
}
if (c === ')') {
if (acc === '' && ast.#parts.length === 0) {
ast.#emptyExt = true;
}
part.push(acc);
acc = '';
ast.push(...parts, part);
return i;
}
acc += c;
}
// unfinished extglob
// if we got here, it was a malformed extglob! not an extglob, but
// maybe something else in there.
ast.type = null;
ast.#hasMagic = undefined;
ast.#parts = [str.substring(pos - 1)];
return i;
}
#canAdoptWithSpace(child) {
return this.#canAdopt(child, adoptionWithSpaceMap);
}
#canAdopt(child, map = adoptionMap) {
if (!child ||
typeof child !== 'object' ||
child.type !== null ||
child.#parts.length !== 1 ||
this.type === null) {
return false;
}
const gc = child.#parts[0];
if (!gc || typeof gc !== 'object' || gc.type === null) {
return false;
}
return this.#canAdoptType(gc.type, map);
}
#canAdoptType(c, map = adoptionAnyMap) {
return !!map.get(this.type)?.includes(c);
}
#adoptWithSpace(child, index) {
const gc = child.#parts[0];
const blank = new _a(null, gc, this.options);
blank.#parts.push('');
gc.push(blank);
this.#adopt(child, index);
}
#adopt(child, index) {
const gc = child.#parts[0];
this.#parts.splice(index, 1, ...gc.#parts);
for (const p of gc.#parts) {
if (typeof p === 'object')
p.#parent = this;
}
this.#toString = undefined;
}
#canUsurpType(c) {
const m = usurpMap.get(this.type);
return !!m?.has(c);
}
#canUsurp(child) {
if (!child ||
typeof child !== 'object' ||
child.type !== null ||
child.#parts.length !== 1 ||
this.type === null ||
this.#parts.length !== 1) {
return false;
}
const gc = child.#parts[0];
if (!gc || typeof gc !== 'object' || gc.type === null) {
return false;
}
return this.#canUsurpType(gc.type);
}
#usurp(child) {
const m = usurpMap.get(this.type);
const gc = child.#parts[0];
const nt = m?.get(gc.type);
/* c8 ignore start - impossible */
if (!nt)
return false;
/* c8 ignore stop */
this.#parts = gc.#parts;
for (const p of this.#parts) {
if (typeof p === 'object') {
p.#parent = this;
}
}
this.type = nt;
this.#toString = undefined;
this.#emptyExt = false;
}
static fromGlob(pattern, options = {}) {
const ast = new _a(null, undefined, options);
_a.#parseAST(pattern, ast, 0, options, 0);
return ast;
}
// returns the regular expression if there's magic, or the unescaped
// string if not.
toMMPattern() {
// should only be called on root
/* c8 ignore start */
if (this !== this.#root)
return this.#root.toMMPattern();
/* c8 ignore stop */
const glob = this.toString();
const [re, body, hasMagic, uflag] = this.toRegExpSource();
// if we're in nocase mode, and not nocaseMagicOnly, then we do
// still need a regular expression if we have to case-insensitively
// match capital/lowercase characters.
const anyMagic = hasMagic ||
this.#hasMagic ||
(this.#options.nocase &&
!this.#options.nocaseMagicOnly &&
glob.toUpperCase() !== glob.toLowerCase());
if (!anyMagic) {
return body;
}
const flags = (this.#options.nocase ? 'i' : '') + (uflag ? 'u' : '');
return Object.assign(new RegExp(`^${re}$`, flags), {
_src: re,
_glob: glob,
});
}
get options() {
return this.#options;
}
// returns the string match, the regexp source, whether there's magic
// in the regexp (so a regular expression is required) and whether or
// not the uflag is needed for the regular expression (for posix classes)
// TODO: instead of injecting the start/end at this point, just return
// the BODY of the regexp, along with the start/end portions suitable
// for binding the start/end in either a joined full-path makeRe context
// (where we bind to (^|/), or a standalone matchPart context (where
// we bind to ^, and not /). Otherwise slashes get duped!
//
// In part-matching mode, the start is:
// - if not isStart: nothing
// - if traversal possible, but not allowed: ^(?!\.\.?$)
// - if dots allowed or not possible: ^
// - if dots possible and not allowed: ^(?!\.)
// end is:
// - if not isEnd(): nothing
// - else: $
//
// In full-path matching mode, we put the slash at the START of the
// pattern, so start is:
// - if first pattern: same as part-matching mode
// - if not isStart(): nothing
// - if traversal possible, but not allowed: /(?!\.\.?(?:$|/))
// - if dots allowed or not possible: /
// - if dots possible and not allowed: /(?!\.)
// end is:
// - if last pattern, same as part-matching mode
// - else nothing
//
// Always put the (?:$|/) on negated tails, though, because that has to be
// there to bind the end of the negated pattern portion, and it's easier to
// just stick it in now rather than try to inject it later in the middle of
// the pattern.
//
// We can just always return the same end, and leave it up to the caller
// to know whether it's going to be used joined or in parts.
// And, if the start is adjusted slightly, can do the same there:
// - if not isStart: nothing
// - if traversal possible, but not allowed: (?:/|^)(?!\.\.?$)
// - if dots allowed or not possible: (?:/|^)
// - if dots possible and not allowed: (?:/|^)(?!\.)
//
// But it's better to have a simpler binding without a conditional, for
// performance, so probably better to return both start options.
//
// Then the caller just ignores the end if it's not the first pattern,
// and the start always gets applied.
//
// But that's always going to be $ if it's the ending pattern, or nothing,
// so the caller can just attach $ at the end of the pattern when building.
//
// So the todo is:
// - better detect what kind of start is needed
// - return both flavors of starting pattern
// - attach $ at the end of the pattern when creating the actual RegExp
//
// Ah, but wait, no, that all only applies to the root when the first pattern
// is not an extglob. If the first pattern IS an extglob, then we need all
// that dot prevention biz to live in the extglob portions, because eg
// +(*|.x*) can match .xy but not .yx.
//
// So, return the two flavors if it's #root and the first child is not an
// AST, otherwise leave it to the child AST to handle it, and there,
// use the (?:^|/) style of start binding.
//
// Even simplified further:
// - Since the start for a join is eg /(?!\.) and the start for a part
// is ^(?!\.), we can just prepend (?!\.) to the pattern (either root
// or start or whatever) and prepend ^ or / at the Regexp construction.
toRegExpSource(allowDot) {
const dot = allowDot ?? !!this.#options.dot;
if (this.#root === this) {
this.#flatten();
this.#fillNegs();
}
if (!isExtglobAST(this)) {
const noEmpty = this.isStart() &&
this.isEnd() &&
!this.#parts.some(s => typeof s !== 'string');
const src = this.#parts
.map(p => {
const [re, _, hasMagic, uflag] = typeof p === 'string' ?
_a.#parseGlob(p, this.#hasMagic, noEmpty)
: p.toRegExpSource(allowDot);
this.#hasMagic = this.#hasMagic || hasMagic;
this.#uflag = this.#uflag || uflag;
return re;
})
.join('');
let start = '';
if (this.isStart()) {
if (typeof this.#parts[0] === 'string') {
// this is the string that will match the start of the pattern,
// so we need to protect against dots and such.
// '.' and '..' cannot match unless the pattern is that exactly,
// even if it starts with . or dot:true is set.
const dotTravAllowed = this.#parts.length === 1 && justDots.has(this.#parts[0]);
if (!dotTravAllowed) {
const aps = addPatternStart;
// check if we have a possibility of matching . or ..,
// and prevent that.
const needNoTrav =
// dots are allowed, and the pattern starts with [ or .
(dot && aps.has(src.charAt(0))) ||
// the pattern starts with \., and then [ or .
(src.startsWith('\\.') && aps.has(src.charAt(2))) ||
// the pattern starts with \.\., and then [ or .
(src.startsWith('\\.\\.') && aps.has(src.charAt(4)));
// no need to prevent dots if it can't match a dot, or if a
// sub-pattern will be preventing it anyway.
const needNoDot = !dot && !allowDot && aps.has(src.charAt(0));
start =
needNoTrav ? startNoTraversal
: needNoDot ? startNoDot
: '';
}
}
}
// append the "end of path portion" pattern to negation tails
let end = '';
if (this.isEnd() &&
this.#root.#filledNegs &&
this.#parent?.type === '!') {
end = '(?:$|\\/)';
}
const final = start + src + end;
return [
final,
unescape(src),
(this.#hasMagic = !!this.#hasMagic),
this.#uflag,
];
}
// We need to calculate the body *twice* if it's a repeat pattern
// at the start, once in nodot mode, then again in dot mode, so a
// pattern like *(?) can match 'x.y'
const repeated = this.type === '*' || this.type === '+';
// some kind of extglob
const start = this.type === '!' ? '(?:(?!(?:' : '(?:';
let body = this.#partsToRegExp(dot);
if (this.isStart() && this.isEnd() && !body && this.type !== '!') {
// invalid extglob, has to at least be *something* present, if it's
// the entire path portion.
const s = this.toString();
const me = this;
me.#parts = [s];
me.type = null;
me.#hasMagic = undefined;
return [s, unescape(this.toString()), false, false];
}
let bodyDotAllowed = !repeated || allowDot || dot || !startNoDot ?
''
: this.#partsToRegExp(true);
if (bodyDotAllowed === body) {
bodyDotAllowed = '';
}
if (bodyDotAllowed) {
body = `(?:${body})(?:${bodyDotAllowed})*?`;
}
// an empty !() is exactly equivalent to a starNoEmpty
let final = '';
if (this.type === '!' && this.#emptyExt) {
final = (this.isStart() && !dot ? startNoDot : '') + starNoEmpty;
}
else {
const close = this.type === '!' ?
// !() must match something,but !(x) can match ''
'))' +
(this.isStart() && !dot && !allowDot ? startNoDot : '') +
star +
')'
: this.type === '@' ? ')'
: this.type === '?' ? ')?'
: this.type === '+' && bodyDotAllowed ? ')'
: this.type === '*' && bodyDotAllowed ? `)?`
: `)${this.type}`;
final = start + body + close;
}
return [
final,
unescape(body),
(this.#hasMagic = !!this.#hasMagic),
this.#uflag,
];
}
#flatten() {
if (!isExtglobAST(this)) {
for (const p of this.#parts) {
if (typeof p === 'object') {
p.#flatten();
}
}
}
else {
// do up to 10 passes to flatten as much as possible
let iterations = 0;
let done = false;
do {
done = true;
for (let i = 0; i < this.#parts.length; i++) {
const c = this.#parts[i];
if (typeof c === 'object') {
c.#flatten();
if (this.#canAdopt(c)) {
done = false;
this.#adopt(c, i);
}
else if (this.#canAdoptWithSpace(c)) {
done = false;
this.#adoptWithSpace(c, i);
}
else if (this.#canUsurp(c)) {
done = false;
this.#usurp(c);
}
}
}
} while (!done && ++iterations < 10);
}
this.#toString = undefined;
}
#partsToRegExp(dot) {
return this.#parts
.map(p => {
// extglob ASTs should only contain parent ASTs
/* c8 ignore start */
if (typeof p === 'string') {
throw new Error('string type in extglob ast??');
}
/* c8 ignore stop */
// can ignore hasMagic, because extglobs are already always magic
const [re, _, _hasMagic, uflag] = p.toRegExpSource(dot);
this.#uflag = this.#uflag || uflag;
return re;
})
.filter(p => !(this.isStart() && this.isEnd()) || !!p)
.join('|');
}
static #parseGlob(glob, hasMagic, noEmpty = false) {
let escaping = false;
let re = '';
let uflag = false;
// multiple stars that aren't globstars coalesce into one *
let inStar = false;
for (let i = 0; i < glob.length; i++) {
const c = glob.charAt(i);
if (escaping) {
escaping = false;
re += (reSpecials.has(c) ? '\\' : '') + c;
continue;
}
if (c === '*') {
if (inStar)
continue;
inStar = true;
re += noEmpty && /^[*]+$/.test(glob) ? starNoEmpty : star;
hasMagic = true;
continue;
}
else {
inStar = false;
}
if (c === '\\') {
if (i === glob.length - 1) {
re += '\\\\';
}
else {
escaping = true;
}
continue;
}
if (c === '[') {
const [src, needUflag, consumed, magic] = parseClass(glob, i);
if (consumed) {
re += src;
uflag = uflag || needUflag;
i += consumed - 1;
hasMagic = hasMagic || magic;
continue;
}
}
if (c === '?') {
re += qmark;
hasMagic = true;
continue;
}
re += regExpEscape(c);
}
return [re, unescape(glob), !!hasMagic, uflag];
}
}
_a = AST;
//# sourceMappingURL=ast.js.map
-1
View File
@@ -1 +0,0 @@
{"version":3,"file":"ast.js","sourceRoot":"","sources":["../../src/ast.ts"],"names":[],"mappings":"AAAA,8BAA8B;;AAE9B,OAAO,EAAE,UAAU,EAAE,MAAM,wBAAwB,CAAA;AAEnD,OAAO,EAAE,QAAQ,EAAE,MAAM,eAAe,CAAA;AAwCxC,MAAM,KAAK,GAAG,IAAI,GAAG,CAAc,CAAC,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,CAAC,CAAC,CAAA;AAC7D,MAAM,aAAa,GAAG,CAAC,CAAgB,EAAoB,EAAE,CAC3D,KAAK,CAAC,GAAG,CAAC,CAAgB,CAAC,CAAA;AAC7B,MAAM,YAAY,GAAG,CAAC,CAAM,EAAoC,EAAE,CAChE,aAAa,CAAC,CAAC,CAAC,IAAI,CAAC,CAAA;AAEvB,wEAAwE;AACxE,EAAE;AACF,4CAA4C;AAC5C,8BAA8B;AAC9B,8BAA8B;AAC9B,8BAA8B;AAC9B,8BAA8B;AAC9B,EAAE;AACF,2DAA2D;AAC3D,8BAA8B;AAC9B,8BAA8B;AAC9B,8BAA8B;AAC9B,EAAE;AACF,oDAAoD;AACpD,8BAA8B;AAC9B,EAAE;AACF,qDAAqD;AACrD,6CAA6C;AAC7C,6CAA6C;AAC7C,EAAE;AACF,qDAAqD;AACrD,6CAA6C;AAC7C,6CAA6C;AAC7C,EAAE;AACF,2CAA2C;AAC3C,8BAA8B;AAC9B,EAAE;AACF,2DAA2D;AAC3D,6CAA6C;AAC7C,6CAA6C;AAC7C,6CAA6C;AAC7C,6CAA6C;AAC7C,EAAE;AACF,6CAA6C;AAC7C,qEAAqE;AACrE,EAAE;AACF,gBAAgB;AAChB,8BAA8B;AAC9B,EAAE;AACF,mBAAmB;AACnB,8DAA8D;AAC9D,EAAE;AACF,mBAAmB;AACnB,8DAA8D;AAC9D,EAAE;AACF,m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CAAC,CAAC,CAAC,IAAI,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC,CAAC,IAAI,CAAA;QACrD,IAAI,CAAC,QAAQ,GAAG,IAAI,CAAC,KAAK,KAAK,IAAI,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,IAAI,CAAC,KAAK,CAAC,QAAQ,CAAA;QACnE,IAAI,CAAC,KAAK,GAAG,IAAI,CAAC,KAAK,KAAK,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC,KAAK,CAAC,KAAK,CAAA;QACxD,IAAI,IAAI,KAAK,GAAG,IAAI,CAAC,IAAI,CAAC,KAAK,CAAC,WAAW;YAAE,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,CAAA;QAClE,IAAI,CAAC,YAAY,GAAG,IAAI,CAAC,OAAO,CAAC,CAAC,CAAC,IAAI,CAAC,OAAO,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,CAAA;IACnE,CAAC;IAED,IAAI,QAAQ;QACV,qBAAqB;QACrB,IAAI,IAAI,CAAC,SAAS,KAAK,SAAS;YAAE,OAAO,IAAI,CAAC,SAAS,CAAA;QACvD,oBAAoB;QACpB,KAAK,MAAM,CAAC,IAAI,IAAI,CAAC,MAAM,EAAE,CAAC;YAC5B,IAAI,OAAO,CAAC,KAAK,QAAQ;gBAAE,SAAQ;YACnC,IAAI,CAAC,CAAC,IAAI,IAAI,CAAC,CAAC,QAAQ;gBAAE,OAAO,CAAC,IAAI,CAAC,SAAS,GAAG,IAAI,CAACLine truncated
-8
View File
@@ -1,8 +0,0 @@
export type ParseClassResult = [
src: string,
uFlag: boolean,
consumed: number,
hasMagic: boolean
];
export declare const parseClass: (glob: string, position: number) => ParseClassResult;
//# sourceMappingURL=brace-expressions.d.ts.map
-1
View File
@@ -1 +0,0 @@
{"version":3,"file":"brace-expressions.d.ts","sourceRoot":"","sources":["../../src/brace-expressions.ts"],"names":[],"mappings":"AAgCA,MAAM,MAAM,gBAAgB,GAAG;IAC7B,GAAG,EAAE,MAAM;IACX,KAAK,EAAE,OAAO;IACd,QAAQ,EAAE,MAAM;IAChB,QAAQ,EAAE,OAAO;CAClB,CAAA;AAQD,eAAO,MAAM,UAAU,GACrB,MAAM,MAAM,EACZ,UAAU,MAAM,KACf,gBA2HF,CAAA"}
-146
View File
@@ -1,146 +0,0 @@
// translate the various posix character classes into unicode properties
// this works across all unicode locales
// { <posix class>: [<translation>, /u flag required, negated]
const posixClasses = {
'[:alnum:]': ['\\p{L}\\p{Nl}\\p{Nd}', true],
'[:alpha:]': ['\\p{L}\\p{Nl}', true],
'[:ascii:]': ['\\x' + '00-\\x' + '7f', false],
'[:blank:]': ['\\p{Zs}\\t', true],
'[:cntrl:]': ['\\p{Cc}', true],
'[:digit:]': ['\\p{Nd}', true],
'[:graph:]': ['\\p{Z}\\p{C}', true, true],
'[:lower:]': ['\\p{Ll}', true],
'[:print:]': ['\\p{C}', true],
'[:punct:]': ['\\p{P}', true],
'[:space:]': ['\\p{Z}\\t\\r\\n\\v\\f', true],
'[:upper:]': ['\\p{Lu}', true],
'[:word:]': ['\\p{L}\\p{Nl}\\p{Nd}\\p{Pc}', true],
'[:xdigit:]': ['A-Fa-f0-9', false],
};
// only need to escape a few things inside of brace expressions
// escapes: [ \ ] -
const braceEscape = (s) => s.replace(/[[\]\\-]/g, '\\$&');
// escape all regexp magic characters
const regexpEscape = (s) => s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&');
// everything has already been escaped, we just have to join
const rangesToString = (ranges) => ranges.join('');
// takes a glob string at a posix brace expression, and returns
// an equivalent regular expression source, and boolean indicating
// whether the /u flag needs to be applied, and the number of chars
// consumed to parse the character class.
// This also removes out of order ranges, and returns ($.) if the
// entire class just no good.
export const parseClass = (glob, position) => {
const pos = position;
/* c8 ignore start */
if (glob.charAt(pos) !== '[') {
throw new Error('not in a brace expression');
}
/* c8 ignore stop */
const ranges = [];
const negs = [];
let i = pos + 1;
let sawStart = false;
let uflag = false;
let escaping = false;
let negate = false;
let endPos = pos;
let rangeStart = '';
WHILE: while (i < glob.length) {
const c = glob.charAt(i);
if ((c === '!' || c === '^') && i === pos + 1) {
negate = true;
i++;
continue;
}
if (c === ']' && sawStart && !escaping) {
endPos = i + 1;
break;
}
sawStart = true;
if (c === '\\') {
if (!escaping) {
escaping = true;
i++;
continue;
}
// escaped \ char, fall through and treat like normal char
}
if (c === '[' && !escaping) {
// either a posix class, a collation equivalent, or just a [
for (const [cls, [unip, u, neg]] of Object.entries(posixClasses)) {
if (glob.startsWith(cls, i)) {
// invalid, [a-[] is fine, but not [a-[:alpha]]
if (rangeStart) {
return ['$.', false, glob.length - pos, true];
}
i += cls.length;
if (neg)
negs.push(unip);
else
ranges.push(unip);
uflag = uflag || u;
continue WHILE;
}
}
}
// now it's just a normal character, effectively
escaping = false;
if (rangeStart) {
// throw this range away if it's not valid, but others
// can still match.
if (c > rangeStart) {
ranges.push(braceEscape(rangeStart) + '-' + braceEscape(c));
}
else if (c === rangeStart) {
ranges.push(braceEscape(c));
}
rangeStart = '';
i++;
continue;
}
// now might be the start of a range.
// can be either c-d or c-] or c<more...>] or c] at this point
if (glob.startsWith('-]', i + 1)) {
ranges.push(braceEscape(c + '-'));
i += 2;
continue;
}
if (glob.startsWith('-', i + 1)) {
rangeStart = c;
i += 2;
continue;
}
// not the start of a range, just a single character
ranges.push(braceEscape(c));
i++;
}
if (endPos < i) {
// didn't see the end of the class, not a valid class,
// but might still be valid as a literal match.
return ['', false, 0, false];
}
// if we got no ranges and no negates, then we have a range that
// cannot possibly match anything, and that poisons the whole glob
if (!ranges.length && !negs.length) {
return ['$.', false, glob.length - pos, true];
}
// if we got one positive range, and it's a single character, then that's
// not actually a magic pattern, it's just that one literal character.
// we should not treat that as "magic", we should just return the literal
// character. [_] is a perfectly valid way to escape glob magic chars.
if (negs.length === 0 &&
ranges.length === 1 &&
/^\\?.$/.test(ranges[0]) &&
!negate) {
const r = ranges[0].length === 2 ? ranges[0].slice(-1) : ranges[0];
return [regexpEscape(r), false, endPos - pos, false];
}
const sranges = '[' + (negate ? '^' : '') + rangesToString(ranges) + ']';
const snegs = '[' + (negate ? '' : '^') + rangesToString(negs) + ']';
const comb = ranges.length && negs.length ? '(' + sranges + '|' + snegs + ')'
: ranges.length ? sranges
: snegs;
return [comb, uflag, endPos - pos, true];
};
//# sourceMappingURL=brace-expressions.js.map
-1
View File
@@ -1 +0,0 @@
{"version":3,"file":"brace-expressions.js","sourceRoot":"","sources":["../../src/brace-expressions.ts"],"names":[],"mappings":"AAAA,wEAAwE;AACxE,wCAAwC;AAExC,8DAA8D;AAC9D,MAAM,YAAY,GAChB;IACE,WAAW,EAAE,CAAC,sBAAsB,EAAE,IAAI,CAAC;IAC3C,WAAW,EAAE,CAAC,eAAe,EAAE,IAAI,CAAC;IACpC,WAAW,EAAE,CAAC,KAAK,GAAG,QAAQ,GAAG,IAAI,EAAE,KAAK,CAAC;IAC7C,WAAW,EAAE,CAAC,YAAY,EAAE,IAAI,CAAC;IACjC,WAAW,EAAE,CAAC,SAAS,EAAE,IAAI,CAAC;IAC9B,WAAW,EAAE,CAAC,SAAS,EAAE,IAAI,CAAC;IAC9B,WAAW,EAAE,CAAC,cAAc,EAAE,IAAI,EAAE,IAAI,CAAC;IACzC,WAAW,EAAE,CAAC,SAAS,EAAE,IAAI,CAAC;IAC9B,WAAW,EAAE,CAAC,QAAQ,EAAE,IAAI,CAAC;IAC7B,WAAW,EAAE,CAAC,QAAQ,EAAE,IAAI,CAAC;IAC7B,WAAW,EAAE,CAAC,uBAAuB,EAAE,IAAI,CAAC;IAC5C,WAAW,EAAE,CAAC,SAAS,EAAE,IAAI,CAAC;IAC9B,UAAU,EAAE,CAAC,6BAA6B,EAAE,IAAI,CAAC;IACjD,YAAY,EAAE,CAAC,WAAW,EAAE,KAAK,CAAC;CACnC,CAAA;AAEH,+DAA+D;AAC/D,mBAAmB;AACnB,MAAM,WAAW,GAA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imatchOptions } from './index.js';
/**
* Escape all magic characters in a glob pattern.
*
* If the {@link MinimatchOptions.windowsPathsNoEscape}
* option is used, then characters are escaped by wrapping in `[]`, because
* a magic character wrapped in a character class can only be satisfied by
* that exact character. In this mode, `\` is _not_ escaped, because it is
* not interpreted as a magic character, but instead as a path separator.
*
* If the {@link MinimatchOptions.magicalBraces} option is used,
* then braces (`{` and `}`) will be escaped.
*/
export declare const escape: (s: string, { windowsPathsNoEscape, magicalBraces, }?: Pick<MinimatchOptions, "windowsPathsNoEscape" | "magicalBraces">) => string;
//# sourceMappingURL=escape.d.ts.map
-1
View File
@@ -1 +0,0 @@
{"version":3,"file":"escape.d.ts","sourceRoot":"","sources":["../../src/escape.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,YAAY,CAAA;AAElD;;;;;;;;;;;GAWG;AACH,eAAO,MAAM,MAAM,GACjB,GAAG,MAAM,EACT,2CAGG,IAAI,CAAC,gBAAgB,EAAE,sBAAsB,GAAG,eAAe,CAAM,WAazE,CAAA"}
-26
View File
@@ -1,26 +0,0 @@
/**
* Escape all magic characters in a glob pattern.
*
* If the {@link MinimatchOptions.windowsPathsNoEscape}
* option is used, then characters are escaped by wrapping in `[]`, because
* a magic character wrapped in a character class can only be satisfied by
* that exact character. In this mode, `\` is _not_ escaped, because it is
* not interpreted as a magic character, but instead as a path separator.
*
* If the {@link MinimatchOptions.magicalBraces} option is used,
* then braces (`{` and `}`) will be escaped.
*/
export const escape = (s, { windowsPathsNoEscape = false, magicalBraces = false, } = {}) => {
// don't need to escape +@! because we escape the parens
// that make those magic, and escaping ! as [!] isn't valid,
// because [!]] is a valid glob class meaning not ']'.
if (magicalBraces) {
return windowsPathsNoEscape ?
s.replace(/[?*()[\]{}]/g, '[$&]')
: s.replace(/[?*()[\]\\{}]/g, '\\$&');
}
return windowsPathsNoEscape ?
s.replace(/[?*()[\]]/g, '[$&]')
: s.replace(/[?*()[\]\\]/g, '\\$&');
};
//# sourceMappingURL=escape.js.map
-1
View File
@@ -1 +0,0 @@
{"version":3,"file":"escape.js","sourceRoot":"","sources":["../../src/escape.ts"],"names":[],"mappings":"AAEA;;;;;;;;;;;GAWG;AACH,MAAM,CAAC,MAAM,MAAM,GAAG,CACpB,CAAS,EACT,EACE,oBAAoB,GAAG,KAAK,EAC5B,aAAa,GAAG,KAAK,MAC+C,EAAE,EACxE,EAAE;IACF,wDAAwD;IACxD,4DAA4D;IAC5D,sDAAsD;IACtD,IAAI,aAAa,EAAE,CAAC;QAClB,OAAO,oBAAoB,CAAC,CAAC;YACzB,CAAC,CAAC,OAAO,CAAC,cAAc,EAAE,MAAM,CAAC;YACnC,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,gBAAgB,EAAE,MAAM,CAAC,CAAA;IACzC,CAAC;IACD,OAAO,oBAAoB,CAAC,CAAC;QACzB,CAAC,CAAC,OAAO,CAAC,YAAY,EAAE,MAAM,CAAC;QACjC,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,cAAc,EAAE,MAAM,CAAC,CAAA;AACvC,CAAC,CAAA","sourcesContent":["import type { MinimatchOptions } from './index.js'\n\n/**\n * Escape all magic characters in a glob pattern.\n *\n * If the {@link MinimatchOptions.windowsPathsNoEscape}\n * option is used, then characters are escaped by wrapping in `[]`, because\n * a magic character wrapped in a character class can only be satisfied by\n * that exact character. In this mode, `\\` is _not_ escaped, because it is\n * not interpreted as a magic character, but instead as a path separator.\n *\n * If the {@link MinimatchOptions.magicalBraces} option is used,\n * then braces (`{` and `}`) will be escaped.\n */\nexport const escape = (\n s: string,\n {\n windowsPathsNoEscape = false,\n magicalBraces = false,\n }: Pick<MinimatchOptions, 'windowsPathsNoEscape' | 'magicalBraces'> = {},\n) => {\n // don't need to escape +@! because we escape the parens\n // that make those magic, and escaping ! as [!] isn't valid,\n // because [!]] is a valid glob class meaning not ']'.\n if (magicalBraces) {\n return windowsPathsNoEscape ?\n s.replace(/[?*()[\\]{}]/g, '[$&]')\n : s.replace(/[?*()[\\]\\\\{}]/g, '\\\\$&')\n }\n return windowsPathsNoEscape ?\n s.replace(/[?*()[\\]]/g, '[$&]')\n : s.replace(/[?*()[\\]\\\\]/g, '\\\\$&')\n}\n"]}
-174
View File
@@ -1,174 +0,0 @@
import { AST } from './ast.js';
export type Platform = 'aix' | 'android' | 'darwin' | 'freebsd' | 'haiku' | 'linux' | 'openbsd' | 'sunos' | 'win32' | 'cygwin' | 'netbsd';
export interface MinimatchOptions {
/** do not expand `{x,y}` style braces */
nobrace?: boolean;
/** do not treat patterns starting with `#` as a comment */
nocomment?: boolean;
/** do not treat patterns starting with `!` as a negation */
nonegate?: boolean;
/** print LOTS of debugging output */
debug?: boolean;
/** treat `**` the same as `*` */
noglobstar?: boolean;
/** do not expand extglobs like `+(a|b)` */
noext?: boolean;
/** return the pattern if nothing matches */
nonull?: boolean;
/** treat `\\` as a path separator, not an escape character */
windowsPathsNoEscape?: boolean;
/**
* inverse of {@link MinimatchOptions.windowsPathsNoEscape}
* @deprecated
*/
allowWindowsEscape?: boolean;
/**
* Compare a partial path to a pattern. As long as the parts
* of the path that are present are not contradicted by the
* pattern, it will be treated as a match. This is useful in
* applications where you're walking through a folder structure,
* and don't yet have the full path, but want to ensure that you
* do not walk down paths that can never be a match.
*/
partial?: boolean;
/** allow matches that start with `.` even if the pattern does not */
dot?: boolean;
/** ignore case */
nocase?: boolean;
/** ignore case only in wildcard patterns */
nocaseMagicOnly?: boolean;
/** consider braces to be "magic" for the purpose of `hasMagic` */
magicalBraces?: boolean;
/**
* 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`.
*/
matchBase?: boolean;
/** invert the results of negated matches */
flipNegate?: boolean;
/** do not collapse multiple `/` into a single `/` */
preserveMultipleSlashes?: boolean;
/**
* A number indicating the level of optimization that should be done
* to the pattern prior to parsing and using it for matches.
*/
optimizationLevel?: number;
/** operating system platform */
platform?: Platform;
/**
* When a pattern starts with a UNC path or drive letter, and in
* `nocase:true` mode, do not convert the root portions of the
* pattern into a case-insensitive regular expression, and instead
* leave them as strings.
*
* This is the default when the platform is `win32` and
* `nocase:true` is set.
*/
windowsNoMagicRoot?: boolean;
/**
* max number of `{...}` patterns to expand. Default 100_000.
*/
braceExpandMax?: number;
/**
* Max number of non-adjacent `**` patterns to recursively walk down.
*
* The default of 200 is almost certainly high enough for most purposes,
* and can handle absurdly excessive patterns.
*/
maxGlobstarRecursion?: number;
/**
* Max depth to traverse for nested extglobs like `*(a|b|c)`
*
* Default is 2, which is quite low, but any higher value
* swiftly results in punishing performance impacts. Note
* that this is *not* relevant when the globstar types can
* be safely coalesced into a single set.
*
* For example, `*(a|@(b|c)|d)` would be flattened into
* `*(a|b|c|d)`. Thus, many common extglobs will retain good
* performance and never hit this limit, even if they are
* excessively deep and complicated.
*
* If the limit is hit, then the extglob characters are simply
* not parsed, and the pattern effectively switches into
* `noextglob: true` mode for the contents of that nested
* sub-pattern. This will typically _not_ result in a match,
* but is considered a valid trade-off for security and
* performance.
*/
maxExtglobRecursion?: number;
}
export declare const minimatch: {
(p: string, pattern: string, options?: MinimatchOptions): boolean;
sep: Sep;
GLOBSTAR: typeof GLOBSTAR;
filter: (pattern: string, options?: MinimatchOptions) => (p: string) => boolean;
defaults: (def: MinimatchOptions) => typeof minimatch;
braceExpand: (pattern: string, options?: MinimatchOptions) => string[];
makeRe: (pattern: string, options?: MinimatchOptions) => false | MMRegExp;
match: (list: string[], pattern: string, options?: MinimatchOptions) => string[];
AST: typeof AST;
Minimatch: typeof Minimatch;
escape: (s: string, { windowsPathsNoEscape, magicalBraces, }?: Pick<MinimatchOptions, "windowsPathsNoEscape" | "magicalBraces">) => string;
unescape: (s: string, { windowsPathsNoEscape, magicalBraces, }?: Pick<MinimatchOptions, "windowsPathsNoEscape" | "magicalBraces">) => string;
};
export type Sep = '\\' | '/';
export declare const sep: Sep;
export declare const GLOBSTAR: unique symbol;
export declare const filter: (pattern: string, options?: MinimatchOptions) => (p: string) => boolean;
export declare const defaults: (def: MinimatchOptions) => typeof minimatch;
export declare const braceExpand: (pattern: string, options?: MinimatchOptions) => string[];
export declare const makeRe: (pattern: string, options?: MinimatchOptions) => false | MMRegExp;
export declare const match: (list: string[], pattern: string, options?: MinimatchOptions) => string[];
export type MMRegExp = RegExp & {
_src?: string;
_glob?: string;
};
export type ParseReturnFiltered = string | MMRegExp | typeof GLOBSTAR;
export type ParseReturn = ParseReturnFiltered | false;
export declare class Minimatch {
#private;
options: MinimatchOptions;
set: ParseReturnFiltered[][];
pattern: string;
windowsPathsNoEscape: boolean;
nonegate: boolean;
negate: boolean;
comment: boolean;
empty: boolean;
preserveMultipleSlashes: boolean;
partial: boolean;
globSet: string[];
globParts: string[][];
nocase: boolean;
isWindows: boolean;
platform: Platform;
windowsNoMagicRoot: boolean;
maxGlobstarRecursion: number;
regexp: false | null | MMRegExp;
constructor(pattern: string, options?: MinimatchOptions);
hasMagic(): boolean;
debug(..._: unknown[]): void;
make(): void;
preprocess(globParts: string[][]): string[][];
adjascentGlobstarOptimize(globParts: string[][]): string[][];
levelOneOptimize(globParts: string[][]): string[][];
levelTwoFileOptimize(parts: string | string[]): string[];
firstPhasePreProcess(globParts: string[][]): string[][];
secondPhasePreProcess(globParts: string[][]): string[][];
partsMatch(a: string[], b: string[], emptyGSMatch?: boolean): false | string[];
parseNegate(): void;
matchOne(file: string[], pattern: ParseReturn[], partial?: boolean): boolean;
braceExpand(): string[];
parse(pattern: string): ParseReturn;
makeRe(): false | MMRegExp;
slashSplit(p: string): string[];
match(f: string, partial?: boolean): boolean;
static defaults(def: MinimatchOptions): typeof Minimatch;
}
export { AST } from './ast.js';
export { escape } from './escape.js';
export { unescape } from './unescape.js';
//# sourceMappingURL=index.d.ts.map
-1
View File
@@ -1 +0,0 @@
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,GAAG,EAAE,MAAM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AE,EACX,YAAY,GAAE,OAAe,GAC5B,KAAK,GAAG,MAAM,EAAE;IA+CnB,WAAW;IAqBX,QAAQ,CACN,IAAI,EAAE,MAAM,EAAE,EACd,OAAO,EAAE,WAAW,EAAE,EACtB,OAAO,GAAE,OAAe;IAiX1B,WAAW;IAIX,KAAK,CAAC,OAAO,EAAE,MAAM,GAAG,WAAW;IA6CnC,MAAM;IAuGN,UAAU,CAAC,CAAC,EAAE,MAAM;IAepB,KAAK,CAAC,CAAC,EAAE,MAAM,EAAE,OAAO,UAAe;IAgEvC,MAAM,CAAC,QAAQ,CAAC,GAAG,EAAE,gBAAgB;CAGtC;AAED,OAAO,EAAE,GAAG,EAAE,MAAM,UAAU,CAAA;AAC9B,OAAO,EAAE,MAAM,EAAE,MAAM,aAAa,CAAA;AACpC,OAAO,EAAE,QAAQ,EAAE,MAAM,eAAe,CAAA"}
-1114
View File
File diff suppressed because it is too large. Load diff
-1
View File
@@ -1 +0,0 @@
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,iBAAiB,CAAA;AACxC,OAAO,EAAE,kBAAkB,EAAE,MAAM,2BAA2B,CAAA;AAE9D,OAAO,EAAE,GAAG,EAAE,MAAM,UAAU,CAAA;AAC9B,OAAO,EAAE,MAAM,EAAE,MAAM,aAAa,CAAA;AACpC,OAAO,EAAE,QAAQ,EAAE,MAAM,eAAe,CAAA;AAqHxC,MAAM,CAAC,MAAM,SAAS,GAAG,CACvB,CAAS,EACT,OAAe,EACf,UAA4B,EAAE,EAC9B,EAAE;IACF,kBAAkB,CAAC,OAAO,CAAC,CAAA;IAE3B,oCAAoC;IACpC,IAAI,CAAC,OAAO,CAAC,SAAS,IAAI,OAAO,CAAC,MAAM,CAAC,CAAC,CAAC,KAAK,GAAG,EAAE,CAAC;QACpD,OAAO,KAAK,CAAA;IACd,CAAC;IAED,OAAO,IAAI,SAAS,CAAC,OAAO,EAAE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,CAAC,EAAE,OAAO,EAAE,OAAO,CAAC,CAAA;AAClC,SAAS,CAAC,MAAM,GAAG,MAAM,CAAA;AAEzB,MAAM,GAAG,GAAG,CAAC,CAAmB,EAAE,IAAsB,EAAE,EAAE,EAAE,CAC5D,MAAM,CAAC,MAAM,CAAC,EAAE,EAAE,CAAC,EAAE,CAAC,CAAC,CAAA;AAEzB,MAAM,CAAC,MAAM,QAAQ,GAAG,CAAC,GAAqB,EAAoB,EAAE;IAClE,IAAI,CAAC,GAAG,IAAI,OLine truncated
-3
View File
@@ -1,3 +0,0 @@
{
"type": "module"
}
-22
View File
@@ -1,22 +0,0 @@
import type { MinimatchOptions } from './index.js';
/**
* Un-escape a string that has been escaped with {@link escape}.
*
* If the {@link MinimatchOptions.windowsPathsNoEscape} option is used, then
* square-bracket escapes are removed, but not backslash escapes.
*
* For example, it will turn the string `'[*]'` into `*`, but it will not
* turn `'\\*'` into `'*'`, because `\` is a path separator in
* `windowsPathsNoEscape` mode.
*
* When `windowsPathsNoEscape` is not set, then both square-bracket escapes and
* backslash escapes are removed.
*
* Slashes (and backslashes in `windowsPathsNoEscape` mode) cannot be escaped
* or unescaped.
*
* When `magicalBraces` is not set, escapes of braces (`{` and `}`) will not be
* unescaped.
*/
export declare const unescape: (s: string, { windowsPathsNoEscape, magicalBraces, }?: Pick<MinimatchOptions, "windowsPathsNoEscape" | "magicalBraces">) => string;
//# sourceMappingURL=unescape.d.ts.map
-1
View File
@@ -1 +0,0 @@
{"version":3,"file":"unescape.d.ts","sourceRoot":"","sources":["../../src/unescape.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,YAAY,CAAA;AAElD;;;;;;;;;;;;;;;;;;GAkBG;AAEH,eAAO,MAAM,QAAQ,GACnB,GAAG,MAAM,EACT,2CAGG,IAAI,CAAC,gBAAgB,EAAE,sBAAsB,GAAG,eAAe,CAAM,WAczE,CAAA"}
-34
View File
@@ -1,34 +0,0 @@
/**
* Un-escape a string that has been escaped with {@link escape}.
*
* If the {@link MinimatchOptions.windowsPathsNoEscape} option is used, then
* square-bracket escapes are removed, but not backslash escapes.
*
* For example, it will turn the string `'[*]'` into `*`, but it will not
* turn `'\\*'` into `'*'`, because `\` is a path separator in
* `windowsPathsNoEscape` mode.
*
* When `windowsPathsNoEscape` is not set, then both square-bracket escapes and
* backslash escapes are removed.
*
* Slashes (and backslashes in `windowsPathsNoEscape` mode) cannot be escaped
* or unescaped.
*
* When `magicalBraces` is not set, escapes of braces (`{` and `}`) will not be
* unescaped.
*/
export const unescape = (s, { windowsPathsNoEscape = false, magicalBraces = true, } = {}) => {
if (magicalBraces) {
return windowsPathsNoEscape ?
s.replace(/\[([^/\\])\]/g, '$1')
: s
.replace(/((?!\\).|^)\[([^/\\])\]/g, '$1$2')
.replace(/\\([^/])/g, '$1');
}
return windowsPathsNoEscape ?
s.replace(/\[([^/\\{}])\]/g, '$1')
: s
.replace(/((?!\\).|^)\[([^/\\{}])\]/g, '$1$2')
.replace(/\\([^/{}])/g, '$1');
};
//# sourceMappingURL=unescape.js.map
-1
View File
@@ -1 +0,0 @@
{"version":3,"file":"unescape.js","sourceRoot":"","sources":["../../src/unescape.ts"],"names":[],"mappings":"AAEA;;;;;;;;;;;;;;;;;;GAkBG;AAEH,MAAM,CAAC,MAAM,QAAQ,GAAG,CACtB,CAAS,EACT,EACE,oBAAoB,GAAG,KAAK,EAC5B,aAAa,GAAG,IAAI,MACgD,EAAE,EACxE,EAAE;IACF,IAAI,aAAa,EAAE,CAAC;QAClB,OAAO,oBAAoB,CAAC,CAAC;YACzB,CAAC,CAAC,OAAO,CAAC,eAAe,EAAE,IAAI,CAAC;YAClC,CAAC,CAAC,CAAC;iBACE,OAAO,CAAC,0BAA0B,EAAE,MAAM,CAAC;iBAC3C,OAAO,CAAC,WAAW,EAAE,IAAI,CAAC,CAAA;IACnC,CAAC;IACD,OAAO,oBAAoB,CAAC,CAAC;QACzB,CAAC,CAAC,OAAO,CAAC,iBAAiB,EAAE,IAAI,CAAC;QACpC,CAAC,CAAC,CAAC;aACE,OAAO,CAAC,4BAA4B,EAAE,MAAM,CAAC;aAC7C,OAAO,CAAC,aAAa,EAAE,IAAI,CAAC,CAAA;AACrC,CAAC,CAAA","sourcesContent":["import type { MinimatchOptions } from './index.js'\n\n/**\n * Un-escape a string that has been escaped with {@link escape}.\n *\n * If the {@link MinimatchOptions.windowsPathsNoEscape} option is used, then\n * square-bracket escapes are removed, but not backslash escapes.\n *\n * For example, it will turn the string `'[*]'` into `*`, but it will not\n * turn `'\\\\*'` into `'*'`, because `\\` is a path separator in\n * `windowsPathsNoEscape` mode.\n *\n * When `windowsPathsNoEscape` is not set, then both square-bracket escapes and\n * backslash escapes are removed.\n *\n * Slashes (and backslashes in `windowsPathsNoEscape` mode) cannot be escaped\n * or unescaped.\n *\n * When `magicalBraces` is not set, escapes of braces (`{` and `}`) will not be\n * unescaped.\n */\n\nexport const unescape = (\n s: string,\n {\n windowsPathsNoEscape = false,\n magicalBraces = true,\n }: Pick<MinimatchOptions, 'windowsPathsNoEscape' | 'magicalBraces'> = {},\n) => {\n if (magicalBraces) {\n return windowsPathsNoEscape ?\n s.replace(/\\[([^/\\\\])\\]/g, '$1')\n : s\n .replace(/((?!\\\\).|^)\\[([^/\\\\])\\]/g, '$1$2')\n .replace(/\\\\([^/])/g, '$1')\n }\n return windowsPathsNoEscape ?\n s.replace(/\\[([^/\\\\{}])\\]/g, '$1')\n : s\n .replace(/((?!\\\\).|^)\\[([^/\\\\{}])\\]/g, '$1$2')\n .replace(/\\\\([^/{}])/g, '$1')\n}\n"]}
-1950
View File
File diff suppressed because it is too large. Load diff
-4960
View File
File diff suppressed because it is too large. Load diff
-75
View File
@@ -1,75 +0,0 @@
{
"author": "Isaac Z. Schlueter <i@izs.me> (http://blog.izs.me)",
"name": "minimatch",
"description": "a glob matcher in javascript",
"version": "10.2.6",
"repository": {
"type": "git",
"url": "git@github.com:isaacs/minimatch"
},
"main": "./dist/commonjs/index.js",
"types": "./dist/commonjs/index.d.ts",
"exports": {
"./package.json": "./package.json",
".": {
"import": {
"types": "./dist/esm/index.d.ts",
"default": "./dist/esm/index.js"
},
"require": {
"types": "./dist/commonjs/index.d.ts",
"default": "./dist/commonjs/index.js"
}
}
},
"files": [
"dist"
],
"scripts": {
"preversion": "npm test",
"postversion": "npm publish",
"prepublishOnly": "git push origin --follow-tags",
"prepare": "tshy",
"pretest": "npm run prepare",
"presnap": "npm run prepare",
"test": "tap",
"snap": "tap",
"format": "prettier --write .",
"benchmark": "node benchmark/index.js",
"typedoc": "typedoc --tsconfig .tshy/esm.json ./src/*.ts",
"lint": "oxlint --fix src test",
"postsnap": "npm run lint",
"postlint": "npm run format",
"node-build": "esbuild ./dist/commonjs/index.js --bundle --platform=node --outfile=index.js"
},
"engines": {
"node": "18 || 20 || >=22"
},
"devDependencies": {
"@types/node": "^26.1.2",
"esbuild": "^0.28.1",
"mkdirp": "^3.0.1",
"oxlint": "^1.76.0",
"oxlint-tsgolint": "^7.0.2001",
"prettier": "^3.9.6",
"tap": "^21.7.5",
"tshy": "^4.1.3",
"typedoc": "^0.28.20"
},
"funding": {
"url": "https://github.com/sponsors/isaacs"
},
"license": "BlueOak-1.0.0",
"tshy": {
"exports": {
"./package.json": "./package.json",
".": "./src/index.ts"
},
"selfLink": false
},
"type": "module",
"module": "./dist/esm/index.js",
"dependencies": {
"brace-expansion": "^5.0.8"
}
}
+117 -9
View File
@@ -1456,7 +1456,7 @@ changes:
* `options` {Object}
* `cwd` {string|URL} current working directory. **Default:** `process.cwd()`
* `exclude` {Function|string\[]} Function to filter out files/directories or a
list of glob patterns to be excluded. If a function is provided, return
list of [glob patterns][] to be excluded. If a function is provided, return
`true` to exclude the item, `false` to include it. **Default:** `undefined`.
If a string array is provided, each string should be a glob pattern that
specifies paths to exclude. Note: Negation patterns (e.g., '!foo.js') are
@@ -1470,6 +1470,8 @@ changes:
* Returns: {AsyncIterator} An AsyncIterator that yields the paths of files
that match the pattern.
See [Glob patterns][] for the syntax `pattern` accepts.
When `followSymlinks` is enabled, detected symbolic link cycles are not
traversed recursively.
@@ -2257,9 +2259,10 @@ added:
queued than `maxQueue` allows. `'ignore'` means overflow events are dropped and a
warning is emitted, while `'error'` means to throw an exception. **Default:** `'ignore'`.
* `ignore` {string|RegExp|Function|Array} Pattern(s) to ignore. Strings are
glob patterns (using [`minimatch`][]), RegExp patterns are tested against
the filename, and functions receive the filename and return `true` to
ignore. **Default:** `undefined`.
[glob patterns][] that, when they contain no `/`, are matched against the
file's basename; RegExp patterns are tested against the filename, and
functions receive the filename and return `true` to ignore.
**Default:** `undefined`.
* Returns: {AsyncIterator} of objects with the properties:
* `eventType` {string} The type of change
* `filename` {string|Buffer|null} The name of the file changed.
@@ -3684,7 +3687,7 @@ changes:
* `options` {Object}
* `cwd` {string|URL} current working directory. **Default:** `process.cwd()`
* `exclude` {Function|string\[]} Function to filter out files/directories or a
list of glob patterns to be excluded. If a function is provided, return
list of [glob patterns][] to be excluded. If a function is provided, return
`true` to exclude the item, `false` to include it. **Default:** `undefined`.
* `followSymlinks` {boolean} When `true`, symbolic links to directories are
followed while expanding `**` patterns. **Default:** `false`.
@@ -3698,6 +3701,8 @@ changes:
* Retrieves the files matching the specified pattern.
See [Glob patterns][] for the syntax `pattern` accepts.
When `followSymlinks` is enabled, detected symbolic link cycles are not
traversed recursively.
@@ -5356,9 +5361,10 @@ changes:
* `throwIfNoEntry` {boolean} Indicates whether an exception should be thrown when the
path does not exist. **Default:** `true`.
* `ignore` {string|RegExp|Function|Array} Pattern(s) to ignore. Strings are
glob patterns (using [`minimatch`][]), RegExp patterns are tested against
the filename, and functions receive the filename and return `true` to
ignore. **Default:** `undefined`.
[glob patterns][] that, when they contain no `/`, are matched against the
file's basename; RegExp patterns are tested against the filename, and
functions receive the filename and return `true` to ignore.
**Default:** `undefined`.
* `listener` {Function|undefined} **Default:** `undefined`
* `eventType` {string}
* `filename` {string|Buffer|null}
@@ -6337,7 +6343,7 @@ changes:
* `options` {Object}
* `cwd` {string|URL} current working directory. **Default:** `process.cwd()`
* `exclude` {Function|string\[]} Function to filter out files/directories or a
list of glob patterns to be excluded. If a function is provided, return
list of [glob patterns][] to be excluded. If a function is provided, return
`true` to exclude the item, `false` to include it. **Default:** `undefined`.
* `followSymlinks` {boolean} When `true`, symbolic links to directories are
followed while expanding `**` patterns. **Default:** `false`.
@@ -6347,6 +6353,8 @@ changes:
`false` otherwise. **Default:** `false`.
* Returns: {string\[]} paths of files that match the pattern.
See [Glob patterns][] for the syntax `pattern` accepts.
When `followSymlinks` is enabled, detected symbolic link cycles are not
traversed recursively.
@@ -9273,6 +9281,101 @@ example `fs.readdirSync('C:\\')` can potentially return a different result than
`fs.readdirSync('C:')`. For more information, see
[this MSDN page][MSDN-Rel-Path].
### Glob patterns
[`fs.glob()`][], [`fs.globSync()`][], [`fsPromises.glob()`][] and
[`path.matchesGlob()`][] take glob patterns, as do the string forms of the
`exclude` and `ignore` options. The syntax follows the pattern matching of
`bash`, with brace expansion and the extended `extglob` operators.
The glob implementation Node.js uses was adopted from [`minimatch`][],
so as a general rule of thumb, all minimatch-supported glob extensions
work with `fs`. For simplicity, such extensions have been documented below:
#### Path separators
A pattern is always split on `/`, on every platform. A backslash in a pattern
is treated as a path separator as well, and never as an escape character, so
patterns built with `path.join()` on Windows still work. Repeated separators
are collapsed, so `a//b` and `a/b` are the same pattern.
#### Wildcards
Wildcards match within a single path segment, and never match a `/`:
| Pattern | Matches |
| ------------------ | ------------------------------------------ |
| `*` | Any run of characters, including none |
| `?` | Exactly one character |
| `[abc]` | Any one of the characters in the set |
| `[a-z]` | Any one character in the range |
| `[!abc]`, `[^abc]` | Any one character not in the set |
| `[[:alpha:]]` | Any one character in the named POSIX class |
```js
path.matchesGlob('src/index.js', 'src/*.js'); // true
path.matchesGlob('src/lib/index.js', 'src/*.js'); // false
path.matchesGlob('file1.txt', 'file[0-9].txt'); // true
path.matchesGlob('é', '[[:alpha:]]'); // true
```
#### Globstar
A `**` that makes up a whole path segment matches zero or more segments, so
`a/**/b` matches both `a/b` and `a/x/y/b`.
```js
path.matchesGlob('src/a/b/index.js', 'src/**/*.js'); // true
path.matchesGlob('src/index.js', 'src/**/*.js'); // true
```
#### Extended globs
Each of these takes a `|`-separated list of alternatives, and they may nest:
| Pattern | Matches |
| --------- | ------------------------------- |
| `?(a\|b)` | Zero or one of the alternatives |
| `*(a\|b)` | Zero or more of them |
| `+(a\|b)` | One or more of them |
| `@(a\|b)` | Exactly one of them |
| `!(a\|b)` | Anything except them |
```js
path.matchesGlob('index.ts', '*.@(js|ts)'); // true
path.matchesGlob('index.css', '!(*.js)'); // true
```
#### Brace expansion
Braces expand to alternatives before anything else in the pattern is
interpreted. `{a,b}` is a list, `{1..9}` and `{a..z}` are sequences, and a
sequence may take a step (`{1..9..3}`) and keep zero padding (`{01..12}`).
Braces nest. A brace group containing neither a comma nor a sequence is
literal.
```js
path.matchesGlob('src/index.ts', 'src/*.{js,ts}'); // true
path.matchesGlob('page3.html', 'page{1..5}.html'); // true
path.matchesGlob('a{b}c', 'a{b}c'); // true
```
#### Dot files
A path segment beginning with a `.` is matched only by a pattern segment
beginning with a literal `.`, so `*` and `**` do not match dot files or
directories.
```js
path.matchesGlob('.env', '*'); // false
path.matchesGlob('.env', '.*'); // true
```
#### Case sensitivity
Matching is case-sensitive, except on Windows and macOS, where the file system
is not case-sensitive itself.
### File descriptors
On POSIX systems, for every process, the kernel maintains a table of currently
@@ -9444,6 +9547,7 @@ the file contents.
[FS constants]: #fs-constants
[File access constants]: #file-access-constants
[File modes]: #file-modes
[Glob patterns]: #glob-patterns
[MDN-Date]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date
[MDN-Number]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Data_structures#number_type
[MSDN-Rel-Path]: https://docs.microsoft.com/en-us/windows/desktop/FileIO/naming-a-file#fully-qualified-vs-relative-paths
@@ -9473,6 +9577,8 @@ the file contents.
[`fs.fstat()`]: #fsfstatfd-options-callback
[`fs.ftruncate()`]: #fsftruncatefd-len-callback
[`fs.futimes()`]: #fsfutimesfd-atime-mtime-callback
[`fs.glob()`]: #fsglobpattern-options-callback
[`fs.globSync()`]: #fsglobsyncpattern-options
[`fs.lstat()`]: #fslstatpath-options-callback
[`fs.lutimes()`]: #fslutimespath-atime-mtime-callback
[`fs.mkdir()`]: #fsmkdirpath-options-callback
@@ -9501,6 +9607,7 @@ the file contents.
[`fs.writev()`]: #fswritevfd-buffers-position-callback
[`fsPromises.access()`]: #fspromisesaccesspath-mode
[`fsPromises.copyFile()`]: #fspromisescopyfilesrc-dest-mode
[`fsPromises.glob()`]: #fspromisesglobpattern-options
[`fsPromises.mkdtemp()`]: #fspromisesmkdtempprefix-options
[`fsPromises.open()`]: #fspromisesopenpath-flags-mode
[`fsPromises.opendir()`]: #fspromisesopendirpath-options
@@ -9511,6 +9618,7 @@ the file contents.
[`kqueue(2)`]: https://www.freebsd.org/cgi/man.cgi?query=kqueue&sektion=2
[`minimatch`]: https://github.com/isaacs/minimatch
[`node:stream/iter`]: stream_iter.md
[`path.matchesGlob()`]: path.md#pathmatchesglobpath-pattern
[`statfs.bsize`]: #statfsbsize
[`stream.getDefaultHighWaterMark()`]: stream.md#streamgetdefaulthighwatermarkobjectmode
[`stream/iter pipeTo()`]: stream_iter.md#pipetosource-transforms-writer-options
+2
View File
@@ -302,6 +302,7 @@ changes:
* Returns: {boolean} Whether or not the `path` matched the `pattern`.
The `path.matchesGlob()` method determines if `path` matches the `pattern`.
See [Glob patterns][] for the syntax `pattern` accepts.
For example:
@@ -657,6 +658,7 @@ of the `path` methods.
The API is accessible via `require('node:path').win32` or `require('node:path/win32')`.
[Glob patterns]: fs.md#glob-patterns
[MSDN-Rel-Path]: https://docs.microsoft.com/en-us/windows/desktop/FileIO/naming-a-file#fully-qualified-vs-relative-paths
[`TypeError`]: errors.md#class-typeerror
[`path.parse()`]: #pathparsepath
@@ -22,7 +22,6 @@ This a list of all the dependencies:
* [libffi][]
* [libuv][]
* [llhttp][]
* [minimatch][]
* [nghttp2][]
* [nghttp3][]
* [ngtcp2][]
@@ -296,11 +295,6 @@ The [llhttp](https://github.com/nodejs/llhttp) dependency is
the http parser used by Node.js.
See [maintaining-http][] for more information.
### minimatch
The [minimatch](https://github.com/isaacs/minimatch) dependency is a
minimal matching utility.
### nghttp2
The [nghttp2](https://github.com/nghttp2/nghttp2) dependency is a C library
@@ -432,7 +426,6 @@ according to [RFC 8878](https://datatracker.ietf.org/doc/html/rfc8878).
[maintaining-openssl]: ./maintaining-openssl.md
[maintaining-web-assembly]: ./maintaining-web-assembly.md
[merve]: #merve
[minimatch]: #minimatch
[nghttp2]: #nghttp2
[nghttp3]: #nghttp3
[ngtcp2]: #ngtcp2
+1 -2
View File
@@ -25,7 +25,6 @@
'use strict';
const {
ArrayFromAsync,
ArrayPrototypePush,
BigIntPrototypeToString,
FunctionPrototypeCall,
@@ -3916,7 +3915,7 @@ function glob(pattern, options, callback) {
const Glob = lazyGlob();
PromisePrototypeThen(
ArrayFromAsync(new Glob(pattern, options).glob()),
new Glob(pattern, options).globAll(),
(res) => callback(null, res),
callback,
);
+118 -1195
View File
File diff suppressed because it is too large. Load diff
+7 -16
View File
@@ -25,8 +25,6 @@ const {
const {
kEmptyObject,
getLazy,
isWindows,
isMacOS,
} = require('internal/util');
const {
@@ -79,7 +77,8 @@ const KFSStatWatcherRefCount = Symbol('KFSStatWatcherRefCount');
const KFSStatWatcherMaxRefCount = Symbol('KFSStatWatcherMaxRefCount');
const kFSStatWatcherAddOrCleanRef = Symbol('kFSStatWatcherAddOrCleanRef');
const lazyMinimatch = getLazy(() => require('internal/deps/minimatch/index'));
const lazyMatchGlobBasename =
getLazy(() => require('internal/fs/glob').matchGlobBasename);
/**
* Creates an ignore matcher function from the ignore option.
@@ -94,19 +93,11 @@ function createIgnoreMatcher(ignore) {
for (let i = 0; i < matchers.length; i++) {
const matcher = matchers[i];
if (typeof matcher === 'string') {
const mm = new (lazyMinimatch().Minimatch)(matcher, {
__proto__: null,
nocase: isWindows || isMacOS,
windowsPathsNoEscape: true,
nonegate: true,
nocomment: true,
optimizationLevel: 2,
platform: process.platform,
// matchBase allows patterns without slashes to match the basename
// e.g., '*.log' matches 'subdir/file.log'
matchBase: true,
});
ArrayPrototypePush(compiled, (filename) => mm.match(filename));
// A pattern without a separator matches the basename, so '*.log'
// matches 'subdir/file.log'.
const matchGlobBasename = lazyMatchGlobBasename();
ArrayPrototypePush(compiled,
(filename) => matchGlobBasename(filename, matcher));
} else if (isRegExp(matcher)) {
ArrayPrototypePush(compiled, (filename) => RegExpPrototypeExec(matcher, filename) !== null);
} else {
+24 -35
View File
@@ -27,7 +27,7 @@ const {
readFileSync,
rmSync,
} = require('fs');
const { setupCoverageHooks } = require('internal/util');
const { isWindows, setupCoverageHooks } = require('internal/util');
const { tmpdir } = require('os');
const { join, resolve, relative } = require('path');
const { fileURLToPath, pathToFileURL, URL } = require('internal/url');
@@ -39,7 +39,7 @@ const {
ERR_SOURCE_MAP_MISSING_SOURCE,
},
} = require('internal/errors');
const { createMatcher } = require('internal/fs/glob');
const { matchGlobPattern } = require('internal/fs/glob');
const { constants: { kMockSearchParam } } = require('internal/test_runner/mock/loader');
const kCoverageFileRegex = /^coverage-(\d+)-(\d{13})-(\d+)\.json$/;
@@ -47,9 +47,6 @@ const kIgnoreRegex = /\/\* node:coverage ignore next (?<count>\d+ )?\*\//;
const kLineEndingRegex = /\r?\n$/u;
const kLineSplitRegex = /(?<=\r?\n)/u;
const kStatusRegex = /\/\* node:coverage (?<status>enable|disable) \*\//;
// Match dotfiles (e.g. `test/.foo.js`) when applying coverage globs so the
// default exclude patterns cover them.
const kMatchGlobPatternOptions = { __proto__: null, dot: true };
const kTypeOnlyImportRegex = /^\s*import\s+type\b/u;
const kTypeScriptSourceRegex = /\.(?:cts|mts|ts)$/u;
const kSourceFileGlob = '**/*.{cjs,cts,js,mjs,mts,ts}';
@@ -66,12 +63,13 @@ function getStripTypeScriptTypesForCoverage() {
return stripTypeScriptTypesForCoverage;
}
function createCoverageMatcher(pattern) {
return {
__proto__: null,
relative: createMatcher(pattern, kMatchGlobPatternOptions),
absolute: createMatcher(pattern),
};
// Match the relative path with `dot` enabled so globs cover dotfiles within
// the project (e.g. `test/.foo.js`), while keeping plain matching for the
// absolute path to avoid misinterpreting dot segments in the filesystem path
// (e.g. tmp dirs like `test/.tmp.0`).
function matchesCoverageGlob(relativePath, absolutePath, pattern) {
return matchGlobPattern(relativePath, pattern, isWindows, true) ||
matchGlobPattern(absolutePath, pattern);
}
class CoverageLine {
@@ -100,8 +98,6 @@ class TestCoverage {
#sourceLines = new SafeMap();
#typeScriptLines = new SafeSet();
#skipCache = new SafeMap();
#excludeMatchers = null;
#includeMatchers = null;
getLines(fileUrl, source) {
// Split the file source into lines. Make sure the lines maintain their
@@ -612,32 +608,25 @@ class TestCoverage {
const absolutePath = fileURLToPath(url);
const relativePath = relative(this.options.cwd, absolutePath);
// The exclude/include globs are fixed for the lifetime of this
// TestCoverage instance, so compile each glob to a matcher once and reuse
// it for every file. Building a fresh Minimatch per call (the previous
// behavior) dominated the coverage report time, scaling with
// files * globs. Each glob compiles to a matcher pair: `relative` enables
// dot:true so globs match dotfiles within the project, while `absolute`
// keeps the default behavior to avoid misinterpreting dot segments in the
// absolute filesystem path (e.g. tmp dirs like `test/.tmp.0`).
this.#excludeMatchers ??= ArrayPrototypeMap(
this.options.coverageExcludeGlobs ?? [], createCoverageMatcher);
this.#includeMatchers ??= ArrayPrototypeMap(
this.options.coverageIncludeGlobs ?? [], createCoverageMatcher);
const excludeGlobs = this.options.coverageExcludeGlobs ?? [];
const includeGlobs = this.options.coverageIncludeGlobs ?? [];
// This check filters out files that match the exclude globs.
for (let i = 0; i < this.#excludeMatchers.length; ++i) {
const matcher = this.#excludeMatchers[i];
if (matcher.relative.match(relativePath) ||
matcher.absolute.match(absolutePath)) return true;
// TODO(@avivkeller): Now that globbing is native in CPP,
// Maybe we can filter these out of the inspector profile
// directly, stopping them from ever crossing the boundary,
// speeding up perf?
for (let i = 0; i < excludeGlobs.length; ++i) {
if (matchesCoverageGlob(relativePath, absolutePath, excludeGlobs[i])) {
return true;
}
}
// This check filters out files that do not match the include globs.
if (this.#includeMatchers.length > 0) {
for (let i = 0; i < this.#includeMatchers.length; ++i) {
const matcher = this.#includeMatchers[i];
if (matcher.relative.match(relativePath) ||
matcher.absolute.match(absolutePath)) return false;
if (includeGlobs.length > 0) {
for (let i = 0; i < includeGlobs.length; ++i) {
if (matchesCoverageGlob(relativePath, absolutePath, includeGlobs[i])) {
return false;
}
}
return true;
}
+1 -2
View File
@@ -2,7 +2,6 @@
const {
ArrayIsArray,
ArrayPrototypeEvery,
ArrayPrototypeFilter,
ArrayPrototypeFind,
ArrayPrototypeForEach,
@@ -181,7 +180,7 @@ function createTestFileList(patterns, cwd) {
});
const results = glob.globSync();
if (hasUserSuppliedPattern && results.length === 0 && ArrayPrototypeEvery(glob.matchers, (m) => !m.hasMagic())) {
if (hasUserSuppliedPattern && results.length === 0 && !glob.hasMagic) {
console.error(`Could not find '${ArrayPrototypeJoin(patterns, ', ')}'`);
process.exit(kGenericUserError);
}
+13 -1
View File
@@ -76,7 +76,6 @@
'deps/v8/tools/tickprocessor-driver.mjs',
'deps/acorn/acorn/dist/acorn.js',
'deps/acorn/acorn-walk/dist/walk.js',
'deps/minimatch/index.js',
'<@(node_builtin_shareable_builtins)',
],
'node_sources': [
@@ -103,6 +102,12 @@
'src/encoding_binding.cc',
'src/env.cc',
'src/fs_event_wrap.cc',
'src/glob/glob_matcher.cc',
'src/glob/glob_unicode.cc',
'src/glob/glob_walker.cc',
'src/glob/node_glob.cc',
'src/glob/glob_parser.cc',
'src/glob/glob_program.cc',
'src/handle_wrap.cc',
'src/heap_utils.cc',
'src/histogram.cc',
@@ -259,6 +264,13 @@
'src/node_errors.h',
'src/node_exit_code.h',
'src/node_external_reference.h',
'src/glob/glob_ast.h',
'src/glob/glob_matcher.h',
'src/glob/glob_parser.h',
'src/glob/glob_program.h',
'src/glob/glob_unicode.h',
'src/glob/glob_walker.h',
'src/glob/node_glob.h',
'src/node_file.h',
'src/node_file-inl.h',
'src/node_http_common.h',
+1
View File
@@ -41,6 +41,7 @@ namespace node {
V(BLOBREADER) \
V(FSEVENTWRAP) \
V(FSREQCALLBACK) \
V(GLOBREQUEST) \
V(FSREQPROMISE) \
V(GETADDRINFOREQWRAP) \
V(GETNAMEINFOREQWRAP) \
+1
View File
@@ -12,6 +12,7 @@ namespace node {
#define SERIALIZABLE_BINDING_TYPES(V) \
V(diagnostics_channel_binding_data, diagnostics_channel::BindingData) \
V(encoding_binding_data, encoding_binding::BindingData) \
V(glob_binding_data, glob::BindingData) \
V(fs_binding_data, fs::BindingData) \
V(mksnapshot_binding_data, mksnapshot::BindingData) \
V(v8_binding_data, v8_utils::BindingData) \
+1
View File
@@ -440,6 +440,7 @@
V(dtls_context_constructor_template, v8::FunctionTemplate) \
V(dtls_endpoint_constructor_template, v8::FunctionTemplate) \
V(dtls_session_constructor_template, v8::FunctionTemplate) \
V(glob_request_template, v8::FunctionTemplate) \
V(fd_constructor_template, v8::ObjectTemplate) \
V(fdclose_constructor_template, v8::ObjectTemplate) \
V(ffi_dynamic_library_constructor_template, v8::FunctionTemplate) \
+136
View File
@@ -0,0 +1,136 @@
#ifndef SRC_GLOB_GLOB_AST_H_
#define SRC_GLOB_GLOB_AST_H_
#include <algorithm>
#include <cstdint>
#include <memory>
#include <string>
#include <string_view>
#include <vector>
namespace node::glob {
// UTF-16, because that is how patterns arrive from V8
using PatternString = std::u16string;
using PatternView = std::u16string_view;
struct CompileFlags {
bool windows = false;
bool nocase = false;
// With nocase, fold case in magic segments only; literal segments keep
// matching exactly (minimatch's nocaseMagicOnly, which fs.glob and
// path.matchesGlob enable). Cleared for exclude patterns, see
// ReadWalkArguments().
bool nocase_magic_only = true;
bool dot = false;
bool match_base = false;
};
constexpr bool IsAsciiLetter(uint32_t c) {
return (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z');
}
constexpr bool IsLineTerminator(uint32_t c) {
return c == '\n' || c == '\r' || c == 0x2028 || c == 0x2029;
}
template <typename A, typename B>
bool UnitsEqual(std::basic_string_view<A> a, std::basic_string_view<B> b) {
return std::ranges::equal(a, b, [](A x, B y) {
return static_cast<uint32_t>(x) == static_cast<uint32_t>(y);
});
}
template <typename Char>
bool StartsWithWindowsDrive(std::basic_string_view<Char> s) {
return s.size() >= 2 && s[1] == ':' && IsAsciiLetter(s[0]);
}
template <typename Char>
bool IsWindowsDrive(std::basic_string_view<Char> s) {
return s.size() == 2 && StartsWithWindowsDrive(s);
}
// Caps on what one pattern may cost, inherited from minimatch
inline constexpr size_t kMaxPatternLength = 64 * 1024;
// Nesting depth for extglobs like `*(a|@(b|c))`
inline constexpr int kMaxExtglobRecursion = 2;
// Non-adjacent `**` parts one match may recurse through
inline constexpr int kMaxGlobstarRecursion = 200;
// How far, in number of braces, braces may expand
inline constexpr size_t kBraceExpansionMax = 100'000;
// How far, in length, braces may expand
inline constexpr size_t kBraceExpansionMaxLength = 4'000'000;
// Braces and extglobs are parsed by recursing once per level of nesting, so
// nesting deep enough to exhaust the C stack has to be refused up front:
// `@(` and `{,` cost two or three code units per level, which leaves room for
// thousands of levels under kMaxPatternLength. Minimatch has no such cap and
// simply throws RangeError once V8's stack runs out. Real patterns nest a
// handful of levels, and 256 keeps the parser under ~150 KB of stack even on
// the smallest worker thread stacks.
inline constexpr int kMaxNestingDepth = 256;
enum class CompileError {
kNone,
kPatternTooLong,
kPatternTooDeep,
kInvalidRegExp,
};
// One node of the per-segment extglob AST, ported from minimatch's AST
// class (ast.js)
struct SegmentNode {
struct Part {
// Exactly one of these is meaningful: `child` when non-null, else `text`.
PatternString text;
SegmentNode* child = nullptr;
Part() = default;
explicit Part(PatternString t) : text(std::move(t)) {}
explicit Part(SegmentNode* c) : child(c) {}
bool is_child() const { return child != nullptr; }
};
using Parts = std::vector<Part>;
char type = 0;
std::shared_ptr<Parts> parts = std::make_shared<Parts>();
// Set when an extglob closed with no contents: `!()`, `@()`, ...
bool empty_ext = false;
// Tree links used by flatten and fill-negs
SegmentNode* parent = nullptr;
size_t parent_index = 0;
bool is_extglob() const { return type != 0; }
// isStart() / isEnd() from Minimatch's ast.js
bool IsStart() const;
bool IsEnd() const;
// AST.toString()
PatternString ToString() const;
};
struct SegmentTree {
SegmentNode* root = nullptr;
std::vector<std::unique_ptr<SegmentNode>> arena;
};
struct PathPart {
enum class Kind : uint8_t { kGlobstar, kSegment };
Kind kind = Kind::kSegment;
PatternString source;
SegmentTree segment;
};
struct ParsedPattern {
struct Row {
std::vector<PathPart> parts;
};
std::vector<Row> rows;
bool empty = false;
};
} // namespace node::glob
#endif // SRC_GLOB_GLOB_AST_H_
+755
View File
@@ -0,0 +1,755 @@
#include "glob/glob_matcher.h"
#include <algorithm>
#include <bit>
#include <limits>
#include <ranges>
#include <span>
#include "glob/glob_parser.h"
#include "glob/glob_unicode.h"
#include "util-inl.h"
namespace node::glob {
namespace {
// The set of positions in the subject a segment's program can currently be
// at. Carrying every position at once is what makes matching linear in
// (positions x nodes) instead of backtracking, so a pattern like
// `*(a|aa)*(a|aa)b` costs the same as any other.
class PosSet {
public:
void Init(size_t positions) {
nwords_ = (positions + kBitsPerWord - 1) / kBitsPerWord;
if (nwords_ > kInlineWords)
heap_.assign(nwords_, 0);
else
std::fill_n(inline_, nwords_, 0);
}
void Set(size_t i) {
words()[i >> kWordShift] |= uint64_t{1} << (i & kBitInWordMask);
}
bool Test(size_t i) const {
return (words()[i >> kWordShift] >> (i & kBitInWordMask)) & 1;
}
bool Empty() const {
return std::ranges::all_of(words(), [](uint64_t v) { return v == 0; });
}
template <typename F>
void ForEach(F&& f) const {
const std::span<const uint64_t> ws = words();
for (size_t w = 0; w < nwords_; w++) {
uint64_t word = ws[w];
while (word != 0) {
f(w * kBitsPerWord + std::countr_zero(word));
word &= word - 1;
}
}
}
void UnionWith(const PosSet& other) {
const std::span<uint64_t> w = words();
const std::span<const uint64_t> o = other.words();
for (size_t i = 0; i < nwords_; i++) w[i] |= o[i];
}
private:
static constexpr size_t kBitsPerWord = std::numeric_limits<uint64_t>::digits;
static constexpr size_t kWordShift = std::countr_zero(kBitsPerWord);
static constexpr size_t kBitInWordMask = kBitsPerWord - 1;
// Four words hold 256 positions, one more than the longest name the
// common filesystems allow, so only a synthetic subject reaches the heap.
static constexpr size_t kInlineWords = 4;
std::span<uint64_t> words() {
return {nwords_ <= kInlineWords ? inline_ : heap_.data(), nwords_};
}
std::span<const uint64_t> words() const {
return {nwords_ <= kInlineWords ? inline_ : heap_.data(), nwords_};
}
size_t nwords_ = 0;
uint64_t inline_[kInlineWords];
std::vector<uint64_t> heap_;
};
template <typename Char>
class SegmentEvaluator {
public:
using View = std::basic_string_view<Char>;
SegmentEvaluator(const SegmentProgram& p, View in)
: p_(p), in_(in), n_(in.size()) {}
bool Accepts() {
if (p_.start_no_traversal && IsDotSegment()) return false;
if (p_.start_no_dot && in_.starts_with('.')) return false;
PosSet start;
start.Init(n_ + 1);
start.Set(0);
PosSet out = Reach(p_.root, start);
return out.Test(n_);
}
private:
bool IsDotSegment() const {
return (n_ == 1 && in_[0] == '.') ||
(n_ == 2 && in_[0] == '.' && in_[1] == '.');
}
// one code point (uflag) or code unit (non-u) at pos; len ∈ {1, 2}.
uint32_t CharAt(size_t pos, size_t* len) const {
const uint32_t c = in_[pos];
if constexpr (sizeof(Char) > 1) {
if (p_.uflag && IsUnicodeLead(c) && pos + 1 < n_ &&
IsUnicodeTrail(in_[pos + 1])) {
*len = 2;
return CombineSurrogates(c, in_[pos + 1]);
}
}
*len = 1;
return c;
}
bool UnitsEqualFolded(uint32_t a, uint32_t b) const {
if (a == b) return true;
if (!p_.nocase) return false;
return Canonicalize(a, p_.uflag) == Canonicalize(b, p_.uflag);
}
// Match a literal run at pos; returns end position or SIZE_MAX.
size_t TextAt(const PatternString& text, size_t pos) const {
if (!p_.nocase) {
if (pos + text.size() > n_) return SIZE_MAX;
for (size_t i = 0; i < text.size(); i++) {
if (static_cast<uint32_t>(in_[pos + i]) !=
static_cast<uint32_t>(text[i])) {
return SIZE_MAX;
}
}
return pos + text.size();
}
// folded comparison, unit-wise (non-u) or cp-wise (u)
size_t ip = pos;
size_t tp = 0;
while (tp < text.size()) {
if (ip >= n_) return SIZE_MAX;
if (p_.uflag && sizeof(Char) > 1) {
size_t il;
const uint32_t ic = CharAt(ip, &il);
const char16_t tc0 = text[tp];
uint32_t tc = tc0;
size_t tl = 1;
if (IsUnicodeLead(tc0) && tp + 1 < text.size() &&
IsUnicodeTrail(text[tp + 1])) {
tc = CombineSurrogates(tc0, text[tp + 1]);
tl = 2;
}
if (!UnitsEqualFolded(ic, tc)) return SIZE_MAX;
ip += il;
tp += tl;
} else {
if (!UnitsEqualFolded(in_[ip], text[tp])) return SIZE_MAX;
ip++;
tp++;
}
}
return ip;
}
// A class matches when some member is case-equivalent to the subject, and
// only then is the polarity applied.
bool ClassMatches(const RxNode::CharClass& k, uint32_t c) const {
if (p_.nocase && !p_.uflag) c = Canonicalize(c, /*fold=*/false);
if (k.has_positive && (k.positive.Contains(c) != k.negate)) return true;
if (k.has_negative && (k.negative.Contains(c) == k.negate)) return true;
return false;
}
// [^/]*? expansion from position p into `out`
void StarChain(size_t p, bool no_empty, PosSet* out) const {
size_t q = p;
bool first = true;
while (true) {
if (!first || !no_empty) {
if (out->Test(q)) return; // chain from q already marked
out->Set(q);
}
if (q >= n_ || in_[q] == '/') return;
size_t len;
CharAt(q, &len);
q += len;
first = false;
}
}
bool GuardMatchesToEnd(const RxNode& neg, size_t p) {
PosSet start;
start.Init(n_ + 1);
start.Set(p);
for (uint32_t child : neg.children) {
PosSet r = Reach(child, start);
if (r.Test(n_)) return true;
}
return false;
}
// Kleene closure of `body` applied to `seed`.
PosSet Closure(uint32_t body, const PosSet& seed) {
PosSet out = seed;
PosSet frontier = seed;
while (!frontier.Empty()) {
PosSet next = Reach(body, frontier);
PosSet fresh;
fresh.Init(n_ + 1);
bool any = false;
next.ForEach([&](size_t pos) {
if (!out.Test(pos)) {
fresh.Set(pos);
out.Set(pos);
any = true;
}
});
if (!any) break;
frontier = fresh;
}
return out;
}
PosSet Reach(uint32_t id, const PosSet& in) {
const RxNode& node = p_.nodes[id];
PosSet out;
out.Init(n_ + 1);
switch (node.kind) {
case RxNode::Kind::kEmpty:
return in;
case RxNode::Kind::kAssert:
in.ForEach([&](size_t pos) {
if (node.assert_no_dot && pos < n_ && in_[pos] == '.') return;
if (node.assert_no_traversal && pos == 0 && IsDotSegment()) {
return;
}
out.Set(pos);
});
return out;
case RxNode::Kind::kText:
in.ForEach([&](size_t pos) {
const size_t end = TextAt(node.text, pos);
if (end != SIZE_MAX) out.Set(end);
});
return out;
case RxNode::Kind::kAnyChar:
in.ForEach([&](size_t pos) {
if (pos >= n_ || in_[pos] == '/') return;
size_t len;
CharAt(pos, &len);
out.Set(pos + len);
});
return out;
case RxNode::Kind::kClass:
in.ForEach([&](size_t pos) {
if (pos >= n_) return;
size_t len;
const uint32_t c = CharAt(pos, &len);
if (ClassMatches(node.klass, c)) out.Set(pos + len);
});
return out;
case RxNode::Kind::kStarAny:
in.ForEach([&](size_t pos) {
if (node.star_no_dot && pos < n_ && in_[pos] == '.') return;
StarChain(pos, node.star_no_empty, &out);
});
return out;
case RxNode::Kind::kConcat: {
PosSet cur = in;
for (uint32_t child : node.children) {
cur = Reach(child, cur);
if (cur.Empty()) break;
}
return cur;
}
case RxNode::Kind::kAlt: {
for (uint32_t child : node.children) {
PosSet r = Reach(child, in);
out.UnionWith(r);
}
return out;
}
case RxNode::Kind::kOpt: {
out = in;
PosSet r = Reach(node.children[0], in);
out.UnionWith(r);
return out;
}
case RxNode::Kind::kStar:
return Closure(node.children[0], in);
case RxNode::Kind::kPlus: {
PosSet once = Reach(node.children[0], in);
return Closure(node.children[0], once);
}
case RxNode::Kind::kTwoBody: {
// (?:first)(?:rest)*?
PosSet first = Reach(node.children[0], in);
return Closure(node.children[1], first);
}
case RxNode::Kind::kNeg: {
in.ForEach([&](size_t pos) {
if (node.star_no_dot && pos < n_ && in_[pos] == '.') return;
if (GuardMatchesToEnd(node, pos)) return;
StarChain(pos, /*no_empty=*/false, &out);
});
return out;
}
}
return out;
}
const SegmentProgram& p_;
View in_;
const size_t n_;
};
template <typename Char>
bool EndsWith(std::basic_string_view<Char> s, PatternView suffix) {
return s.size() >= suffix.size() &&
UnitsEqual(s.substr(s.size() - suffix.size()), suffix);
}
// `f.toLowerCase().endsWith(ext.toLowerCase())`
template <typename Char>
bool EndsWithLowered(std::basic_string_view<Char> f, PatternView lowered_ext) {
const bool ascii = std::ranges::all_of(
f, [](Char c) { return static_cast<uint32_t>(c) <= kMaxAsciiCodePoint; });
if (ascii) {
return f.size() >= lowered_ext.size() &&
std::ranges::equal(lowered_ext,
f.substr(f.size() - lowered_ext.size()),
[](char16_t ext, Char c) {
return static_cast<uint32_t>(ext) ==
AsciiLower(static_cast<uint32_t>(c));
});
}
PatternString widened(f.begin(), f.end());
PatternString lowered;
AppendLowered(widened, &lowered);
return EndsWith<char16_t>(lowered, lowered_ext);
}
template <typename Char>
bool IsDots(std::basic_string_view<Char> f) {
return (f.size() == 1 && f[0] == '.') ||
(f.size() == 2 && f[0] == '.' && f[1] == '.');
}
template <typename Char>
bool Equals(std::basic_string_view<Char> f, PatternView text) {
return UnitsEqual(f, text);
}
// /^text$/i without the 'u' flag: code units compared under Canonicalize
template <typename Char>
bool EqualsFolded(std::basic_string_view<Char> f, PatternView text) {
if (f.size() != text.size()) return false;
for (size_t i = 0; i < f.size(); i++) {
const uint32_t a = static_cast<uint32_t>(f[i]);
const uint32_t b = static_cast<uint32_t>(text[i]);
if (a != b && Canonicalize(a, false) != Canonicalize(b, false)) {
return false;
}
}
return true;
}
template <typename Char>
bool TestSegmentImpl(const SegmentProgram& p, std::basic_string_view<Char> f) {
switch (p.tier) {
case SegmentProgram::Tier::kEmpty:
return f.empty();
case SegmentProgram::Tier::kLiteral:
if (p.nocase) return EqualsFolded(f, p.literal);
return Equals(f, p.literal);
case SegmentProgram::Tier::kStar:
// starTest / starTestDot
if (f.empty()) return false;
return p.dot ? !IsDots(f) : !f.starts_with('.');
case SegmentProgram::Tier::kStarDotExt: {
if (!p.dot && f.starts_with('.')) return false;
if (p.nocase) return EndsWithLowered(f, p.literal_lower);
return EndsWith(f, p.literal);
}
case SegmentProgram::Tier::kStarDotStar: {
const bool has_dot =
f.find(static_cast<Char>('.')) != std::basic_string_view<Char>::npos;
if (p.dot) return !IsDots(f) && has_dot;
return !f.starts_with('.') && has_dot;
}
case SegmentProgram::Tier::kDotStar:
return !IsDots(f) && f.starts_with('.');
case SegmentProgram::Tier::kQmarks: {
if (f.size() != p.qmarks_len) return false;
if (p.dot) {
if (IsDots(f)) return false;
} else if (f.starts_with('.')) {
return false;
}
if (p.literal.empty()) return true;
if (p.nocase) return EndsWithLowered(f, p.literal_lower);
return EndsWith(f, p.literal);
}
case SegmentProgram::Tier::kRegex: {
SegmentEvaluator<Char> ev(p, f);
return ev.Accepts();
}
}
return false;
}
template <typename Char>
bool TestPartImpl(const PartMatcher& part, std::basic_string_view<Char> f) {
switch (part.kind) {
case PartMatcher::Kind::kGlobstar:
return false; // handled structurally by the path matcher
case PartMatcher::Kind::kLiteral:
return Equals(f, part.literal);
case PartMatcher::Kind::kProgram:
return TestSegmentImpl(part.program, f);
}
return false;
}
} // namespace
bool TestPart(const PartMatcher& part, PatternView f) {
return TestPartImpl<char16_t>(part, f);
}
bool TestPart(const PartMatcher& part, OneByteView f) {
return TestPartImpl<char8_t>(part, f);
}
namespace {
template <typename Char>
class PathMatcher {
public:
using View = std::basic_string_view<Char>;
// The file's path parts as views
using Parts = std::span<const View>;
explicit PathMatcher(const CompiledPattern& pat) : pat_(&pat) {}
bool Match(View path) {
if (pat_->empty) return path.empty();
View f = path;
if (pat_->flags.windows &&
path.find(static_cast<Char>('\\')) != View::npos) {
rewritten_.assign(path.begin(), path.end());
for (Char& c : rewritten_) {
if (c == '\\') c = '/';
}
f = View(rewritten_.data(), rewritten_.size());
}
Parts file = SplitViews(f);
View basename;
if (pat_->flags.match_base) {
for (const View& part : file | std::views::reverse) {
if (!part.empty()) {
basename = part;
break;
}
}
}
if (std::ranges::any_of(file, IsDots<Char>)) file = NormalizeFile(file);
for (const CompiledPattern::Row& row : pat_->rows) {
if (pat_->flags.match_base && row.parts.size() == 1) {
const Parts only{&basename, 1};
if (MatchOne(only, row)) return true;
continue;
}
if (MatchOne(file, row)) return true;
}
return false;
}
private:
using RowParts = std::vector<PartMatcher>;
// Path depth held without allocating. Deeper paths still work; they just
// grow the buffer, and they are rare enough not to matter.
static constexpr size_t kInlineParts = 32;
// Minimatch#slashSplit
Parts SplitViews(View f) {
size_t count = 0;
auto push = [&](View v) {
if (count == parts_.capacity()) {
parts_.SetLength(count);
parts_.AllocateSufficientStorage(count * 2);
}
parts_.out()[count++] = v;
};
SlashSplitInto(f, pat_->flags.windows, push);
return {parts_.out(), count};
}
Parts NormalizeFile(Parts file) {
owned_.clear();
owned_.reserve(file.size());
for (size_t i = 0; i < file.size(); i++) {
owned_.emplace_back(file[i].begin(), file[i].end());
}
LevelTwoFileOptimize(&owned_, pat_->flags);
owned_views_.clear();
owned_views_.reserve(owned_.size());
for (const std::basic_string<Char>& s : owned_) {
owned_views_.emplace_back(s);
}
return {owned_views_.data(), owned_views_.size()};
}
static bool PartIsLiteral(const PartMatcher& p, PatternView text) {
return p.kind == PartMatcher::Kind::kLiteral &&
PatternView(p.literal) == text;
}
bool MatchOne(Parts file, const CompiledPattern::Row& row) {
size_t file_start = 0;
size_t pattern_start = 0;
const RowParts& pattern = row.parts;
if (pat_->flags.windows) {
const bool file_drive = !file.empty() && IsWindowsDrive<Char>(file[0]);
const bool file_unc = !file_drive && file.size() > 3 && file[0].empty() &&
file[1].empty() && file[2].size() == 1 &&
file[2][0] == '?' && IsWindowsDrive<Char>(file[3]);
const bool pattern_drive =
!pattern.empty() && pattern[0].kind == PartMatcher::Kind::kLiteral &&
IsWindowsDrive<char16_t>(pattern[0].literal);
const bool pattern_unc = !pattern_drive && pattern.size() > 3 &&
PartIsLiteral(pattern[0], u"") &&
PartIsLiteral(pattern[1], u"") &&
PartIsLiteral(pattern[2], u"?") &&
pattern[3].kind == PartMatcher::Kind::kLiteral &&
IsWindowsDrive<char16_t>(pattern[3].literal);
const ptrdiff_t fdi = file_unc ? 3 : file_drive ? 0 : -1;
const ptrdiff_t pdi = pattern_unc ? 3 : pattern_drive ? 0 : -1;
if (fdi >= 0 && pdi >= 0) {
const View fd = file[fdi];
const PatternString& pd = pattern[pdi].literal;
if (fd.size() == pd.size() && AsciiLower(fd[0]) == AsciiLower(pd[0]) &&
static_cast<uint32_t>(fd[1]) == static_cast<uint32_t>(pd[1])) {
// minimatch rewrites its compiled drive letter to the file's and
// matches on from there; comparing here and stepping past both is
// the same thing without mutating the shared compiled pattern.
pattern_start = pdi + 1;
file_start = fdi + 1;
}
}
}
if (row.has_globstar) {
return MatchGlobstar(file, pattern, file_start, pattern_start) ==
Tri::kTrue;
}
return MatchLinear(
file, file.size(), pattern, pattern_start, pattern.size(), file_start);
}
// #matchOne(file.slice(0, f_end), pattern.slice(p_begin, p_end), partial,
// fileIndex, 0)
bool MatchLinear(Parts file,
size_t f_end,
const RowParts& pattern,
size_t p_begin,
size_t p_end,
size_t f_index) {
size_t fi = f_index;
size_t pi = p_begin;
const size_t fl = f_end;
const size_t pl = p_end;
for (; fi < fl && pi < pl; fi++, pi++) {
const PartMatcher& p = pattern[pi];
if (p.kind == PartMatcher::Kind::kGlobstar) return false;
if (fi >= file.size()) return false; // sliced view can't exceed store
if (!TestPartImpl(p, file[fi])) return false;
}
if (fi == fl && pi == pl) return true;
if (fi == fl) return false;
if (pi == pl) return fi == fl - 1 && fi < file.size() && file[fi].empty();
return false;
}
enum class Tri { kFalse, kNull, kTrue };
struct Section {
size_t begin, end; // pattern part indices
ptrdiff_t after; // last possible file index this section can start at
};
Tri MatchGlobstar(Parts file,
const RowParts& pattern,
size_t file_index,
size_t pattern_index) {
// locate first (from pattern_index) and last globstar
size_t firstgs = pattern_index;
while (firstgs < pattern.size() &&
pattern[firstgs].kind != PartMatcher::Kind::kGlobstar) {
firstgs++;
}
size_t lastgs = pattern.size();
for (size_t i = pattern.size(); i-- > 0;) {
if (pattern[i].kind == PartMatcher::Kind::kGlobstar) {
lastgs = i;
break;
}
}
// head, body, tail
const size_t head_begin = pattern_index;
const size_t head_end = firstgs;
const size_t body_begin = firstgs + 1;
// slice(firstgs + 1, lastgs) is empty when they are the same globstar
const size_t body_end = std::max(lastgs, body_begin);
const size_t tail_begin = lastgs + 1;
const size_t tail_end = pattern.size();
const size_t head_len = head_end - head_begin;
size_t fi = file_index;
if (head_len > 0) {
// #matchOne(file.slice(fileIndex, fileIndex + head.length), head, ...)
const size_t slice_end = std::min(file.size(), fi + head_len);
if (!MatchLinear(file, slice_end, pattern, head_begin, head_end, fi)) {
return Tri::kFalse;
}
fi += head_len;
}
const size_t tail_len = tail_end - tail_begin;
size_t file_tail_match = 0;
if (tail_len > 0) {
if (tail_len + fi > file.size()) return Tri::kFalse;
size_t tail_start = file.size() - tail_len;
if (MatchLinear(
file, file.size(), pattern, tail_begin, tail_end, tail_start)) {
file_tail_match = tail_len;
} else {
// affordance: a/**/* matching a/b/
if (file.empty() || !file.back().empty() ||
fi + tail_len == file.size()) {
return Tri::kFalse;
}
tail_start--;
if (!MatchLinear(
file, file.size(), pattern, tail_begin, tail_end, tail_start)) {
return Tri::kFalse;
}
file_tail_match = tail_len + 1;
}
}
const size_t body_len = body_end - body_begin;
if (body_len == 0) {
bool saw_some = file_tail_match != 0;
const size_t scan_end =
file.size() >= file_tail_match ? file.size() - file_tail_match : 0;
for (size_t i = fi; i < scan_end; i++) {
const View f = file[i];
saw_some = true;
if (IsDots(f) || (!pat_->flags.dot && f.starts_with('.'))) {
return Tri::kFalse;
}
}
return saw_some ? Tri::kTrue : Tri::kFalse;
}
// split body into globstar-delimited sections with their last possible
// start positions
std::vector<Section> sections;
sections.push_back({body_begin, body_begin, 0});
std::vector<size_t> non_gs_sums{0};
size_t non_gs = 0;
for (size_t i = body_begin; i < body_end; i++) {
if (pattern[i].kind == PartMatcher::Kind::kGlobstar) {
non_gs_sums.push_back(non_gs);
sections.push_back({i + 1, i + 1, 0});
} else {
sections.back().end = i + 1;
non_gs++;
}
}
const ptrdiff_t file_length = static_cast<ptrdiff_t>(file.size()) -
static_cast<ptrdiff_t>(file_tail_match);
{
size_t i = sections.size() - 1;
for (Section& s : sections) {
s.after = file_length - (static_cast<ptrdiff_t>(non_gs_sums[i--]) +
static_cast<ptrdiff_t>(s.end - s.begin));
}
}
return MatchBodySections(
file, pattern, sections, fi, 0, 0, file_tail_match != 0);
}
// #matchGlobStarBodySections
Tri MatchBodySections(Parts file,
const RowParts& pattern,
const std::vector<Section>& sections,
size_t file_index,
size_t body_index,
int globstar_depth,
bool saw_tail) {
if (body_index >= sections.size()) {
// just make sure that there's no bad dots
for (size_t i = file_index; i < file.size(); i++) {
saw_tail = true;
const View f = file[i];
if (IsDots(f) || (!pat_->flags.dot && f.starts_with('.'))) {
return Tri::kFalse;
}
}
return saw_tail ? Tri::kTrue : Tri::kFalse;
}
const Section& bs = sections[body_index];
const size_t body_len = bs.end - bs.begin;
size_t fi = file_index;
while (static_cast<ptrdiff_t>(fi) <= bs.after) {
const size_t slice_end = std::min(file.size(), fi + body_len);
const bool m =
MatchLinear(file, slice_end, pattern, bs.begin, bs.end, fi);
// if the cap is exceeded: intentional false negative, for security
if (m && globstar_depth < kMaxGlobstarRecursion) {
const Tri sub = MatchBodySections(file,
pattern,
sections,
fi + body_len,
body_index + 1,
globstar_depth + 1,
saw_tail);
if (sub != Tri::kFalse) return sub;
}
if (fi >= file.size()) return Tri::kFalse;
const View f = file[fi];
if (IsDots(f) || (!pat_->flags.dot && f.starts_with('.'))) {
return Tri::kFalse;
}
fi++;
}
return Tri::kNull;
}
const CompiledPattern* pat_;
std::basic_string<Char> rewritten_;
MaybeStackBuffer<View, kInlineParts> parts_;
std::vector<std::basic_string<Char>> owned_;
std::vector<View> owned_views_;
};
} // namespace
bool MatchPattern(const CompiledPattern& pattern, PatternView path) {
PathMatcher<char16_t> m(pattern);
return m.Match(path);
}
bool MatchPattern(const CompiledPattern& pattern, OneByteView path) {
PathMatcher<char8_t> m(pattern);
return m.Match(path);
}
} // namespace node::glob
+20
View File
@@ -0,0 +1,20 @@
#ifndef SRC_GLOB_GLOB_MATCHER_H_
#define SRC_GLOB_GLOB_MATCHER_H_
#include <string_view>
#include "glob/glob_program.h"
namespace node::glob {
using OneByteView = std::basic_string_view<char8_t>;
bool TestPart(const PartMatcher& part, PatternView f);
bool TestPart(const PartMatcher& part, OneByteView f);
bool MatchPattern(const CompiledPattern& pattern, PatternView path);
bool MatchPattern(const CompiledPattern& pattern, OneByteView path);
} // namespace node::glob
#endif // SRC_GLOB_GLOB_MATCHER_H_
File diff suppressed because it is too large. Load diff
+70
View File
@@ -0,0 +1,70 @@
#ifndef SRC_GLOB_GLOB_PARSER_H_
#define SRC_GLOB_GLOB_PARSER_H_
#include <string>
#include <string_view>
#include <vector>
#include "glob/glob_ast.h"
namespace node::glob {
// Sets *error and returns {} for a pattern that cannot be expanded.
std::vector<PatternString> BraceExpand(PatternView pattern,
CompileError* error);
// Minimatch#slashSplit
template <typename Char, typename Emit>
void SlashSplitInto(std::basic_string_view<Char> s, bool windows, Emit emit) {
if (windows && s.size() >= 3 && s[0] == '/' && s[1] == '/' && s[2] != '/') {
emit(std::basic_string_view<Char>());
}
size_t i = 0;
size_t start = 0;
while (i < s.size()) {
if (s[i] != '/') {
i++;
continue;
}
emit(s.substr(start, i - start));
while (i < s.size() && s[i] == '/') i++;
start = i;
}
emit(s.substr(start));
}
std::vector<PatternString> SlashSplit(PatternView s, const CompileFlags& flags);
// Minimatch#preprocess at optimizationLevel 2
void PreprocessLevel2(std::vector<std::vector<PatternString>>* glob_parts,
const CompileFlags& flags);
// Minimatch#levelTwoFileOptimize
template <typename Char>
void LevelTwoFileOptimize(std::vector<std::basic_string<Char>>* parts,
const CompileFlags& flags);
extern template void LevelTwoFileOptimize<char16_t>(
std::vector<std::basic_string<char16_t>>*, const CompileFlags&);
extern template void LevelTwoFileOptimize<char8_t>(
std::vector<std::basic_string<char8_t>>*, const CompileFlags&);
// AST.#parseAST + #flatten + #fillNegs
SegmentTree ParseSegmentAst(PatternView part, CompileError* error);
bool HasGlobMagic(PatternView s);
struct ParseResult {
ParsedPattern pattern;
CompileError error = CompileError::kNone;
};
ParseResult ParsePattern(PatternView raw, const CompileFlags& flags);
// Overwrites `out`, reusing its capacity across calls.
void Utf8ToUtf16(std::string_view utf8, PatternString* out);
std::string Utf16ToUtf8(PatternView utf16);
} // namespace node::glob
#endif // SRC_GLOB_GLOB_PARSER_H_
+930
View File
@@ -0,0 +1,930 @@
#include "glob/glob_program.h"
#include <algorithm>
#include <span>
#include "glob/glob_unicode.h"
namespace node::glob {
namespace {
// The [^+@!?*[(] character class these shapes end in.
constexpr PatternView kExtChars = u"+@!?*[(";
// Serialize() writes node kinds into a UTF-16 string alongside the '(',
// ')' and '|' it uses for structure. Offsetting the kinds into the Private
// Use Area keeps the two apart, and class bounds are split into halves
// because a code point does not fit in one unit.
//
// (The "Private Use Area" is explained in glob_parser.cc's BraceSentinels)
constexpr char16_t kSerializedKindBase = 0xE000;
constexpr int kCodeUnitBits = 16;
constexpr uint32_t kCodeUnitMask = 0xFFFF;
// Index of the first unit that is not `c`, or the end.
size_t SkipRun(PatternView s, char16_t c, size_t from = 0) {
const size_t end = s.find_first_not_of(c, from);
return end == PatternView::npos ? s.size() : end;
}
// /^\*+$/
bool ProbeStar(PatternView s) {
return !s.empty() && SkipRun(s, u'*') == s.size();
}
// /^\*+([^+@!?*[(]*)$/
bool ProbeStarDotExt(PatternView s, PatternString* ext) {
const size_t i = SkipRun(s, u'*');
if (i == 0 || s.find_first_of(kExtChars, i) != PatternView::npos) {
return false;
}
ext->assign(s.substr(i));
return true;
}
// /^\?+([^+@!?*[(]*)?$/
bool ProbeQmarks(PatternView s, PatternString* ext) {
const size_t i = SkipRun(s, u'?');
if (i == 0 || s.find_first_of(kExtChars, i) != PatternView::npos) {
return false;
}
ext->assign(s.substr(i));
return true;
}
// /^\*+\.\*+$/
bool ProbeStarDotStar(PatternView s) {
const size_t dot = SkipRun(s, u'*');
if (dot == 0 || dot >= s.size() || s[dot] != u'.') return false;
return dot + 1 < s.size() && SkipRun(s, u'*', dot + 1) == s.size();
}
// /^\.\*+$/
bool ProbeDotStar(PatternView s) {
return s.size() >= 2 && s[0] == u'.' && SkipRun(s, u'*', 1) == s.size();
}
// --- regexpEscape simulation (only the *first characters* of the regex
// source matter, for guard selection) -----------------------------------------
// /[-[\]{}()*+?.,\\^$|#\s]/, where \s is the whole JavaScript whitespace
// set.
bool NeedsRegExpEscape(char16_t c) {
switch (c) {
case u'-':
case u'[':
case u']':
case u'{':
case u'}':
case u'(':
case u')':
case u'*':
case u'+':
case u'?':
case u'.':
case u',':
case u'\\':
case u'^':
case u'$':
case u'|':
case u'#':
case u' ':
case u'\t':
case u'\n':
case u'\v':
case u'\f':
case u'\r':
return true;
default:
return c == 0x00A0 || c == 0x1680 || (c >= 0x2000 && c <= 0x200A) ||
c == 0x202F || c == 0x205F || c == 0x3000 || c == 0xFEFF ||
IsLineTerminator(c);
}
}
// Characters regexpEscape would escape that are legal identity escapes
// under the 'u' flag (SyntaxCharacter or '/'); everything else escaped in a
// u-mode regular expression makes `new RegExp` throw.
bool IsULegalIdentityEscape(char16_t c) {
switch (c) {
case u'^':
case u'$':
case u'\\':
case u'.':
case u'*':
case u'+':
case u'?':
case u'(':
case u')':
case u'[':
case u']':
case u'{':
case u'}':
case u'|':
case u'/':
return true;
default:
return false;
}
}
struct ClassParse {
bool consumed_any = false; // consumed > 0
size_t consumed = 0;
bool magic = false;
bool uflag = false;
bool demoted = false; // single-char class became a literal
char16_t demoted_char = 0;
bool poison = false; // '$.', an atom that can never match
bool unsupported_property = false;
RxNode::CharClass klass;
// First character of the regex source this class produced ('[', '(', or
// the demoted literal's escaped/plain first char).
char16_t src_first = u'[';
bool src_first_escaped = false;
};
struct PosixClassDef {
PatternView name;
// The Unicode properties the class translates to.
std::span<const UnicodeProperty> properties;
// Literal members some classes carry alongside their properties.
std::span<const CharSet::Range> extra;
// The class needs the `u` flag (property escapes require it).
bool uflag;
// '[:graph:]' is emitted negated: [^\p{Z}\p{C}].
bool negated;
};
using P = UnicodeProperty;
constexpr P kAlnum[] = {P::kLetter, P::kLetterNumber, P::kDecimalNumber};
constexpr P kAlpha[] = {P::kLetter, P::kLetterNumber};
constexpr P kBlank[] = {P::kSpaceSeparator};
constexpr P kCntrl[] = {P::kControl};
constexpr P kDigit[] = {P::kDecimalNumber};
constexpr P kGraph[] = {P::kSeparator, P::kOther};
constexpr P kLower[] = {P::kLowercase};
constexpr P kPrint[] = {P::kOther};
constexpr P kPunct[] = {P::kPunctuation};
constexpr P kSpace[] = {P::kSeparator};
constexpr P kUpper[] = {P::kUppercase};
constexpr P kWord[] = {
P::kLetter, P::kLetterNumber, P::kDecimalNumber, P::kConnector};
constexpr CharSet::Range kAsciiRange[] = {{0x00, 0x7F}};
constexpr CharSet::Range kXdigitRanges[] = {
{u'A', u'F'}, {u'a', u'f'}, {u'0', u'9'}};
constexpr CharSet::Range kTab[] = {{u'\t', u'\t'}};
constexpr CharSet::Range kSpaceExtras[] = {{u'\t', u'\t'},
{u'\r', u'\r'},
{u'\n', u'\n'},
{u'\v', u'\v'},
{u'\f', u'\f'}};
const PosixClassDef kPosixClasses[] = {
{u"[:alnum:]", kAlnum, {}, true, false},
{u"[:alpha:]", kAlpha, {}, true, false},
{u"[:ascii:]", {}, kAsciiRange, false, false},
{u"[:blank:]", kBlank, kTab, true, false},
{u"[:cntrl:]", kCntrl, {}, true, false},
{u"[:digit:]", kDigit, {}, true, false},
{u"[:graph:]", kGraph, {}, true, true},
{u"[:lower:]", kLower, {}, true, false},
{u"[:print:]", kPrint, {}, true, false},
{u"[:punct:]", kPunct, {}, true, false},
{u"[:space:]", kSpace, kSpaceExtras, true, false},
{u"[:upper:]", kUpper, {}, true, false},
{u"[:word:]", kWord, {}, true, false},
{u"[:xdigit:]", {}, kXdigitRanges, false, false},
};
ClassParse ParseClass(PatternView glob, size_t position) {
ClassParse out;
const size_t pos = position;
size_t i = pos + 1;
bool saw_start = false;
bool escaping = false;
bool negate = false;
size_t end_pos = pos;
bool have_range_start = false;
char16_t range_start = 0;
struct Added { // one entry per push into `ranges`
bool single_char;
char16_t ch;
};
std::vector<Added> added;
CharSet positive;
CharSet negative;
bool has_positive = false;
bool has_negative = false;
bool uflag = false;
bool unsupported_property = false;
while (i < glob.size()) {
const char16_t c = glob[i];
if ((c == u'!' || c == u'^') && i == pos + 1) {
negate = true;
i++;
continue;
}
if (c == u']' && saw_start && !escaping) {
end_pos = i + 1;
break;
}
saw_start = true;
if (c == u'\\') {
if (!escaping) {
escaping = true;
i++;
continue;
}
}
if (c == u'[' && !escaping) {
bool matched_posix = false;
for (const PosixClassDef& def : kPosixClasses) {
if (glob.substr(i).starts_with(def.name)) {
if (have_range_start) {
// [a-[:alpha:]] poisons the whole remaining glob text.
out.consumed_any = true;
out.consumed = glob.size() - pos;
out.magic = true;
out.poison = true;
return out;
}
i += def.name.size();
CharSet& side = def.negated ? negative : positive;
(def.negated ? has_negative : has_positive) = true;
for (UnicodeProperty property : def.properties) {
if (!side.AddProperty(property)) unsupported_property = true;
}
for (const CharSet::Range& range : def.extra) {
side.AddRange(range.lo, range.hi);
}
added.push_back({false, 0});
uflag = uflag || def.uflag;
matched_posix = true;
break;
}
}
if (matched_posix) continue;
}
escaping = false;
if (have_range_start) {
if (c > range_start) {
positive.AddRange(range_start, c);
has_positive = true;
added.push_back({false, 0});
} else if (c == range_start) {
positive.AddChar(c);
has_positive = true;
added.push_back({true, c});
}
// (c < range_start: range dropped entirely)
have_range_start = false;
i++;
continue;
}
// possible range start: c-] / c-x / c
if (i + 2 < glob.size() && glob[i + 1] == u'-' && glob[i + 2] == u']') {
// 'c-' as two literal members
positive.AddChar(c);
positive.AddChar(u'-');
has_positive = true;
added.push_back({false, 0}); // "c-" is a 2-char source piece
i += 2;
continue;
}
if (i + 1 < glob.size() && glob[i + 1] == u'-') {
range_start = c;
have_range_start = true;
i += 2;
continue;
}
positive.AddChar(c);
has_positive = true;
added.push_back({true, c});
i++;
}
if (end_pos < i || end_pos == pos) {
// didn't find the closing ']': not a class, '[' stays literal
return out;
}
out.consumed_any = true;
out.consumed = end_pos - pos;
if (!has_positive && !has_negative) {
// "[]" (or all-dropped): poison
out.consumed = glob.size() - pos;
out.magic = true;
out.poison = true;
return out;
}
// single positive plain char, not negated
if (!has_negative && !negate && added.size() == 1 && added[0].single_char) {
out.demoted = true;
out.demoted_char = added[0].ch;
out.magic = false;
const char16_t ch = added[0].ch;
out.src_first_escaped = NeedsRegExpEscape(ch);
out.src_first = out.src_first_escaped ? u'\\' : ch;
return out;
}
out.magic = true;
out.uflag = uflag;
out.unsupported_property = unsupported_property;
positive.Seal();
negative.Seal();
out.klass.positive = std::move(positive);
out.klass.negative = std::move(negative);
out.klass.has_positive = has_positive;
out.klass.has_negative = has_negative;
out.klass.negate = negate;
// comb source starts with '(' when both sides exist, else '['
out.src_first = (has_positive && has_negative) ? u'(' : u'[';
return out;
}
struct Lowered {
uint32_t node = 0;
bool source_empty = true; // produced no regex source at all
// First simulated source characters (up to 5), for guard decisions.
PatternString src_prefix;
bool bad_uescape = false;
bool bad_syntax = false;
};
class SegmentLowering {
public:
SegmentLowering(const CompileFlags& flags, SegmentProgram* out)
: flags_(flags), out_(out) {}
uint32_t Add(RxNode&& n) {
out_->nodes.push_back(std::move(n));
return static_cast<uint32_t>(out_->nodes.size() - 1);
}
void AppendPrefix(PatternString* prefix, char16_t c) {
if (prefix->size() < 5) prefix->push_back(c);
}
void AppendPrefix(PatternString* prefix, PatternView s) {
for (char16_t c : s) {
if (prefix->size() >= 5) break;
prefix->push_back(c);
}
}
// #parseGlob: one literal text run
Lowered LowerText(PatternView text, bool no_empty) {
Lowered result;
std::vector<uint32_t> seq;
bool in_star = false;
PatternString pending_text;
auto flush_text = [&]() {
if (pending_text.empty()) return;
RxNode n;
n.kind = RxNode::Kind::kText;
n.text = std::move(pending_text);
pending_text.clear();
seq.push_back(Add(std::move(n)));
};
bool escaping = false;
const bool all_stars = ProbeStar(text);
auto note_escaped_literal = [&result](char16_t c) {
if (NeedsRegExpEscape(c) && !IsULegalIdentityEscape(c)) {
result.bad_uescape = true;
}
};
for (size_t i = 0; i < text.size(); i++) {
const char16_t c = text[i];
if (escaping) {
escaping = false;
AppendPrefix(
&result.src_prefix,
NeedsRegExpEscape(c) ? PatternString{u'\\', c} : PatternString{c});
note_escaped_literal(c);
pending_text.push_back(c);
literal_value_ += c;
continue;
}
if (c == u'*') {
if (in_star) continue;
in_star = true;
flush_text();
RxNode n;
n.kind = RxNode::Kind::kStarAny;
n.star_no_empty = no_empty && all_stars;
seq.push_back(Add(std::move(n)));
AppendPrefix(&result.src_prefix, u'['); // '[^/]*?' / '[^/]+?'
magic_ = true;
continue;
}
in_star = false;
if (c == u'\\') {
if (i == text.size() - 1) {
pending_text.push_back(u'\\');
literal_value_ += u'\\';
AppendPrefix(&result.src_prefix, PatternView(u"\\\\"));
} else {
escaping = true;
}
continue;
}
if (c == u'[') {
ClassParse cp = ParseClass(text, i);
if (cp.consumed_any) {
i += cp.consumed - 1;
if (cp.demoted) {
pending_text.push_back(cp.demoted_char);
literal_value_ += cp.demoted_char;
note_escaped_literal(cp.demoted_char);
if (cp.src_first_escaped) {
AppendPrefix(&result.src_prefix, u'\\');
AppendPrefix(&result.src_prefix, cp.demoted_char);
} else {
AppendPrefix(&result.src_prefix, cp.demoted_char);
}
} else if (cp.unsupported_property) {
bad_property_ = true;
flush_text();
RxNode n;
n.kind = RxNode::Kind::kClass;
seq.push_back(Add(std::move(n)));
AppendPrefix(&result.src_prefix, u'[');
magic_ = true;
} else if (cp.poison) {
flush_text();
RxNode n;
n.kind = RxNode::Kind::kClass; // empty class: never matches
seq.push_back(Add(std::move(n)));
AppendPrefix(&result.src_prefix, u'$');
magic_ = true;
} else {
flush_text();
uflag_ = uflag_ || cp.uflag;
RxNode n;
n.kind = RxNode::Kind::kClass;
n.klass = std::move(cp.klass);
seq.push_back(Add(std::move(n)));
AppendPrefix(&result.src_prefix, cp.src_first);
magic_ = true;
}
continue;
}
// not consumed: fall through as a literal '['
}
if (c == u'?') {
flush_text();
RxNode n;
n.kind = RxNode::Kind::kAnyChar;
seq.push_back(Add(std::move(n)));
AppendPrefix(&result.src_prefix, u'['); // '[^/]'
magic_ = true;
continue;
}
AppendPrefix(
&result.src_prefix,
NeedsRegExpEscape(c) ? PatternString{u'\\', c} : PatternString{c});
note_escaped_literal(c);
pending_text.push_back(c);
literal_value_ += c;
}
flush_text();
if (seq.empty()) {
RxNode n;
n.kind = RxNode::Kind::kEmpty;
result.node = Add(std::move(n));
} else if (seq.size() == 1) {
result.node = seq[0];
} else {
RxNode n;
n.kind = RxNode::Kind::kConcat;
n.children = std::move(seq);
result.node = Add(std::move(n));
}
// A nonempty text run always produces regex source.
result.source_empty = text.empty();
return result;
}
// toRegExpSource(allowDot)
Lowered LowerNode(SegmentNode* node, bool allow_dot) {
const bool dot = allow_dot || flags_.dot;
if (!node->is_extglob()) {
return LowerPlain(node, allow_dot, dot);
}
return LowerExtglob(node, allow_dot, dot);
}
bool magic() const { return magic_; }
bool uflag() const { return uflag_; }
bool bad_property() const { return bad_property_; }
const PatternString& literal_value() const { return literal_value_; }
private:
Lowered LowerPlain(SegmentNode* node, bool allow_dot, bool dot) {
const bool no_empty =
node->IsStart() && node->IsEnd() &&
std::ranges::all_of(*node->parts, [](const SegmentNode::Part& p) {
return !p.is_child();
});
Lowered result;
std::vector<uint32_t> seq;
bool first = true;
for (const SegmentNode::Part& p : *node->parts) {
Lowered lp = p.is_child() ? LowerNode(p.child, allow_dot)
: LowerText(p.text, no_empty);
if (first || result.src_prefix.size() < 5) {
AppendPrefix(&result.src_prefix, lp.src_prefix);
}
first = false;
if (!lp.source_empty) result.source_empty = false;
result.bad_uescape = result.bad_uescape || lp.bad_uescape;
result.bad_syntax = result.bad_syntax || lp.bad_syntax;
seq.push_back(lp.node);
}
// A segment beginning with '.' is matched only by a
// pattern segment beginning with a literal '.', and '.' and '..' are
// never matched by a wildcard.
bool start_no_dot = false;
bool start_no_traversal = false;
if (node->IsStart() && !node->parts->empty() &&
!(*node->parts)[0].is_child()) {
const bool dot_trav_allowed =
node->parts->size() == 1 && !(*node->parts)[0].is_child() &&
((*node->parts)[0].text == u"." || (*node->parts)[0].text == u"..");
if (!dot_trav_allowed) {
const PatternString& src = result.src_prefix;
auto at = [&src](size_t i) -> char16_t {
return i < src.size() ? src[i] : 0;
};
const bool starts_escaped_dot = at(0) == u'\\' && at(1) == u'.';
const bool starts_two_escaped_dots =
starts_escaped_dot && at(2) == u'\\' && at(3) == u'.';
auto is_aps = [](char16_t c) { return c == u'[' || c == u'.'; };
const bool need_no_trav = (dot && is_aps(at(0))) ||
(starts_escaped_dot && is_aps(at(2))) ||
(starts_two_escaped_dots && is_aps(at(4)));
const bool need_no_dot = !dot && !allow_dot && is_aps(at(0));
start_no_dot = !need_no_trav && need_no_dot;
start_no_traversal = need_no_trav;
}
}
if (node->parent == nullptr) {
out_->start_no_dot = start_no_dot;
out_->start_no_traversal = start_no_traversal;
if (seq.empty()) {
RxNode n;
n.kind = RxNode::Kind::kEmpty;
result.node = Add(std::move(n));
result.source_empty = true;
return result;
}
} else if (start_no_dot || start_no_traversal) {
RxNode g;
g.kind = RxNode::Kind::kAssert;
g.assert_no_dot = start_no_dot;
g.assert_no_traversal = start_no_traversal;
seq.insert(seq.begin(), Add(std::move(g)));
}
if (seq.empty()) {
RxNode n;
n.kind = RxNode::Kind::kEmpty;
result.node = Add(std::move(n));
result.source_empty = true;
} else if (seq.size() == 1) {
result.node = seq[0];
} else {
RxNode n;
n.kind = RxNode::Kind::kConcat;
n.children = std::move(seq);
result.node = Add(std::move(n));
}
return result;
}
// #partsToRegExp
std::vector<Lowered> LowerAlternatives(SegmentNode* node, bool allow_dot) {
std::vector<Lowered> alts;
const bool drop_empty = node->IsStart() && node->IsEnd();
for (const SegmentNode::Part& p : *node->parts) {
if (!p.is_child()) continue; // extglob parts are always sub-ASTs
Lowered l = LowerNode(p.child, allow_dot);
if (drop_empty && l.source_empty) continue;
alts.push_back(std::move(l));
}
return alts;
}
// Serializes a subtree for minimatch's `bodyDotAllowed === body`
// comparison
void Serialize(uint32_t id, PatternString* out) const {
const RxNode& n = out_->nodes[id];
out->push_back(
static_cast<char16_t>(kSerializedKindBase + static_cast<int>(n.kind)));
out->push_back(static_cast<char16_t>(
u'0' + (n.star_no_empty ? 1 : 0) + (n.star_no_dot ? 2 : 0) +
(n.assert_no_dot ? 4 : 0) + (n.assert_no_traversal ? 8 : 0)));
if (n.kind == RxNode::Kind::kText) {
out->append(n.text);
} else if (n.kind == RxNode::Kind::kClass) {
for (const CharSet* set : {&n.klass.positive, &n.klass.negative}) {
for (const CharSet::Range& r : set->ranges()) {
out->push_back(static_cast<char16_t>(r.lo & kCodeUnitMask));
out->push_back(static_cast<char16_t>(r.lo >> kCodeUnitBits));
out->push_back(static_cast<char16_t>(r.hi & kCodeUnitMask));
out->push_back(static_cast<char16_t>(r.hi >> kCodeUnitBits));
}
out->push_back(u'|');
}
out->push_back(static_cast<char16_t>(u'0' + (n.klass.negate ? 1 : 0) +
(n.klass.has_positive ? 2 : 0) +
(n.klass.has_negative ? 4 : 0)));
}
out->push_back(u'(');
for (uint32_t c : n.children) Serialize(c, out);
out->push_back(u')');
}
Lowered LowerExtglob(SegmentNode* node, bool allow_dot, bool dot) {
Lowered result;
const bool repeated = node->type == '*' || node->type == '+';
std::vector<Lowered> alts = LowerAlternatives(node, allow_dot);
// minimatch's `body === ''` reversion
if (node->IsStart() && node->IsEnd() && alts.empty() && node->type != '!') {
// Invalid empty extglob
const PatternString raw = node->ToString();
const char type = node->type;
node->type = 0;
// A fresh array: clearing through the pointer could clear a parts
// array another node aliases.
node->parts = std::make_shared<SegmentNode::Parts>();
node->parts->emplace_back(PatternString(raw));
node->empty_ext = false;
literal_value_ += raw;
RxNode n;
n.kind = RxNode::Kind::kText;
// As raw regex source, `@(||)` is a literal '@' followed by a group
// matching the empty string
if (type == '@') {
n.text = PatternString(1, u'@');
} else {
n.text = raw;
result.bad_syntax = true;
}
result.node = Add(std::move(n));
result.source_empty = raw.empty();
AppendPrefix(&result.src_prefix, PatternView(raw));
return result;
}
magic_ = true; // extglobs are inherently magical
AppendPrefix(&result.src_prefix, u'(');
result.source_empty = false;
if (node->type == '!' && node->empty_ext) {
// The emptyExt flag is set by the parser whenever the last
// alternative ended empty at the ')' (including `!(a|)` and
// `!(a|b())` shapes)
RxNode n;
n.kind = RxNode::Kind::kStarAny;
n.star_no_empty = true;
n.star_no_dot = node->IsStart() && !dot;
result.node = Add(std::move(n));
return result;
}
auto make_alt = [&](std::vector<Lowered>& list) -> uint32_t {
if (list.size() == 1) return list[0].node;
RxNode n;
if (list.empty()) {
n.kind = RxNode::Kind::kEmpty;
} else {
n.kind = RxNode::Kind::kAlt;
for (Lowered& l : list) n.children.push_back(l.node);
}
return Add(std::move(n));
};
auto merge_flags = [&result](const std::vector<Lowered>& list) {
for (const Lowered& l : list) {
result.bad_uescape = result.bad_uescape || l.bad_uescape;
result.bad_syntax = result.bad_syntax || l.bad_syntax;
}
};
if (node->type == '!') {
// A negated extglob is a guard plus a `[^/]*?` consume, which is what
// a regular expression can express. That makes it less permissive than
// bash when something greedy follows: `!(a)*` does not match 'ab',
// because the guard cannot take 'ab' and leave the `*` empty.
//
// That being said, in a future major update, we can potentially
// change this behavior for less RegExp-compat and more Bash-compat.
merge_flags(alts);
RxNode n;
n.kind = RxNode::Kind::kNeg;
for (Lowered& l : alts) n.children.push_back(l.node);
n.star_no_dot = node->IsStart() && !dot && !allow_dot;
result.node = Add(std::move(n));
return result;
}
merge_flags(alts);
// bodyDotAllowed: only for repeated extglobs when dots are not already
// allowed.
bool has_body_dot = false;
uint32_t body_dot_alt = 0;
uint32_t body_alt = make_alt(alts);
if (repeated && !allow_dot && !flags_.dot) {
std::vector<Lowered> alts_dot = LowerAlternatives(node, true);
uint32_t alt_dot = make_alt(alts_dot);
PatternString a, b;
Serialize(body_alt, &a);
Serialize(alt_dot, &b);
if (a != b) {
has_body_dot = true;
body_dot_alt = alt_dot;
merge_flags(alts_dot);
}
}
RxNode n;
switch (node->type) {
case '@':
result.node = body_alt;
return result;
case '?':
n.kind = RxNode::Kind::kOpt;
n.children = {body_alt};
result.node = Add(std::move(n));
return result;
case '+':
if (has_body_dot) {
n.kind = RxNode::Kind::kTwoBody;
n.children = {body_alt, body_dot_alt};
} else {
n.kind = RxNode::Kind::kPlus;
n.children = {body_alt};
}
result.node = Add(std::move(n));
return result;
case '*':
default:
if (has_body_dot) {
RxNode two;
two.kind = RxNode::Kind::kTwoBody;
two.children = {body_alt, body_dot_alt};
const uint32_t two_id = Add(std::move(two));
n.kind = RxNode::Kind::kOpt;
n.children = {two_id};
} else {
n.kind = RxNode::Kind::kStar;
n.children = {body_alt};
}
result.node = Add(std::move(n));
return result;
}
}
const CompileFlags& flags_;
SegmentProgram* out_;
bool magic_ = false;
bool uflag_ = false;
bool bad_property_ = false;
PatternString literal_value_;
};
} // namespace
SegmentProgram LowerSegment(SegmentNode* root,
const CompileFlags& flags,
PatternView source) {
SegmentProgram program;
program.dot = flags.dot;
if (source.empty()) {
program.tier = SegmentProgram::Tier::kEmpty;
return program;
}
// Shape probes. minimatch installs these in place of the regular
// expression, so they define the segment's semantics.
PatternString ext;
if (ProbeStar(source)) {
program.tier = SegmentProgram::Tier::kStar;
return program;
}
if (ProbeStarDotExt(source, &ext)) {
program.tier = SegmentProgram::Tier::kStarDotExt;
program.nocase = flags.nocase;
program.literal = std::move(ext);
if (flags.nocase) AppendLowered(program.literal, &program.literal_lower);
return program;
}
if (ProbeQmarks(source, &ext)) {
program.tier = SegmentProgram::Tier::kQmarks;
program.nocase = flags.nocase;
program.qmarks_len = source.size();
program.literal = std::move(ext);
if (flags.nocase) AppendLowered(program.literal, &program.literal_lower);
return program;
}
if (ProbeStarDotStar(source)) {
program.tier = SegmentProgram::Tier::kStarDotStar;
return program;
}
if (ProbeDotStar(source)) {
program.tier = SegmentProgram::Tier::kDotStar;
return program;
}
SegmentLowering lowering(flags, &program);
Lowered l = lowering.LowerNode(root, false);
program.root = l.node;
program.uflag = lowering.uflag();
if (!lowering.magic()) {
program.tier = SegmentProgram::Tier::kLiteral;
program.literal = lowering.literal_value();
// minimatch keeps a non-magic segment a plain string unless nocase applies
// to literals too, in which case it becomes /^text$/i (never 'u': only
// classes set the flag, and those are magic).
program.nocase = flags.nocase && !flags.nocase_magic_only;
program.nodes.clear();
program.start_no_dot = false;
program.start_no_traversal = false;
return program;
}
program.tier = SegmentProgram::Tier::kRegex;
program.nocase = flags.nocase;
if (flags.nocase) {
for (RxNode& node : program.nodes) {
if (node.kind != RxNode::Kind::kClass) continue;
for (CharSet* set : {&node.klass.positive, &node.klass.negative}) {
if (program.uflag) {
set->CloseOverCaseFold();
} else {
set->CanonicalizeMembers();
}
}
}
}
// `new RegExp` would throw on this source (e.g. an illegal identity escape
// under the 'u' flag such as `\-` outside a class, etc)
program.invalid_regex = (program.uflag && l.bad_uescape) || l.bad_syntax ||
lowering.bad_property();
return program;
}
CompiledPattern CompileProgram(ParsedPattern&& parsed,
const CompileFlags& flags) {
CompiledPattern out;
out.flags = flags;
out.empty = parsed.empty;
for (ParsedPattern::Row& row : parsed.rows) {
CompiledPattern::Row crow;
for (PathPart& part : row.parts) {
PartMatcher m;
m.source = part.source;
if (part.kind == PathPart::Kind::kGlobstar) {
m.kind = PartMatcher::Kind::kGlobstar;
crow.has_globstar = true;
} else if (part.segment.root == nullptr) {
m.kind = PartMatcher::Kind::kLiteral;
m.literal = part.source;
} else {
m.kind = PartMatcher::Kind::kProgram;
m.program = LowerSegment(part.segment.root, flags, part.source);
if (m.program.invalid_regex) {
out.error = CompileError::kInvalidRegExp;
return out;
}
if (m.program.tier == SegmentProgram::Tier::kLiteral &&
!m.program.nocase) {
// Fold to a plain literal part ('===' comparison); a case-folded
// literal stays a program so that TestPart() folds it.
m.kind = PartMatcher::Kind::kLiteral;
m.literal = std::move(m.program.literal);
} else if (m.program.tier == SegmentProgram::Tier::kEmpty) {
// minimatch's parse('') returns the string '', and the Windows
// drive and UNC detection in matchOne depends on the part being
// a string.
m.kind = PartMatcher::Kind::kLiteral;
m.literal.clear();
}
}
crow.parts.push_back(std::move(m));
}
out.rows.push_back(std::move(crow));
}
return out;
}
} // namespace node::glob
+115
View File
@@ -0,0 +1,115 @@
#ifndef SRC_GLOB_GLOB_PROGRAM_H_
#define SRC_GLOB_GLOB_PROGRAM_H_
#include <cstdint>
#include <memory>
#include <string>
#include <vector>
#include "glob/glob_ast.h"
#include "glob/glob_unicode.h"
namespace node::glob {
struct RxNode {
enum class Kind : uint8_t {
kEmpty, // matches ''
kAssert, // zero-width start guard (see assert_* flags)
kText, // literal unit run
kAnyChar, // [^/]
kStarAny, // [^/]*? (flags below select +? and dot guards)
kClass,
kConcat,
kAlt,
kOpt, // (?:body)?
kStar, // (?:body)*
kPlus, // (?:body)+
kTwoBody, // (?:first)(?:rest)*? children = [first, rest]
kNeg, // !(..) group: guard alts + [^/]*? consume
};
Kind kind = Kind::kEmpty;
bool star_no_empty = false; // at least one unit
bool star_no_dot = false; // (?!\.) at entry
bool assert_no_dot = false; // `(?!\.)`
bool assert_no_traversal = false; // `(?!(?:^|/)\.\.?(?:$|/))`
struct CharClass {
CharSet positive;
CharSet negative;
bool has_positive = false;
bool has_negative = false;
bool negate = false;
};
CharClass klass;
PatternString text;
std::vector<uint32_t> children;
};
// One compiled path segment.
struct SegmentProgram {
enum class Tier : uint8_t {
kEmpty, // '', which matches only ''
kLiteral, // f === text
kStar, // /^\*+$/
kStarDotExt, // /^\*+([^+@!?*[(]*)$/
kStarDotStar, // /^\*+\.\*+$/
kDotStar, // /^\.\*+$/
kQmarks, // /^\?+([^+@!?*[(]*)?$/
kRegex, // generic
};
Tier tier = Tier::kRegex;
bool uflag = false; // code-point semantics + 'iu' folding
bool nocase = false; // fold case (kLiteral: only if !nocase_magic_only)
bool dot = false;
// If kLiteral: the text. If kStarDotExt/kQmarks: the extension.
PatternString literal;
PatternString literal_lower;
// kQmarks: full pattern length in UTF-16 units ($0.length).
size_t qmarks_len = 0;
// kRegex:
std::vector<RxNode> nodes;
uint32_t root = 0;
bool start_no_dot = false; // (?!\.)
bool start_no_traversal = false; // rejects '.' and '..'
bool invalid_regex = false;
};
// One lowered path part.
struct PartMatcher {
enum class Kind : uint8_t { kGlobstar, kLiteral, kProgram };
Kind kind = Kind::kProgram;
PatternString literal; // kLiteral: '===' comparison (Windows roots etc.)
// Source info
PatternString source;
SegmentProgram program;
};
struct CompiledPattern {
bool empty = false; // empty pattern: matches only ''
CompileFlags flags;
struct Row {
std::vector<PartMatcher> parts;
bool has_globstar = false;
};
std::vector<Row> rows;
// Set when the pattern does not compile
CompileError error = CompileError::kNone;
};
using CompiledPatternPtr = std::shared_ptr<CompiledPattern>;
CompiledPattern CompileProgram(ParsedPattern&& parsed,
const CompileFlags& flags);
// "Lowering", as in toLowerCase-ing
SegmentProgram LowerSegment(SegmentNode* root,
const CompileFlags& flags,
PatternView source);
} // namespace node::glob
#endif // SRC_GLOB_GLOB_PROGRAM_H_
+205
View File
@@ -0,0 +1,205 @@
#include "glob/glob_unicode.h"
#include <algorithm>
#include <tuple>
#ifdef NODE_HAVE_I18N_SUPPORT
#include <unicode/uchar.h>
#include <unicode/uniset.h>
#include <unicode/ustring.h>
#endif // NODE_HAVE_I18N_SUPPORT
namespace node::glob {
namespace {
constexpr uint32_t kMaxCodePoint = 0x10FFFF;
constexpr uint32_t kMaxCodeUnit = 0xFFFF;
#ifdef NODE_HAVE_I18N_SUPPORT
uint32_t PropertyMask(UnicodeProperty property) {
switch (property) {
case UnicodeProperty::kLetter:
return U_GC_L_MASK;
case UnicodeProperty::kLetterNumber:
return U_GC_NL_MASK;
case UnicodeProperty::kDecimalNumber:
return U_GC_ND_MASK;
case UnicodeProperty::kSpaceSeparator:
return U_GC_ZS_MASK;
case UnicodeProperty::kControl:
return U_GC_CC_MASK;
case UnicodeProperty::kSeparator:
return U_GC_Z_MASK;
case UnicodeProperty::kOther:
return U_GC_C_MASK;
case UnicodeProperty::kLowercase:
return U_GC_LL_MASK;
case UnicodeProperty::kUppercase:
return U_GC_LU_MASK;
case UnicodeProperty::kPunctuation:
return U_GC_P_MASK;
case UnicodeProperty::kConnector:
return U_GC_PC_MASK;
}
return 0;
}
#endif // NODE_HAVE_I18N_SUPPORT
} // namespace
void CharSet::AddRange(uint32_t lo, uint32_t hi) {
if (lo > hi) return;
ranges_.push_back({lo, std::min(hi, kMaxCodePoint)});
}
bool CharSet::AddProperty(UnicodeProperty property) {
#ifdef NODE_HAVE_I18N_SUPPORT
const uint32_t mask = PropertyMask(property);
UErrorCode status = U_ZERO_ERROR;
icu::UnicodeSet set;
set.applyIntPropertyValue(
UCHAR_GENERAL_CATEGORY_MASK, static_cast<int32_t>(mask), status);
if (U_FAILURE(status)) return false;
const int32_t count = set.getRangeCount();
for (int32_t i = 0; i < count; i++) {
AddRange(static_cast<uint32_t>(set.getRangeStart(i)),
static_cast<uint32_t>(set.getRangeEnd(i)));
}
return true;
#else
return false;
#endif // NODE_HAVE_I18N_SUPPORT
}
void CharSet::Seal() {
if (ranges_.empty()) return;
std::ranges::sort(
ranges_, {}, [](const Range& r) { return std::tie(r.lo, r.hi); });
std::vector<Range> merged;
merged.push_back(ranges_.front());
for (size_t i = 1; i < ranges_.size(); i++) {
Range& last = merged.back();
const Range& next = ranges_[i];
// Adjacent ranges merge too, so the result is canonical.
if (next.lo <= last.hi || next.lo == last.hi + 1) {
last.hi = std::max(last.hi, next.hi);
} else {
merged.push_back(next);
}
}
ranges_ = std::move(merged);
}
bool CharSet::CloseOverCaseFold() {
Seal();
#ifdef NODE_HAVE_I18N_SUPPORT
icu::UnicodeSet set;
for (const Range& range : ranges_) {
set.add(static_cast<UChar32>(range.lo), static_cast<UChar32>(range.hi));
}
set.closeOver(USET_CASE_INSENSITIVE);
ranges_.clear();
const int32_t count = set.getRangeCount();
for (int32_t i = 0; i < count; i++) {
AddRange(static_cast<uint32_t>(set.getRangeStart(i)),
static_cast<uint32_t>(set.getRangeEnd(i)));
}
Seal();
return true;
#else
const std::vector<Range> original = ranges_;
for (const Range& range : original) {
for (uint32_t cp = range.lo; cp <= std::min(range.hi, uint32_t{'z'});
cp++) {
AddChar(AsciiLower(cp));
AddChar(AsciiUpper(cp));
}
}
Seal();
return false;
#endif // NODE_HAVE_I18N_SUPPORT
}
void CharSet::CanonicalizeMembers() {
Seal();
const std::vector<Range> original = ranges_;
ranges_.clear();
for (const Range& range : original) {
if (range.lo > kMaxCodeUnit) continue;
const uint32_t hi = std::min(range.hi, kMaxCodeUnit);
for (uint32_t cp = range.lo; cp <= hi; cp++) {
AddChar(Canonicalize(cp, /*fold=*/false));
if (cp == kMaxCodeUnit) break;
}
}
Seal();
}
bool CharSet::Contains(uint32_t cp) const {
// Seal() left the ranges sorted, so this is fairly simple.
const auto after = std::ranges::upper_bound(
ranges_, cp, {}, [](const Range& r) { return r.lo; });
return after != ranges_.begin() && cp <= std::prev(after)->hi;
}
uint32_t Canonicalize(uint32_t cp, bool fold) {
if (cp <= kMaxAsciiCodePoint) return AsciiUpper(cp);
#ifdef NODE_HAVE_I18N_SUPPORT
if (fold) {
return static_cast<uint32_t>(
u_foldCase(static_cast<UChar32>(cp), U_FOLD_CASE_DEFAULT));
}
const uint32_t upper =
static_cast<uint32_t>(u_toupper(static_cast<UChar32>(cp)));
// A non-ASCII character whose uppercase mapping is ASCII must
// not fold into it
return upper <= kMaxAsciiCodePoint ? cp : upper;
#else
return cp;
#endif // NODE_HAVE_I18N_SUPPORT
}
void AppendLowered(const std::u16string& text, std::u16string* out) {
#ifdef NODE_HAVE_I18N_SUPPORT
const int32_t length = static_cast<int32_t>(text.size());
const size_t offset = out->size();
// Lowercasing can lengthen a strings (oddly, see U+0130) so
// reserve a little slack.
//
// Should a pattern for whatever reason contain a number of these
// odd expansions, the U_BUFFER_OVERFLOW_ERROR case below will handle
// them using a slower path.
out->resize(offset + text.size() + 8);
UErrorCode status = U_ZERO_ERROR;
int32_t written = u_strToLower(reinterpret_cast<UChar*>(out->data() + offset),
static_cast<int32_t>(out->size() - offset),
reinterpret_cast<const UChar*>(text.data()),
length,
"",
&status);
if (status == U_BUFFER_OVERFLOW_ERROR) {
out->resize(offset + written);
status = U_ZERO_ERROR;
written = u_strToLower(reinterpret_cast<UChar*>(out->data() + offset),
static_cast<int32_t>(out->size() - offset),
reinterpret_cast<const UChar*>(text.data()),
length,
"",
&status);
}
if (U_FAILURE(status)) {
out->resize(offset);
out->append(text);
return;
}
out->resize(offset + written);
#else
for (char16_t c : text) {
out->push_back(static_cast<char16_t>(AsciiLower(c)));
}
#endif // NODE_HAVE_I18N_SUPPORT
}
} // namespace node::glob
+74
View File
@@ -0,0 +1,74 @@
#ifndef SRC_GLOB_GLOB_UNICODE_H_
#define SRC_GLOB_GLOB_UNICODE_H_
#include <cstdint>
#include <string>
#include <vector>
#include "glob/glob_ast.h"
namespace node::glob {
// The last code point whose case mapping is pure ASCII arithmetic; above it
// case folding needs ICU (see Canonicalize).
inline constexpr uint32_t kMaxAsciiCodePoint = 0x7F;
// Avoiding util.h's ASCII + Locale work saves time, so this
// is a simple reimplementation.
inline constexpr uint32_t AsciiLower(uint32_t c) {
return (c >= 'A' && c <= 'Z') ? c + 32 : c;
}
inline constexpr uint32_t AsciiUpper(uint32_t c) {
return (c >= 'a' && c <= 'z') ? c - 32 : c;
}
enum class UnicodeProperty {
kLetter, // \p{L}
kLetterNumber, // \p{Nl}
kDecimalNumber, // \p{Nd}
kSpaceSeparator, // \p{Zs}
kControl, // \p{Cc}
kSeparator, // \p{Z}
kOther, // \p{C}
kLowercase, // \p{Ll}
kUppercase, // \p{Lu}
kPunctuation, // \p{P}
kConnector, // \p{Pc}
};
class CharSet {
public:
struct Range {
uint32_t lo;
uint32_t hi;
};
void AddRange(uint32_t lo, uint32_t hi);
void AddChar(uint32_t cp) { AddRange(cp, cp); }
// Adds every code point with the given property.
bool AddProperty(UnicodeProperty property);
bool CloseOverCaseFold();
void CanonicalizeMembers();
bool Contains(uint32_t cp) const;
bool empty() const { return ranges_.empty(); }
// Sorts and merges the ranges (so that we can optimize them!)
void Seal();
const std::vector<Range>& ranges() const { return ranges_; }
private:
std::vector<Range> ranges_;
};
uint32_t Canonicalize(uint32_t cp, bool fold);
// String.prototype.toLowerCase(), appended to `out`
void AppendLowered(const std::u16string& text, std::u16string* out);
} // namespace node::glob
#endif // SRC_GLOB_GLOB_UNICODE_H_
File diff suppressed because it is too large. Load diff
+127
View File
@@ -0,0 +1,127 @@
#ifndef SRC_GLOB_GLOB_WALKER_H_
#define SRC_GLOB_GLOB_WALKER_H_
#if defined(NODE_WANT_INTERNALS) && NODE_WANT_INTERNALS
#include <cstdint>
#include <limits>
#include <memory>
#include <string>
#include <string_view>
#include <vector>
#include "glob/glob_program.h"
#include "uv.h"
namespace node {
class Environment;
} // namespace node
namespace node::glob {
class ExcludeFilter {
public:
virtual ~ExcludeFilter() = default;
// A path relative to the walk's cwd.
virtual bool ExcludesPath(std::string_view path) = 0;
// A directory entry: its name, the absolute path of the directory holding
// it, and its uv_dirent_type_t.
virtual bool ExcludesEntry(std::string_view name,
std::string_view parent_path,
int type) = 0;
// Set once a call has thrown. The walk stops and the exception is left
// for the caller to propagate.
virtual bool failed() const = 0;
};
struct WalkOptions {
// options.cwd, or ".": the string paths are resolved against.
std::string cwd = ".";
bool follow_symlinks = false;
bool with_file_types = false;
// options.maxDepth: how many directory levels below cwd a result may
// sit at (cwd itself is 0), or kNoDepthLimit.
static constexpr size_t kNoDepthLimit = std::numeric_limits<size_t>::max();
size_t max_depth = kNoDepthLimit;
ExcludeFilter* exclude_filter = nullptr;
};
struct WalkEntry {
std::string path;
int type = UV_DIRENT_UNKNOWN;
};
// One call a walk off the main thread needs made to the exclude callback,
// which only that thread can do. A directory's questions are recorded in
// the order the callback would see them, together with what decides
// whether each is asked at all, so the main thread can put exactly the
// calls the walk on that thread would have made.
struct Question {
static constexpr size_t kNoEntry = SIZE_MAX;
// ExcludesEntry(first, parent, type) when set, else ExcludesPath(first)
bool entry;
std::string first;
std::string parent;
int type;
// The listing entry the question belongs to; kNoEntry for none
size_t entry_id;
// For an entry question: whether "not excluded" makes the walk descend
// into the entry, which raises the entry's path question. For a path
// question: whether the walk descends regardless of the entry's answers.
bool descends;
};
struct Answer {
bool entry;
bool excluded;
};
class WalkerImpl;
class Walk {
public:
Walk(Environment* env,
const WalkOptions& options,
const std::vector<CompiledPatternPtr>& includes,
const std::vector<CompiledPatternPtr>& excludes);
~Walk();
// Advances the traversal until at least `max_results` new results are
// available or the walk is over
bool RunSlice(size_t max_results,
bool on_main_thread,
std::vector<WalkEntry>* out);
// A slice that stopped because a directory needs the exclude callback:
// the questions for the main thread, then the answers to resume with.
bool HasQuestions() const;
const std::vector<Question>& questions() const;
void SetAnswers(std::vector<Answer> answers);
// Paths the permission model denied off the main thread since the last
// call, for publishing from that thread
void TakeDenied(std::vector<std::string>* out);
// Stops background scanning and joins the walk's threads. Idempotent;
// safe while a slice is in flight (it will wind down promptly). Called
// when the walk finishes or is cancelled so threads never wait for
// garbage collection.
void Stop();
private:
std::unique_ptr<WalkerImpl> impl_;
};
// Runs a walk to completion.
void GlobSync(Environment* env,
const WalkOptions& options,
const std::vector<CompiledPatternPtr>& includes,
const std::vector<CompiledPatternPtr>& excludes,
std::vector<WalkEntry>* out);
} // namespace node::glob
#endif // defined(NODE_WANT_INTERNALS) && NODE_WANT_INTERNALS
#endif // SRC_GLOB_GLOB_WALKER_H_
+697
View File
@@ -0,0 +1,697 @@
#include "glob/node_glob.h"
#include <cmath>
#include <limits>
#include "env-inl.h"
#include "glob/glob_matcher.h"
#include "glob/glob_parser.h"
#include "glob/glob_walker.h"
#include "memory_tracker-inl.h"
#include "node_errors.h"
#include "node_external_reference.h"
#include "util-inl.h"
#include "v8.h"
namespace node::glob {
using v8::Array;
using v8::Boolean;
using v8::Context;
using v8::Exception;
using v8::Function;
using v8::FunctionCallbackInfo;
using v8::FunctionTemplate;
using v8::HandleScope;
using v8::Integer;
using v8::Isolate;
using v8::Just;
using v8::Local;
using v8::Maybe;
using v8::MaybeLocal;
using v8::Nothing;
using v8::Number;
using v8::Object;
using v8::ObjectTemplate;
using v8::Promise;
using v8::SnapshotCreator;
using v8::String;
using v8::Uint32;
using v8::Undefined;
using v8::Value;
namespace {
constexpr uint32_t kFlagWindows = 1;
constexpr uint32_t kFlagNocase = 2;
constexpr uint32_t kFlagDot = 4;
constexpr uint32_t kFlagFollowSymlinks = 8;
constexpr uint32_t kFlagWithFileTypes = 16;
constexpr uint32_t kFlagMatchBase = 32;
// Not sent from JavaScript, only distinguishes cache keys
constexpr uint32_t kFlagNocaseLiterals = 64;
// The host's own facts are not sent from JavaScript. Matching keeps the
// caller's `windows` choice (path.win32/posix work from anywhere), so only
// case sensitivity is the host's; a walk always follows the host's rules.
#ifdef _WIN32
constexpr uint32_t kHostMatchFlags = kFlagNocase;
constexpr uint32_t kHostWalkFlags = kFlagWindows | kFlagNocase;
#elif defined(__APPLE__)
constexpr uint32_t kHostMatchFlags = kFlagNocase;
constexpr uint32_t kHostWalkFlags = kFlagNocase;
#else
constexpr uint32_t kHostMatchFlags = 0;
constexpr uint32_t kHostWalkFlags = 0;
#endif
CompileFlags UnpackFlags(uint32_t packed) {
CompileFlags flags;
flags.windows = (packed & kFlagWindows) != 0;
flags.nocase = (packed & kFlagNocase) != 0;
flags.dot = (packed & kFlagDot) != 0;
flags.match_base = (packed & kFlagMatchBase) != 0;
return flags;
}
// Builds the compiled-pattern cache key into `key` (for caching)
void BuildCacheKey(PatternView pattern,
const CompileFlags& flags,
PatternString* key) {
const uint32_t packed =
(flags.windows ? kFlagWindows : 0) | (flags.nocase ? kFlagNocase : 0) |
(flags.dot ? kFlagDot : 0) | (flags.match_base ? kFlagMatchBase : 0) |
(flags.nocase_magic_only ? 0 : kFlagNocaseLiterals);
key->assign(1, static_cast<char16_t>(packed));
key->append(pattern);
}
// Patterns that do not compile throw, try a different pattern
void ThrowCompileError(Isolate* isolate, CompileError error) {
const bool bad_regexp = error == CompileError::kInvalidRegExp;
const char* message;
switch (error) {
case CompileError::kPatternTooDeep:
message = "pattern nests too deeply";
break;
case CompileError::kInvalidRegExp:
message = "invalid generated regular expression";
break;
default:
message = "pattern is too long";
break;
}
Local<String> text = OneByteString(isolate, message);
isolate->ThrowException(bad_regexp ? Exception::SyntaxError(text)
: Exception::TypeError(text));
}
constexpr size_t kMarshalStackEntries = GlobRequest::kBatchSize;
// Builds [paths array, types array|undefined] for a batch of results.
bool MarshalEntries(Environment* env,
const std::vector<WalkEntry>& entries,
bool with_types,
Local<Array>* paths_out,
Local<Value>* types_out) {
Isolate* isolate = env->isolate();
Local<Context> context = env->context();
MaybeStackBuffer<Value, kMarshalStackEntries> paths(isolate, entries.size());
for (size_t i = 0; i < entries.size(); i++) {
if (!ToV8Value(context, entries[i].path, isolate).ToLocal(&paths[i])) {
return false;
}
}
*paths_out = paths.ToArray();
*types_out = Undefined(isolate);
if (with_types) {
MaybeStackBuffer<Value, kMarshalStackEntries> types(isolate,
entries.size());
for (size_t i = 0; i < entries.size(); i++) {
types[i] = Integer::New(isolate, entries[i].type);
}
*types_out = types.ToArray();
}
return true;
}
size_t ProgramSize(const CompiledPattern& p) {
size_t total = sizeof(CompiledPattern);
for (const CompiledPattern::Row& row : p.rows) {
total += sizeof(CompiledPattern::Row);
for (const PartMatcher& part : row.parts) {
total += sizeof(PartMatcher) + part.literal.size() * sizeof(char16_t) +
part.program.literal.size() * sizeof(char16_t) +
part.program.nodes.size() * sizeof(RxNode);
for (const RxNode& node : part.program.nodes) {
total += node.text.size() * sizeof(char16_t) +
(node.klass.positive.ranges().size() +
node.klass.negative.ranges().size()) *
sizeof(CharSet::Range) +
node.children.size() * sizeof(uint32_t);
}
}
}
return total;
}
} // namespace
BindingData::BindingData(Realm* realm,
Local<Object> object,
InternalFieldInfoBase* info)
: SnapshotableObject(realm, object, type_int) {}
bool BindingData::PrepareForSerialization(Local<Context> context,
SnapshotCreator* creator) {
cache_.Clear();
return true;
}
InternalFieldInfoBase* BindingData::Serialize(int index) {
DCHECK_IS_SNAPSHOT_SLOT(index);
return InternalFieldInfoBase::New<InternalFieldInfo>(type());
}
void BindingData::Deserialize(Local<Context> context,
Local<Object> holder,
int index,
InternalFieldInfoBase* info) {
DCHECK_IS_SNAPSHOT_SLOT(index);
Realm* realm = Realm::GetCurrent(context);
HandleScope scope(realm->isolate());
BindingData* binding = realm->AddBindingData<BindingData>(holder, info);
CHECK_NOT_NULL(binding);
}
void BindingData::MemoryInfo(MemoryTracker* tracker) const {
size_t bytes = 0;
for (const auto& [key, entry] : cache_) {
bytes += key.size() * sizeof(char16_t) + sizeof(CacheEntry) +
ProgramSize(entry->compiled);
}
tracker->TrackFieldWithSize("compiled_pattern_cache", bytes);
}
CompiledPatternPtr BindingData::Lookup(PatternView pattern,
const CompileFlags& flags,
CompileError* error) {
BuildCacheKey(pattern, flags, &lookup_key_);
const PatternString& key = lookup_key_;
std::shared_ptr<CacheEntry> entry;
if (std::shared_ptr<CacheEntry>* found = cache_.GetIf(key)) {
entry = *found;
} else {
entry = std::make_shared<CacheEntry>();
ParseResult parsed = ParsePattern(pattern, flags);
if (parsed.error != CompileError::kNone) {
entry->error = parsed.error;
} else {
entry->compiled = CompileProgram(std::move(parsed.pattern), flags);
entry->error = entry->compiled.error;
}
cache_.Put(key, entry);
}
*error = entry->error;
if (entry->error != CompileError::kNone) return nullptr;
return CompiledPatternPtr(entry, &entry->compiled);
}
void BindingData::MatchesGlob(const FunctionCallbackInfo<Value>& args) {
Realm* realm = Realm::GetCurrent(args);
BindingData* binding = realm->GetBindingData<BindingData>();
Isolate* isolate = realm->isolate();
CHECK_EQ(args.Length(), 3);
CHECK(args[0]->IsString()); // path
CHECK(args[1]->IsString()); // pattern
CHECK(args[2]->IsUint32()); // packed flags
const CompileFlags flags =
UnpackFlags(args[2].As<Uint32>()->Value() | kHostMatchFlags);
TwoByteValue pattern(isolate, args[1]);
CompileError error = CompileError::kNone;
const CompiledPatternPtr compiled =
binding->Lookup(pattern.ToU16StringView(), flags, &error);
if (compiled == nullptr) {
ThrowCompileError(isolate, error);
return;
}
TwoByteValue path(isolate, args[0]);
args.GetReturnValue().Set(MatchPattern(*compiled, path.ToU16StringView()));
}
// Whether the pattern is anything more than a simple, literal path
// (Basically, is it a glob or just a normal string)
void BindingData::HasMagic(const FunctionCallbackInfo<Value>& args) {
Realm* realm = Realm::GetCurrent(args);
BindingData* binding = realm->GetBindingData<BindingData>();
Isolate* isolate = realm->isolate();
CHECK_EQ(args.Length(), 1);
CHECK(args[0]->IsString());
const CompileFlags flags = UnpackFlags(kHostWalkFlags);
TwoByteValue pattern(isolate, args[0]);
CompileError error = CompileError::kNone;
const CompiledPatternPtr compiled =
binding->Lookup(pattern.ToU16StringView(), flags, &error);
if (compiled == nullptr) {
ThrowCompileError(isolate, error);
return;
}
for (const CompiledPattern::Row& row : compiled->rows) {
for (const PartMatcher& part : row.parts) {
if (part.kind != PartMatcher::Kind::kLiteral) {
args.GetReturnValue().Set(true);
return;
}
}
}
args.GetReturnValue().Set(false);
}
// Both strings are one-byte and the pattern is normally
// already compiled, so the whole call is a hash lookup plus the match.
// Reads (cwd, includePatterns[], excludePatterns[], flags, excludeFn,
// maxDepth) and compiles the patterns.
bool BindingData::ReadWalkArguments(const FunctionCallbackInfo<Value>& args,
WalkOptions* options,
std::vector<CompiledPatternPtr>* includes,
std::vector<CompiledPatternPtr>* excludes,
std::unique_ptr<JsExcludeFilter>* filter) {
Realm* realm = Realm::GetCurrent(args);
Isolate* isolate = realm->isolate();
Local<Context> context = realm->context();
CHECK_EQ(args.Length(), 6);
CHECK(args[0]->IsString()); // cwd
CHECK(args[1]->IsArray()); // include patterns
CHECK(args[2]->IsArray()); // exclude patterns
CHECK(args[3]->IsUint32()); // packed flags
CHECK(args[4]->IsFunction() || args[4]->IsUndefined()); // exclude callback
CHECK(args[5]->IsNumber()); // maxDepth
const uint32_t packed = args[3].As<Uint32>()->Value() | kHostWalkFlags;
const CompileFlags flags = UnpackFlags(packed);
// Exclude matching is a pure string comparison with no filesystem lookups,
// so unlike include patterns, literal segments must also match
// case-insensitively on case-insensitive platforms.
CompileFlags exclude_flags = flags;
exclude_flags.nocase_magic_only = false;
options->follow_symlinks = (packed & kFlagFollowSymlinks) != 0;
options->with_file_types = (packed & kFlagWithFileTypes) != 0;
if (args[4]->IsFunction()) {
*filter =
std::make_unique<JsExcludeFilter>(realm->env(), args[4].As<Function>());
options->exclude_filter = filter->get();
}
{
Utf8Value cwd(isolate, args[0]);
options->cwd = cwd.ToString();
}
// A non-negative integer, or Infinity for no limit, validated in JS.
const double max_depth = args[5].As<Number>()->Value();
if (std::isfinite(max_depth)) {
CHECK_GE(max_depth, 0);
options->max_depth = static_cast<size_t>(max_depth);
}
for (int which = 0; which < 2; which++) {
std::vector<CompiledPatternPtr>* out = which == 0 ? includes : excludes;
Local<Array> list = args[1 + which].As<Array>();
const uint32_t length = list->Length();
out->reserve(length);
for (uint32_t i = 0; i < length; i++) {
Local<Value> value;
if (!list->Get(context, i).ToLocal(&value)) return false;
CHECK(value->IsString());
TwoByteValue pattern(isolate, value);
CompileError error = CompileError::kNone;
CompiledPatternPtr compiled = Lookup(pattern.ToU16StringView(),
which == 0 ? flags : exclude_flags,
&error);
if (compiled == nullptr) {
ThrowCompileError(isolate, error);
return false;
}
out->push_back(std::move(compiled));
}
}
return true;
}
// globSync(cwd, includePatterns[], excludePatterns[], flags, excludeFn,
// maxDepth)
void BindingData::GlobSync(const FunctionCallbackInfo<Value>& args) {
Realm* realm = Realm::GetCurrent(args);
Environment* env = realm->env();
BindingData* binding = realm->GetBindingData<BindingData>();
Isolate* isolate = realm->isolate();
WalkOptions options;
std::vector<CompiledPatternPtr> includes;
std::vector<CompiledPatternPtr> excludes;
std::unique_ptr<JsExcludeFilter> filter;
if (!binding->ReadWalkArguments(
args, &options, &includes, &excludes, &filter)) {
return;
}
std::vector<WalkEntry> entries;
glob::GlobSync(env, options, includes, excludes, &entries);
// An exclude callback that threw leaves its exception pending.
if (filter != nullptr && filter->failed()) return;
Local<Array> paths;
Local<Value> types;
if (!MarshalEntries(env, entries, options.with_file_types, &paths, &types)) {
return;
}
if (!options.with_file_types) {
args.GetReturnValue().Set(paths);
return;
}
Local<Value> pair[] = {paths, types};
args.GetReturnValue().Set(Array::New(isolate, pair, arraysize(pair)));
}
// Calls the user's `exclude`
JsExcludeFilter::JsExcludeFilter(Environment* env, Local<Function> callback)
: env_(env), callback_(env->isolate(), callback) {}
Maybe<bool> JsExcludeFilter::Call(bool entry,
std::string_view first,
std::string_view second,
int type) {
Isolate* isolate = env_->isolate();
HandleScope scope(isolate);
Local<Context> context = env_->context();
// (isEntry, name-or-path, parentPath, type), see #excludeAdapter().
Local<Value> argv[4];
if (!ToV8Value(context, first, isolate).ToLocal(&argv[1]) ||
!ToV8Value(context, second, isolate).ToLocal(&argv[2])) {
return Nothing<bool>();
}
argv[0] = Boolean::New(isolate, entry);
argv[3] = Integer::New(isolate, type);
Local<Value> result;
if (!callback_.Get(isolate)
->Call(context, Undefined(isolate), arraysize(argv), argv)
.ToLocal(&result)) {
return Nothing<bool>();
}
return Just(result->BooleanValue(isolate));
}
bool JsExcludeFilter::ExcludesPath(std::string_view path) {
if (failed_) return false;
bool excluded = false;
failed_ = !Call(false, path, std::string_view(), 0).To(&excluded);
return excluded;
}
bool JsExcludeFilter::ExcludesEntry(std::string_view name,
std::string_view parent_path,
int type) {
if (failed_) return false;
bool excluded = false;
failed_ = !Call(true, name, parent_path, type).To(&excluded);
return excluded;
}
GlobRequest::GlobRequest(Environment* env,
Local<Object> object,
const WalkOptions& options,
const std::vector<CompiledPatternPtr>& includes,
const std::vector<CompiledPatternPtr>& excludes,
std::unique_ptr<JsExcludeFilter> filter)
: AsyncWrap(env, object, AsyncWrap::PROVIDER_GLOBREQUEST),
ThreadPoolWork(env, "glob"),
filter_(std::move(filter)),
walk_(env, options, includes, excludes),
with_file_types_(options.with_file_types) {
MakeWeak();
}
void GlobRequest::MemoryInfo(MemoryTracker* tracker) const {
// A slice in flight owns batch_ on another thread.
if (!in_flight_) {
tracker->TrackFieldWithSize("batch", batch_.size() * sizeof(WalkEntry));
}
}
void GlobRequest::DoThreadPoolWork() {
// A pull spans several slices when the exclude callback is consulted
// in between; the batch keeps filling across them (and a directory
// visited before a stop may already have filled it).
size_t max_results = std::numeric_limits<size_t>::max();
if (!drain_) {
max_results = batch_.size() < kBatchSize ? kBatchSize - batch_.size() : 0;
}
done_ = walk_.RunSlice(max_results, /*on_main_thread=*/false, &batch_);
}
void GlobRequest::PublishDenials() {
Environment* env = AsyncWrap::env();
std::vector<std::string> denied;
walk_.TakeDenied(&denied);
for (const std::string& path : denied) {
env->permission()->PublishDenied(
env, permission::PermissionScope::kFileSystemRead, path);
}
}
void GlobRequest::AnswerQuestions() {
std::vector<Answer> answers;
size_t entry = Question::kNoEntry;
bool descends = false; // whether the walk descends into `entry`
for (const Question& question : walk_.questions()) {
if (question.entry_id != entry) {
entry = question.entry_id;
descends = false;
}
bool excluded;
if (question.entry) {
excluded = filter_->ExcludesEntry(
question.first, question.parent, question.type);
if (!excluded && question.descends) descends = true;
} else {
// A subpattern is only asked about when the walk descends into it.
if (entry != Question::kNoEntry && !question.descends && !descends) {
continue;
}
excluded = filter_->ExcludesPath(question.first);
}
// The callback threw: its exception is pending, the walk is over.
if (filter_->failed()) return;
answers.push_back({question.entry, excluded});
}
walk_.SetAnswers(std::move(answers));
}
// Builds [paths, types|undefined, done]
MaybeLocal<Value> GlobRequest::Settle() {
Environment* env = AsyncWrap::env();
Isolate* isolate = env->isolate();
Local<Array> paths;
Local<Value> types;
if (!MarshalEntries(env, batch_, with_file_types_, &paths, &types)) {
return MaybeLocal<Value>();
}
batch_.clear();
Local<Value> result[] = {paths, types, Boolean::New(isolate, done_)};
return Array::New(isolate, result, arraysize(result));
}
void GlobRequest::AfterThreadPoolWork(int status) {
in_flight_ = false;
Environment* env = AsyncWrap::env();
// Environment teardown or a cancelled queue entry must not call back
// into JavaScript.
if (status == UV_ECANCELED || !env->can_call_into_js()) {
resolver_.Reset();
done_ = true;
walk_.Stop();
MakeWeak();
return;
}
if (cancelled_) done_ = true;
HandleScope scope(env->isolate());
Local<Context> context = env->context();
Context::Scope context_scope(context);
InternalCallbackScope callback_scope(this);
PublishDenials();
if (!done_ && walk_.HasQuestions()) {
errors::TryCatchScope try_catch(env);
AnswerQuestions();
if (try_catch.HasCaught() || filter_->failed()) {
// The exclude callback threw: the pull rejects with its exception.
done_ = true;
walk_.Stop();
batch_.clear();
Local<Promise::Resolver> resolver = resolver_.Get(env->isolate());
resolver_.Reset();
MakeWeak();
// A terminating isolate (worker shutdown) has nothing to pass on.
if (try_catch.HasTerminated() || !try_catch.HasCaught()) return;
USE(resolver->Reject(context, try_catch.Exception()));
return;
}
// The walk resumes with the answers.
in_flight_ = true;
ScheduleWork();
return;
}
// A finished walk keeps no threads waiting for garbage collection.
if (done_) walk_.Stop();
Local<Promise::Resolver> resolver = resolver_.Get(env->isolate());
resolver_.Reset();
// The request is idle again, so it may be collected with its handle.
MakeWeak();
Local<Value> value;
if (!Settle().ToLocal(&value)) return;
USE(resolver->Resolve(context, value));
}
// next() -> Promise<[paths, types, done]>: one batch of results.
void GlobRequest::Next(const FunctionCallbackInfo<Value>& args) {
Pull(args, /*drain=*/false);
}
// all() -> Promise<[paths, types, done]>: the rest of the walk at once.
void GlobRequest::All(const FunctionCallbackInfo<Value>& args) {
Pull(args, /*drain=*/true);
}
void GlobRequest::Pull(const FunctionCallbackInfo<Value>& args, bool drain) {
GlobRequest* request;
ASSIGN_OR_RETURN_UNWRAP(&request, args.This());
Environment* env = request->AsyncWrap::env();
Isolate* isolate = env->isolate();
// Reachable through the async_hooks resource object, so misuse (a
// second pull, or a pull from inside an exclude callback) must throw,
// not crash or clobber the pending resolver.
if (request->in_flight_) {
THROW_ERR_INVALID_STATE(env, "glob is already waiting for results");
return;
}
request->drain_ = drain;
Local<Promise::Resolver> resolver;
if (!Promise::Resolver::New(env->context()).ToLocal(&resolver)) return;
args.GetReturnValue().Set(resolver->GetPromise());
if (request->cancelled_ || request->done_) {
request->done_ = true;
Local<Value> value;
if (!request->Settle().ToLocal(&value)) return;
USE(resolver->Resolve(env->context(), value));
return;
}
request->resolver_.Reset(isolate, resolver);
request->in_flight_ = true;
// Keep the request alive for as long as the worker holds a pointer to it.
request->ClearWeak();
request->ScheduleWork();
}
// Stops the walk. A slice in flight still owns done_; the cancellation
// takes effect when it completes, but the walk's threads stop now.
void GlobRequest::Cancel(const FunctionCallbackInfo<Value>& args) {
GlobRequest* request;
ASSIGN_OR_RETURN_UNWRAP(&request, args.This());
request->cancelled_ = true;
if (!request->in_flight_) request->done_ = true;
request->walk_.Stop();
}
void BindingData::GlobStart(const FunctionCallbackInfo<Value>& args) {
Realm* realm = Realm::GetCurrent(args);
Environment* env = realm->env();
BindingData* binding = realm->GetBindingData<BindingData>();
WalkOptions options;
std::vector<CompiledPatternPtr> includes;
std::vector<CompiledPatternPtr> excludes;
std::unique_ptr<JsExcludeFilter> filter;
if (!binding->ReadWalkArguments(
args, &options, &includes, &excludes, &filter)) {
return;
}
Local<Object> object;
if (!env->glob_request_template()
->InstanceTemplate()
->NewInstance(realm->context())
.ToLocal(&object)) {
return;
}
new GlobRequest(env, object, options, includes, excludes, std::move(filter));
args.GetReturnValue().Set(object);
}
void BindingData::CreatePerIsolateProperties(IsolateData* isolate_data,
Local<ObjectTemplate> target) {
Isolate* isolate = isolate_data->isolate();
SetMethodNoSideEffect(isolate, target, "matchesGlob", MatchesGlob);
SetMethodNoSideEffect(isolate, target, "hasMagic", HasMagic);
SetMethod(isolate, target, "globSync", GlobSync);
SetMethod(isolate, target, "globStart", GlobStart);
Local<FunctionTemplate> glob_request = NewFunctionTemplate(isolate, nullptr);
glob_request->InstanceTemplate()->SetInternalFieldCount(
AsyncWrap::kInternalFieldCount);
glob_request->Inherit(AsyncWrap::GetConstructorTemplate(isolate_data));
SetProtoMethod(isolate, glob_request, "next", GlobRequest::Next);
SetProtoMethod(isolate, glob_request, "all", GlobRequest::All);
SetProtoMethod(isolate, glob_request, "cancel", GlobRequest::Cancel);
isolate_data->set_glob_request_template(glob_request);
}
void BindingData::CreatePerContextProperties(Local<Object> target,
Local<Value> unused,
Local<Context> context,
void* priv) {
Realm* realm = Realm::GetCurrent(context);
realm->AddBindingData<BindingData>(target);
// The flag bits JavaScript may pass back in; the host-only bits stay
// private to this file.
NODE_DEFINE_CONSTANT(target, kFlagWindows);
NODE_DEFINE_CONSTANT(target, kFlagDot);
NODE_DEFINE_CONSTANT(target, kFlagFollowSymlinks);
NODE_DEFINE_CONSTANT(target, kFlagWithFileTypes);
NODE_DEFINE_CONSTANT(target, kFlagMatchBase);
}
void BindingData::RegisterExternalReferences(
ExternalReferenceRegistry* registry) {
registry->Register(MatchesGlob);
registry->Register(HasMagic);
registry->Register(GlobSync);
registry->Register(GlobStart);
registry->Register(GlobRequest::Next);
registry->Register(GlobRequest::All);
registry->Register(GlobRequest::Cancel);
}
} // namespace node::glob
NODE_BINDING_CONTEXT_AWARE_INTERNAL(
glob, node::glob::BindingData::CreatePerContextProperties)
NODE_BINDING_PER_ISOLATE_INIT(
glob, node::glob::BindingData::CreatePerIsolateProperties)
NODE_BINDING_EXTERNAL_REFERENCE(
glob, node::glob::BindingData::RegisterExternalReferences)
+150
View File
@@ -0,0 +1,150 @@
#ifndef SRC_GLOB_NODE_GLOB_H_
#define SRC_GLOB_NODE_GLOB_H_
#if defined(NODE_WANT_INTERNALS) && NODE_WANT_INTERNALS
#include <memory>
#include <string>
#include <string_view>
#include "async_wrap.h"
#include "glob/glob_program.h"
#include "glob/glob_walker.h"
#include "lru_cache-inl.h"
#include "node_internals.h"
#include "node_snapshotable.h"
#include "threadpoolwork-inl.h"
namespace node::glob {
// Consults a JavaScript `exclude` callback.
class JsExcludeFilter final : public ExcludeFilter {
public:
JsExcludeFilter(Environment* env, v8::Local<v8::Function> callback);
bool ExcludesPath(std::string_view path) override;
bool ExcludesEntry(std::string_view name,
std::string_view parent_path,
int type) override;
bool failed() const override { return failed_; }
private:
// Nothing when the callback threw; the exception stays pending.
v8::Maybe<bool> Call(bool entry,
std::string_view first,
std::string_view second,
int type);
Environment* env_;
v8::Global<v8::Function> callback_;
bool failed_ = false;
};
class BindingData : public SnapshotableObject {
public:
BindingData(Realm* realm,
v8::Local<v8::Object> object,
InternalFieldInfoBase* info = nullptr);
using InternalFieldInfo = InternalFieldInfoBase;
SERIALIZABLE_OBJECT_METHODS()
SET_BINDING_ID(glob_binding_data)
void MemoryInfo(MemoryTracker* tracker) const override;
SET_SELF_SIZE(BindingData)
SET_MEMORY_INFO_NAME(BindingData)
static void MatchesGlob(const v8::FunctionCallbackInfo<v8::Value>& args);
static void HasMagic(const v8::FunctionCallbackInfo<v8::Value>& args);
static void GlobSync(const v8::FunctionCallbackInfo<v8::Value>& args);
static void GlobStart(const v8::FunctionCallbackInfo<v8::Value>& args);
static void CreatePerIsolateProperties(IsolateData* isolate_data,
v8::Local<v8::ObjectTemplate> target);
static void CreatePerContextProperties(v8::Local<v8::Object> target,
v8::Local<v8::Value> unused,
v8::Local<v8::Context> context,
void* priv);
static void RegisterExternalReferences(ExternalReferenceRegistry* registry);
bool ReadWalkArguments(const v8::FunctionCallbackInfo<v8::Value>& args,
WalkOptions* options,
std::vector<CompiledPatternPtr>* includes,
std::vector<CompiledPatternPtr>* excludes,
std::unique_ptr<JsExcludeFilter>* filter);
// Compiles (or fetches) `pattern`; returns nullptr on a compile error,
// with the reason written to *error.
CompiledPatternPtr Lookup(PatternView pattern,
const CompileFlags& flags,
CompileError* error);
private:
struct CacheEntry {
CompiledPattern compiled;
// Set when the pattern does not compile.
CompileError error = CompileError::kNone;
};
// A compiled pattern is large, so we limit the size
// of the cache.
static constexpr size_t kMaxCacheEntries = 256;
// Compiled patterns, keyed by the pattern text + flag
LRUCache<PatternString, std::shared_ptr<CacheEntry>> cache_{kMaxCacheEntries};
PatternString lookup_key_;
};
class GlobRequest : public AsyncWrap, public ThreadPoolWork {
public:
GlobRequest(Environment* env,
v8::Local<v8::Object> object,
const WalkOptions& options,
const std::vector<CompiledPatternPtr>& includes,
const std::vector<CompiledPatternPtr>& excludes,
std::unique_ptr<JsExcludeFilter> filter);
// How many results an iterator pull returns at a time.
// See the explanation in this header's .cc file for
// more information.
static constexpr size_t kBatchSize = 256;
static void Next(const v8::FunctionCallbackInfo<v8::Value>& args);
static void All(const v8::FunctionCallbackInfo<v8::Value>& args);
static void Cancel(const v8::FunctionCallbackInfo<v8::Value>& args);
void DoThreadPoolWork() override;
void AfterThreadPoolWork(int status) override;
void MemoryInfo(MemoryTracker* tracker) const override;
SET_MEMORY_INFO_NAME(GlobRequest)
SET_SELF_SIZE(GlobRequest)
private:
static void Pull(const v8::FunctionCallbackInfo<v8::Value>& args, bool drain);
v8::MaybeLocal<v8::Value> Settle();
// The main-thread half of a slice: publishes the permission denials the
// walk met and puts the questions of a directory waiting on the exclude
// callback to it, in the order the walk would have.
void PublishDenials();
void AnswerQuestions();
// Declared before the walk, which points at it.
std::unique_ptr<JsExcludeFilter> filter_;
Walk walk_;
const bool with_file_types_;
// Set by all(): the pull consumes the rest of the walk in one batch.
bool drain_ = false;
bool done_ = false;
bool cancelled_ = false;
bool in_flight_ = false;
std::vector<WalkEntry> batch_;
v8::Global<v8::Promise::Resolver> resolver_;
};
} // namespace node::glob
#endif // defined(NODE_WANT_INTERNALS) && NODE_WANT_INTERNALS
#endif // SRC_GLOB_NODE_GLOB_H_
+8
View File
@@ -41,6 +41,14 @@ class LRUCache {
return it->second->second;
}
// The entry for `key`, or nullptr when there is none.
value_t* GetIf(const key_t& key) {
auto it = lookup_map_.find(key);
if (it == lookup_map_.end()) return nullptr;
lru_list_.splice(lru_list_.begin(), lru_list_, it->second);
return &it->second->second;
}
void Erase(const key_t& key) {
auto it = lookup_map_.find(key);
if (it != lookup_map_.end()) {
+1
View File
@@ -69,6 +69,7 @@
V(fs) \
V(fs_dir) \
V(fs_event_wrap) \
V(glob) \
V(heap_utils) \
V(http2) \
V(http_parser) \
+1
View File
@@ -65,6 +65,7 @@ static_assert(static_cast<int>(NM_F_LINKED) ==
V(encoding_binding) \
V(fs) \
V(fs_dir) \
V(glob) \
V(http_parser) \
V(locks) \
V(messaging) \
+1
View File
@@ -80,6 +80,7 @@ class ExternalReferenceRegistry {
V(fs) \
V(fs_dir) \
V(fs_event_wrap) \
V(glob) \
V(handle_wrap) \
V(heap_utils) \
V(http_parser) \
+1
View File
@@ -11,6 +11,7 @@
#include "embedded_data.h"
#include "encoding_binding.h"
#include "env-inl.h"
#include "glob/node_glob.h"
#include "node_blob.h"
#include "node_builtins.h"
#include "node_contextify.h"
-9
View File
@@ -47,15 +47,6 @@ using v8::String;
using v8::Uint32;
using v8::Value;
// If a UTF-16 character is a low/trailing surrogate.
CHAR_TEST(16, IsUnicodeTrail, (ch & 0xFC00) == 0xDC00)
// If a UTF-16 character is a surrogate.
CHAR_TEST(16, IsUnicodeSurrogate, (ch & 0xF800) == 0xD800)
// If a UTF-16 surrogate is a low/trailing one.
CHAR_TEST(16, IsUnicodeSurrogateTrail, (ch & 0x400) != 0)
static void GetOwnNonIndexProperties(
const FunctionCallbackInfo<Value>& args) {
Isolate* isolate = args.GetIsolate();
-18
View File
@@ -8,16 +8,6 @@
namespace node {
#ifdef _WIN32
constexpr bool IsPathSeparator(const char c) noexcept {
return c == '\\' || c == '/';
}
#else // POSIX
constexpr bool IsPathSeparator(const char c) noexcept {
return c == '/';
}
#endif // _WIN32
std::string NormalizeString(const std::string_view path,
bool allowAboveRoot,
const std::string_view separator) {
@@ -90,14 +80,6 @@ std::string NormalizeString(const std::string_view path,
}
#ifdef _WIN32
constexpr bool IsWindowsDriveLetter(const std::string_view path) noexcept {
return path.size() > 2 && IsWindowsDeviceRoot(path[0]) &&
(path[1] == ':' && (path[2] == '/' || path[2] == '\\'));
}
constexpr bool IsWindowsDeviceRoot(const char c) noexcept {
return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z');
}
std::string PathResolve(Environment* env,
const std::vector<std::string_view>& paths) {
std::string resolvedDevice = "";
+18 -3
View File
@@ -10,7 +10,20 @@
namespace node {
constexpr bool IsPathSeparator(const char c) noexcept;
#ifdef _WIN32
constexpr bool IsPathSeparator(const char c) noexcept {
return c == '\\' || c == '/';
}
#else // POSIX
constexpr bool IsPathSeparator(const char c) noexcept {
return c == '/';
}
#endif // _WIN32
// Not _WIN32-only: callers reason about windows-style paths from any host.
constexpr bool IsWindowsDeviceRoot(const char c) noexcept {
return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z');
}
std::string NormalizeString(const std::string_view path,
bool allowAboveRoot,
@@ -22,8 +35,10 @@ std::string NormalizeFileURLOrPath(Environment* env, std::string_view path);
bool IsAbsoluteFilePath(std::string_view path);
#ifdef _WIN32
constexpr bool IsWindowsDeviceRoot(const char c) noexcept;
constexpr bool IsWindowsDriveLetter(const std::string_view path) noexcept;
constexpr bool IsWindowsDriveLetter(const std::string_view path) noexcept {
return path.size() > 2 && IsWindowsDeviceRoot(path[0]) &&
(path[1] == ':' && (path[2] == '/' || path[2] == '\\'));
}
#endif // _WIN32
void ToNamespacedPath(Environment* env, BufferValue* path);
+3
View File
@@ -120,6 +120,7 @@ namespace permission {
void FSPermission::Apply(Environment* env,
std::span<const std::string> allow,
PermissionScope scope) {
RwLock::ScopedWriteLock lock(lock_);
for (const std::string& res : allow) {
if (res == "*") {
if (scope == PermissionScope::kFileSystemRead) {
@@ -138,6 +139,7 @@ void FSPermission::Apply(Environment* env,
void FSPermission::Drop(Environment* env,
PermissionScope scope,
std::string_view param) {
RwLock::ScopedWriteLock lock(lock_);
if (param.empty()) {
// Drop all access for this scope
if (scope == PermissionScope::kFileSystemRead ||
@@ -232,6 +234,7 @@ void FSPermission::GrantAccess(PermissionScope perm, const std::string& res) {
bool FSPermission::is_granted(Environment* env,
PermissionScope perm,
std::string_view param = "") const {
RwLock::ScopedReadLock lock(lock_);
switch (perm) {
case PermissionScope::kFileSystem:
return allow_all_in_ && allow_all_out_;
+5
View File
@@ -5,6 +5,7 @@
#include <memory>
#include <vector>
#include "node_mutex.h"
#include "permission/permission_base.h"
#include "util.h"
@@ -18,6 +19,8 @@ class FSPermission final : public PermissionBase {
void Drop(Environment* env,
PermissionScope scope,
std::string_view param) override;
// Safe to call from any thread: Drop() rewrites the trees on the
// thread that owns `env`, which this waits out.
bool is_granted(Environment* env,
PermissionScope perm,
std::string_view param) const override;
@@ -183,6 +186,8 @@ class FSPermission final : public PermissionBase {
void GrantAccess(PermissionScope scope, const std::string& param);
void RevokeAccess(PermissionScope scope, const std::string& param);
void RebuildTree(PermissionScope scope);
// Guards everything below: Apply() and Drop() write, is_granted() reads.
RwLock lock_;
// fs granted on startup
RadixTree granted_in_fs_;
RadixTree granted_out_fs_;
+41 -43
View File
@@ -311,39 +311,55 @@ void Permission::EnableWarningOnly() {
}
}
bool Permission::is_scope_granted(Environment* env,
bool Permission::is_granted_quiet(Environment* env,
PermissionScope permission,
std::string_view res) const {
if (!enabled_) [[likely]] {
return true;
}
CHECK(permission != PermissionScope::kPermissionsRoot &&
permission != PermissionScope::kPermissionsCount);
auto& perm_node = nodes_[static_cast<size_t>(permission)];
bool result = false;
if (perm_node) {
result = perm_node->is_granted(env, permission, res);
}
if (!result && !publishing_) {
auto ch = GetOrCreateChannel(env, permission);
if (ch && ch->HasSubscribers()) {
publishing_ = true;
v8::Isolate* isolate = env->isolate();
v8::HandleScope handle_scope(isolate);
v8::Local<v8::Context> context = env->context();
v8::MaybeLocal<v8::Value> values[] = {
PermissionToString(env, permission),
ToV8Value(context, res),
Undefined(isolate),
};
ch->Publish(
env,
GetPermissionDiagnosticsTemplate(env)->NewInstance(context, values));
publishing_ = false;
}
}
return perm_node && perm_node->is_granted(env, permission, res);
}
bool Permission::is_scope_granted(Environment* env,
PermissionScope permission,
std::string_view res) const {
const bool result = is_granted_quiet(env, permission, res);
if (!result) Publish(env, permission, res, /*dropped=*/false);
return result;
}
void Permission::PublishDenied(Environment* env,
PermissionScope permission,
std::string_view res) const {
Publish(env, permission, res, /*dropped=*/false);
}
void Permission::Publish(Environment* env,
PermissionScope scope,
std::string_view res,
bool dropped) const {
// A subscriber's own checks must not publish recursively
if (publishing_) return;
auto ch = GetOrCreateChannel(env, scope);
if (!ch || !ch->HasSubscribers()) return;
publishing_ = true;
v8::Isolate* isolate = env->isolate();
v8::HandleScope handle_scope(isolate);
v8::Local<v8::Context> context = env->context();
v8::MaybeLocal<v8::Value> values[] = {
PermissionToString(env, scope),
ToV8Value(context, res),
dropped ? v8::True(isolate).As<v8::Value>()
: Undefined(isolate).As<v8::Value>(),
};
ch->Publish(
env, GetPermissionDiagnosticsTemplate(env)->NewInstance(context, values));
publishing_ = false;
}
BaseObjectPtr<diagnostics_channel::Channel> Permission::GetOrCreateChannel(
Environment* env, PermissionScope scope) const {
CHECK(scope != PermissionScope::kPermissionsRoot &&
@@ -380,25 +396,7 @@ void Permission::Drop(Environment* env,
}
// Publish to diagnostics channel so observers can track drops
if (!publishing_) {
auto ch = GetOrCreateChannel(env, scope);
if (ch && ch->HasSubscribers()) {
publishing_ = true;
v8::Isolate* isolate = env->isolate();
v8::HandleScope handle_scope(isolate);
v8::Local<v8::Context> context = env->context();
v8::MaybeLocal<v8::Value> values[] = {
PermissionToString(env, scope),
ToV8Value(context, param),
v8::True(isolate),
};
ch->Publish(
env,
GetPermissionDiagnosticsTemplate(env)->NewInstance(context, values));
publishing_ = false;
}
}
Publish(env, scope, param, /*dropped=*/true);
}
void Initialize(Local<Object> target,
+17
View File
@@ -97,6 +97,18 @@ class Permission {
return is_scope_granted(env, permission, res);
}
// The check alone, without the diagnostics channel message a denial
// publishes: for threads other than the one that owns `env`, which
// report their denials from that thread with PublishDenied(). Only the
// file system scopes may be checked this way.
bool is_granted_quiet(Environment* env,
PermissionScope permission,
std::string_view res = "") const;
// Publishes the diagnostics channel message for a denied check of `res`
void PublishDenied(Environment* env,
PermissionScope permission,
std::string_view res) const;
FORCE_INLINE bool enabled() const { return enabled_; }
FORCE_INLINE bool warning_only() const { return warning_only_; }
@@ -128,6 +140,11 @@ class Permission {
BaseObjectPtr<diagnostics_channel::Channel> GetOrCreateChannel(
Environment* env, PermissionScope scope) const;
// Publishes a denial (or a drop) of `res` to the scope's channel
void Publish(Environment* env,
PermissionScope scope,
std::string_view res,
bool dropped) const;
static constexpr size_t kPermissionCount =
static_cast<size_t>(PermissionScope::kPermissionsCount);
+23 -6
View File
@@ -36,16 +36,33 @@
#include <regex> // NOLINT(build/c++11)
#endif // _WIN32
#define CHAR_TEST(bits, name, expr) \
template <typename T> \
bool name(const T ch) { \
static_assert(sizeof(ch) >= (bits) / 8, \
"Character must be wider than " #bits " bits"); \
return (expr); \
#define CHAR_TEST(bits, name, expr) \
template <typename T> \
constexpr bool name(const T ch) { \
static_assert(sizeof(ch) >= (bits) / 8, \
"Character must be wider than " #bits " bits"); \
return (expr); \
}
namespace node {
// If a UTF-16 character is a high/leading surrogate.
CHAR_TEST(16, IsUnicodeLead, (ch & 0xFC00) == 0xD800)
// If a UTF-16 character is a low/trailing surrogate.
CHAR_TEST(16, IsUnicodeTrail, (ch & 0xFC00) == 0xDC00)
// If a UTF-16 character is a surrogate.
CHAR_TEST(16, IsUnicodeSurrogate, (ch & 0xF800) == 0xD800)
// If a UTF-16 surrogate is a low/trailing one.
CHAR_TEST(16, IsUnicodeSurrogateTrail, (ch & 0x400) != 0)
// The code point encoded by a valid surrogate pair.
constexpr uint32_t CombineSurrogates(uint32_t lead, uint32_t trail) {
return 0x10000 + ((lead - 0xD800) << 10) + (trail - 0xDC00);
}
template <typename T>
ListNode<T>::ListNode() : prev_(this), next_(this) {}
@@ -0,0 +1,144 @@
// An `exclude` callback can only run on the main thread. The async APIs
// still must not hold the event loop for the whole walk: the walk
// advances in short main-thread slices between which the loop turns.
import * as common from '../common/index.mjs';
import tmpdir from '../common/tmpdir.js';
import assert from 'node:assert';
import { glob, globSync } from 'node:fs';
import { glob as globIterator, mkdir, writeFile } from 'node:fs/promises';
import { dirname, join, sep } from 'node:path';
import { promisify } from 'node:util';
tmpdir.refresh();
const cwd = tmpdir.resolve('tree');
const files = ['a/b/c/d.txt', 'a/b/e.txt', 'a/f/g.txt', 'h/i.txt', 'j.txt'];
for (const file of files) {
await mkdir(join(cwd, dirname(file)), { recursive: true });
await writeFile(join(cwd, file), '');
}
const expected = files.map((file) => file.replaceAll('/', sep)).sort();
assert.deepStrictEqual(globSync('**/*.txt', { cwd }).sort(), expected);
// Long enough that the slice it runs in overruns its time budget, so the
// next directory is visited from a later loop turn.
function stall(ms) {
const end = performance.now() + ms;
while (performance.now() < end);
}
// Counts loop turns for as long as the walks run.
let turn = 0;
let walking = true;
(function tick() {
turn++;
if (walking) setImmediate(tick);
})();
// Records the loop turns its calls landed in.
function makeExclude() {
const turns = new Set();
const exclude = common.mustCallAtLeast((name) => {
assert.strictEqual(typeof name, 'string');
turns.add(turn);
stall(2);
return name === 'f';
}, 1);
return { exclude, turns };
}
const expectedExcluded = expected.filter((file) => !file.includes(`${sep}f${sep}`));
{
// Callback API
const { exclude, turns } = makeExclude();
await new Promise((resolve) => {
glob('**/*.txt', { cwd, exclude }, common.mustSucceed((results) => {
assert.deepStrictEqual(results.sort(), expectedExcluded);
resolve();
}));
// Nothing of the walk runs before the call returns.
assert.strictEqual(turns.size, 0);
});
assert.ok(turns.size >= 2, `exclude ran within ${turns.size} loop turn(s)`);
}
{
// Promisified callback API
const { exclude, turns } = makeExclude();
const pending = promisify(glob)('**/*.txt', { cwd, exclude });
assert.strictEqual(turns.size, 0);
assert.deepStrictEqual((await pending).sort(), expectedExcluded);
assert.ok(turns.size >= 2, `exclude ran within ${turns.size} loop turn(s)`);
}
{
// Async iterator
const { exclude, turns } = makeExclude();
const results = [];
for await (const entry of globIterator('**/*.txt', { cwd, exclude })) {
results.push(entry);
}
assert.deepStrictEqual(results.sort(), expectedExcluded);
assert.ok(turns.size >= 2, `exclude ran within ${turns.size} loop turn(s)`);
}
{
// Leaving the iterator early cancels a walk that is not over: the
// directory visited first (the last in listing order) holds more
// entries than one batch, so it fills the first batch while the other
// directories are still queued.
const many = tmpdir.resolve('many');
for (const dir of ['a', 'b', 'zz']) {
await mkdir(join(many, dir), { recursive: true });
await writeFile(join(many, dir, 'file.txt'), '');
}
for (let i = 0; i < 300; i++) {
await writeFile(join(many, 'zz', `${i}.txt`), '');
}
let calls = 0;
const exclude = () => {
calls++;
return false;
};
let seen = 0;
for await (const entry of globIterator('**/*.txt', { cwd: many, exclude })) {
assert.ok(entry.endsWith('.txt'), entry);
if (++seen === 2) break;
}
assert.strictEqual(seen, 2);
const callsAtBreak = calls;
await new Promise((resolve) => setTimeout(resolve, 20));
assert.strictEqual(calls, callsAtBreak);
}
{
// A callback that throws fails the walk with its error.
const error = new Error('exclude failed');
const exclude = common.mustCall(() => { throw error; });
glob('**/*.txt', { cwd, exclude }, common.mustCall((err, results) => {
assert.strictEqual(err, error);
assert.strictEqual(results, undefined);
}));
await assert.rejects(
promisify(glob)('**/*.txt', { cwd, exclude: common.mustCall(() => { throw error; }) }),
(err) => err === error);
await assert.rejects(
(async () => {
for await (const entry of globIterator('**/*.txt', { cwd, exclude: common.mustCall(() => { throw error; }) })) {
assert.fail(`unexpected result ${entry}`);
}
})(),
(err) => err === error);
}
{
// withFileTypes: the callback sees Dirents.
const { exclude: base, turns } = makeExclude();
const exclude = (dirent) => base(dirent.name);
const results = await promisify(glob)('**/*.txt', { cwd, exclude, withFileTypes: true });
assert.deepStrictEqual(
results.map((dirent) => join(dirent.parentPath, dirent.name).slice(cwd.length + 1)).sort(),
expectedExcluded);
assert.ok(turns.size >= 2, `exclude ran within ${turns.size} loop turn(s)`);
}
walking = false;
Loaded 100 of 108 files, more files were not shown because too many files have changed in this diff. Show more