diff --git a/.editorconfig b/.editorconfig
index 6474895..80e3ab4 100644
--- a/.editorconfig
+++ b/.editorconfig
@@ -1,74 +1,50 @@
-root = true
-
-[*]
-charset = utf-8
-indent_size = 4
-indent_style = space
-insert_final_newline = true
-trim_trailing_whitespace = true
-
-[*.{yml,props,targets,csproj}]
-indent_size = 2
-
-# IDE0059: Unnecessary assigment of a value
-dotnet_diagnostic.IDE0059.severity = none
-
-# IDE0060: Remove unused parameter
-dotnet_diagnostic.IDE0060.severity = none
-
-# IDE0079: Remove unnecessary suppression
-dotnet_remove_unnecessary_suppression_exclusions = category:ReSharper
-
-# IDE0079: Remove unnecessary suppression
-# dotnet_diagnostic.IDE0079.severity = none
-
-# CA2255: The 'ModuleInitializer' attribute should not be used in libraries
-dotnet_diagnostic.CA2255.severity = none
-
-# CS8600: Converting null literal or possible null value to non-nullable type.
-dotnet_diagnostic.CS8600.severity = error
-
-# CS8601: Possible null reference assignment.
-dotnet_diagnostic.CS8601.severity = error
-
-# CS8602: Dereference of a possibly null reference.
-dotnet_diagnostic.CS8602.severity = error
-
-# CS8603: Possible null reference return.
-dotnet_diagnostic.CS8603.severity = error
-
-# CS8604: Possible null reference argument.
-dotnet_diagnostic.CS8604.severity = error
-
-# CS8610: Nullability of reference types in type of parameter doesn't match overridden member.
-dotnet_diagnostic.CS8610.severity = error
-
-# CS8613: Nullability of reference types in return type doesn't match implicitly implemented member.
-dotnet_diagnostic.CS8613.severity = error
-
-# CS8614: Nullability of reference types in type of parameter doesn't match implicitly implemented member.
-dotnet_diagnostic.CS8614.severity = error
-
-# CS8618: Non-nullable field is uninitialized. Consider declaring as nullable.
-dotnet_diagnostic.CS8618.severity = error
-
-# CS8619: Nullability of reference types in value doesn't match target type.
-dotnet_diagnostic.CS8619.severity = error
-
-# CS8620: Argument cannot be used for parameter due to differences in the nullability of reference types.
-dotnet_diagnostic.CS8620.severity = error
-
-# CS8625: Cannot convert null literal to non-nullable reference type.
-dotnet_diagnostic.CS8625.severity = error
-
-# CS8634: The type cannot be used as type parameter in the generic type or method. Nullability of type argument doesn't match 'class' constraint.
-dotnet_diagnostic.CS8634.severity = error
-
-# CS8643: Nullability of reference types in explicit interface specifier doesn't match interface implemented by the type.
-dotnet_diagnostic.CS8643.severity = error
-
-# CS8653: A default expression introduces a null value for a type parameter.
-dotnet_diagnostic.CS8653.severity = error
-
-# CS8714: The type cannot be used as type parameter in the generic type or method. Nullability of type argument doesn't match 'notnull' constraint.
-dotnet_diagnostic.CS8714.severity = error
+root = true
+
+[*]
+charset = utf-8
+indent_size = 4
+indent_style = space
+trim_trailing_whitespace = true
+insert_final_newline = true
+
+[*.{yml,yaml}]
+indent_size = 2
+
+[*.{slnx,csproj,proj,props,targets}]
+indent_size = 2
+
+[*.cs]
+resharper_csharp_max_line_length = 160
+
+# Using directive options
+dotnet_sort_system_directives_first = true
+dotnet_separate_import_directive_groups = true
+
+# Prefer var whenever possible
+csharp_style_var_for_built_in_types = true:suggestion
+csharp_style_var_when_type_is_apparent = true:suggestion
+csharp_style_var_elsewhere = true:suggestion
+
+# Indentation preferences
+csharp_indent_labels = no_change
+
+# IDE0079: Remove unnecessary suppression
+dotnet_remove_unnecessary_suppression_exclusions = category:ReSharper
+
+[Ramstack.Globbing.Tests/**.cs]
+# CA1707: Identifiers should not contain underscores
+# Tests follow the Method_Condition_ExpectedResult naming convention.
+dotnet_diagnostic.CA1707.severity = none
+
+# CA1001: Types that own disposable fields should be disposable
+# Test fixtures release their resources in [OneTimeTearDown] methods, which the rule does not recognize.
+dotnet_diagnostic.CA1001.severity = none
+
+[benchmarks/**.cs]
+# CA1707: Identifiers should not contain underscores
+# Underscores keep the generated BenchmarkDotNet report readable.
+dotnet_diagnostic.CA1707.severity = none
+
+# CA1822: Mark members as static
+# BenchmarkDotNet discovers instance methods and properties.
+dotnet_diagnostic.CA1822.severity = none
diff --git a/.gitattributes b/.gitattributes
new file mode 100644
index 0000000..176a458
--- /dev/null
+++ b/.gitattributes
@@ -0,0 +1 @@
+* text=auto
diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml
index 4acfc0f..9fc1428 100644
--- a/.github/workflows/publish.yml
+++ b/.github/workflows/publish.yml
@@ -1,38 +1,38 @@
-name: Publish
-
-on:
- push:
- tags:
- - "[0-9]+.[0-9]+.[0-9]+"
- - "[0-9]+.[0-9]+.[0-9]+-[a-z]+.[0-9]+"
-
-permissions:
- contents: write
-
-jobs:
- publish:
- if: github.repository == 'rameel/ramstack.globbing'
- runs-on: ubuntu-latest
- steps:
- - name: Install .NET
- uses: actions/setup-dotnet@v4
- with:
- dotnet-version: 10.0.x
-
- - name: Checkout
- uses: actions/checkout@v4
-
- - name: Build
- run: dotnet build -c Release
-
- - name: Create NuGet Packages
- run: dotnet pack -c Release -o ./nuget --no-build
-
- - name: Publish NuGet Packages
- run: dotnet nuget push ./nuget/*.nupkg --api-key ${{secrets.NUGET_API_KEY}} --skip-duplicate -s https://api.nuget.org/v3/index.json
-
- - name: Create GitHub Release
- uses: softprops/action-gh-release@v2
- with:
- draft: true
- files: nuget/*
+name: Publish
+
+on:
+ push:
+ tags:
+ - "[0-9]+.[0-9]+.[0-9]+"
+ - "[0-9]+.[0-9]+.[0-9]+-[a-z]+.[0-9]+"
+
+permissions:
+ contents: write
+
+jobs:
+ publish:
+ if: github.repository == 'rameel/ramstack.globbing'
+ runs-on: ubuntu-latest
+ steps:
+ - name: Install .NET
+ uses: actions/setup-dotnet@v4
+ with:
+ dotnet-version: 10.0.x
+
+ - name: Checkout
+ uses: actions/checkout@v4
+
+ - name: Build
+ run: dotnet build -c Release
+
+ - name: Create NuGet Packages
+ run: dotnet pack -c Release -o ./nuget --no-build
+
+ - name: Publish NuGet Packages
+ run: dotnet nuget push ./nuget/*.nupkg --api-key ${{secrets.NUGET_API_KEY}} --skip-duplicate -s https://api.nuget.org/v3/index.json
+
+ - name: Create GitHub Release
+ uses: softprops/action-gh-release@v2
+ with:
+ draft: true
+ files: nuget/*
diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml
index b0ddf0e..20bd5c2 100644
--- a/.github/workflows/test.yml
+++ b/.github/workflows/test.yml
@@ -1,60 +1,60 @@
-name: Build & Test
-
-on:
- pull_request:
- branches: [main]
-
-jobs:
- build-and-test:
-
- name: build-and-test-${{ matrix.os }}
- runs-on: ${{ matrix.os }}
- strategy:
- matrix:
- os: [ubuntu-latest, ubuntu-24.04-arm, windows-latest]
-
- steps:
- - name: Setup .NET
- uses: actions/setup-dotnet@v4
- with:
- dotnet-version: |
- 6.x
- 7.x
- 8.x
- 9.x
- 10.x
-
- - name: Checkout
- uses: actions/checkout@v4
-
- - name: Build (Debug)
- run: dotnet build -c Debug
-
- - name: Build (Release)
- run: dotnet build -c Release
-
- - name: Test (Debug)
- run: dotnet test -c Debug --no-build
-
- - name: Test (Release)
- run: dotnet test -c Release --no-build
-
- - name: Test (Debug, AVX2=0)
- env:
- DOTNET_EnableAVX2: "0"
- run: dotnet test -c Debug --no-build
-
- - name: Test (Release, AVX2=0)
- env:
- DOTNET_EnableAVX2: "0"
- run: dotnet test -c Release --no-build
-
- - name: Test (Debug, HWIntrinsic=0)
- env:
- DOTNET_EnableHWIntrinsic: "0"
- run: dotnet test -c Debug --no-build
-
- - name: Test (Release, HWIntrinsic=0)
- env:
- DOTNET_EnableHWIntrinsic: "0"
- run: dotnet test -c Release --no-build
+name: Build & Test
+
+on:
+ pull_request:
+ branches: [main]
+
+jobs:
+ build-and-test:
+
+ name: build-and-test-${{ matrix.os }}
+ runs-on: ${{ matrix.os }}
+ strategy:
+ matrix:
+ os: [ubuntu-latest, ubuntu-24.04-arm, windows-latest]
+
+ steps:
+ - name: Setup .NET
+ uses: actions/setup-dotnet@v4
+ with:
+ dotnet-version: |
+ 6.x
+ 7.x
+ 8.x
+ 9.x
+ 10.x
+
+ - name: Checkout
+ uses: actions/checkout@v4
+
+ - name: Build (Debug)
+ run: dotnet build -c Debug
+
+ - name: Build (Release)
+ run: dotnet build -c Release
+
+ - name: Test (Debug)
+ run: dotnet test -c Debug --no-build
+
+ - name: Test (Release)
+ run: dotnet test -c Release --no-build
+
+ - name: Test (Debug, AVX2=0)
+ env:
+ DOTNET_EnableAVX2: "0"
+ run: dotnet test -c Debug --no-build
+
+ - name: Test (Release, AVX2=0)
+ env:
+ DOTNET_EnableAVX2: "0"
+ run: dotnet test -c Release --no-build
+
+ - name: Test (Debug, HWIntrinsic=0)
+ env:
+ DOTNET_EnableHWIntrinsic: "0"
+ run: dotnet test -c Debug --no-build
+
+ - name: Test (Release, HWIntrinsic=0)
+ env:
+ DOTNET_EnableHWIntrinsic: "0"
+ run: dotnet test -c Release --no-build
diff --git a/.gitignore b/.gitignore
index 294b8a6..66f2121 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1,40 +1,40 @@
-# Ignore thumbnails created by windows
-[Tt]humbs.db
-
-# Ignore files build by Visual Studio
-*.obj
-*.exe
-*.pdb
-*.user
-*.patch
-*.aps
-*.pch
-*.vspscc
-*_i.c
-*_p.c
-*.ncb
-*.suo
-*.tlb
-*.tlh
-*.bak
-*.cache
-*.ilk
-*.log
-*.lib
-*.sbr
-*.cs.ide
-[Dd]ebug*/
-[Rr]elease*/
-bin/
-obj/
-.vs/
-.vscode/
-*.ReSharper
-*.ReSharper.user
-[Tt]est[Rr]esult*
-
-# Ignore Rider/Idea files
-.idea/
-
-# Ignore BenchmarkDotNet artifacts
-BenchmarkDotNet.Artifacts
+# Ignore thumbnails created by windows
+[Tt]humbs.db
+
+# Ignore files build by Visual Studio
+*.obj
+*.exe
+*.pdb
+*.user
+*.patch
+*.aps
+*.pch
+*.vspscc
+*_i.c
+*_p.c
+*.ncb
+*.suo
+*.tlb
+*.tlh
+*.bak
+*.cache
+*.ilk
+*.log
+*.lib
+*.sbr
+*.cs.ide
+[Dd]ebug*/
+[Rr]elease*/
+bin/
+obj/
+.vs/
+.vscode/
+*.ReSharper
+*.ReSharper.user
+[Tt]est[Rr]esult*
+
+# Ignore Rider/Idea files
+.idea/
+
+# Ignore BenchmarkDotNet artifacts
+BenchmarkDotNet.Artifacts
diff --git a/Directory.Build.props b/Directory.Build.props
index bf61882..9e6caca 100644
--- a/Directory.Build.props
+++ b/Directory.Build.props
@@ -1,5 +1,19 @@
-
-
- true
-
-
+
+
+ true
+
+
+
+ $(NoWarn);CS0649
+ true
+
+
+
+ true
+ latest
+ Recommended
+ Default
+ true
+ true
+
+
diff --git a/LICENSE b/LICENSE
index 6666765..92e3431 100644
--- a/LICENSE
+++ b/LICENSE
@@ -1,9 +1,9 @@
-MIT License
-
-Copyright 2024 Rameel (https://github.com/rameel)
-
-Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
-
-The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
-
-THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+MIT License
+
+Copyright 2024 Rameel (https://github.com/rameel)
+
+Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
diff --git a/README.md b/README.md
index e74d6e0..3c1fb94 100644
--- a/README.md
+++ b/README.md
@@ -1,246 +1,246 @@
-# Ramstack.Globbing
-[](https://nuget.org/packages/Ramstack.Globbing)
-[](https://github.com/rameel/ramstack.globbing/blob/main/LICENSE)
-
-Fast and zero-allocation .NET globbing library for matching file paths using [glob patterns](https://en.wikipedia.org/wiki/Glob_(programming)).
-No external dependencies.
-
-## Getting Started
-
-To install the `Ramstack.Globbing` [NuGet package](https://www.nuget.org/packages/Ramstack.Globbing) to your project, run the following command:
-```console
-dotnet add package Ramstack.Globbing
-```
-
-## Usage
-
-```csharp
-bool result = Matcher.IsMatch("wiki/section-1/start.md", "wiki/**/*.md");
-```
-The `IsMatch` method attempts to match the specified path against the provided wildcard pattern.
-
-Matching is **case-sensitive**.
-
-`Matcher.IsMatch` compares path strings as-is and treats both `path` and `pattern` as **relative paths** in the same logical namespace.
-Absolute or rooted-looking strings are not handled specially: leading and trailing separators are ignored, so they are matched the same way as relative paths.
-
-The `.` and `..` segments have no special meaning and are matched as ordinary path segments.
-Parent-directory navigation is not supported.
-
-Matching APIs are **thread-safe** and can be used concurrently from multiple threads.
-
-By default, the system's default path separators are used. You can override this behavior by specifying one of the following flags:
-
-| Name | Description |
-|---------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
-| Auto | Automatically determines whether to treat backslashes (`\`) as escape sequences or path separators based on the platform's separator convention. |
-| Windows | Treats backslashes (`\`) as path separators instead of escape sequences.
Provides behavior consistent with Windows-style paths.
Both backslashes (`\`) and forward slashes (`/`) are considered as path separators in this mode. |
-| Unix | Treats backslashes (`\`) as escape sequences, allowing for special character escaping.
Provides behavior consistent with Unix-style paths. |
-
-Example with a specific flag:
-```csharp
-bool result = Matcher.IsMatch("wiki/section-1/start.md", @"wiki\**\*.md", MatchFlags.Windows);
-```
-
-## Patterns
-From [Wikipedia](https://en.wikipedia.org/wiki/Glob_(programming)#Syntax)
-
-| Pattern | Description | Example | Matches | Does not match |
-|---------|------------------------------------------------------------------------------|--------------|----------------------------------------------------------|---------------------------------------|
-| * | matches any number of any characters including none | Law* | Law, Laws, or Lawyer | GrokLaw, La, Law/foo or aw |
-| | | \*Law\* | Law, GrokLaw, or Lawyer. | La, or aw |
-| ? | matches any single character | ?at | Cat, cat, Bat or bat | at |
-| [abc] | matches one character given in the bracket | [CB]at | Cat or Bat | cat, bat or CBat |
-| [a-z] | matches one character from the (locale-dependent) range given in the bracket | Letter[0-9] | Letter0, Letter1, Letter2 up to Letter9 | Letters, Letter or Letter10 |
-| [!abc] | matches one character that is not given in the bracket | [!C]at | Bat, bat, or cat | Cat |
-| [!a-z] | matches one character that is not from the range given in the bracket | Letter[!3-5] | Letter1, Letter2, Letter6 up to Letter9 and Letterx etc. | Letter3, Letter4, Letter5 or Letterxx |
-
-### Pattern-specific for directories
-
-| Pattern | Description | Example | Matches | Does not match |
-|---------|-----------------------------------------------------|---------|--------------------------------|----------------|
-| ** | matches any number of path segments including none | **/Law | dir1/dir2/Law, dir1/Law or Law | dir1/La |
-
-### Brace patterns
-
-Brace patterns allow for matching multiple alternatives in a single pattern. Here are some key features:
-
-| Pattern | Description | Example | Matches | Does not match |
-|----------------|------------------------------------------|---------------------|-------------------------------------------------|----------------|
-| {a,b,c} | matches any of the comma-separated terms | file.{jpg,png} | file.jpg, file.png | file.gif |
-| {src,test{s,}} | supports nested brace patterns | {src,test{s,}}/*.cs | src/main.cs, tests/unit.cs, test/integration.cs | doc/readme.cs |
-| {main,,test} | supports empty alternatives | {main,,test}1.txt | main1.txt, test1.txt, 1.txt | file1.txt |
-| {[sS]rc,test*} | supports full glob pattern within braces | {[sS]rc,test*}/*.cs | src/app.cs, Src/main.cs, testing/script.cs | lib/util.cs |
-
-* Empty alternatives are valid, e.g., `{src,test,}` will also match paths without the listed prefixes.
-* Brace patterns can be nested, allowing for complex matching scenarios.
-* Full glob patterns can be used within braces, providing powerful and flexible matching capabilities.
-
-## Escaping characters
-
-The meta characters `?`, `*`, `[`, `\` can be escaped by using the `[]`, which means *match one character listed in the bracket*.
-* `[[]` matches the literal `[`
-* `[*]` matches the literal `*`
-
-This works when using any `MatchFlags` (`Windows` or `Unix`).
-When using `MatchFlags.Unix`, an additional escape character (`\`) is available:
-* `\[` matches the literal `[`
-* `\*` matches the literal `*`
-
-## Notes
-* Leading and trailing path separators are ignored.
-* Consecutive path separators are counted as one separator.
-* Matching is case-sensitive.
-* `Matcher.IsMatch` treats both `path` and `pattern` as relative paths. Absolute or rooted-looking strings are not handled specially.
-* The `.` and `..` segments are treated as ordinary path segments; parent-directory navigation is not supported.
-
-### Special cases
-* At the root level, an empty path segment is valid, which can be represented by patterns like "*".
-* At any deeper level, an empty segment indicates that a required directory or file is missing,
- making the path invalid for patterns expecting something at that level.
-
-| Pattern | Matches | Does not match | Explanation |
-|----------|-------------|----------------|-------------------------------------------------------------------------------------|
-| `*` | `foo`, `""` | | Matches everything, e.g. empty string |
-| `*/*` | `a/b`,`b/c` | `a`,`b`,`foo` | Requires at least one directory level, so `a` is not a match |
-| `*/{,b}` | `a/b` | `a`,`b`,`foo` | Requires a directory or a specific file `b` at the next level, so `a` doesn't match |
-
-:bulb: This means that the patterns `*/{}` and `*/{,}` cannot match any path due to the rule: an empty segment is not allowed beyond the root level.
-
-## Optimizations
-We use optimizations that prevent quadratic behavior in scenarios like the pattern `a*a*a*a*a*a*a*a*a*c`
-matching against the text `aaaaaaaaaaaaaaa...aaaa...aaa`.
-Similarly, for the `a/**/a/**/a/**/.../a/**/a/**/a/**/b` pattern matching against `a/a/a/a/.../a/.../a`.
-
-## File traversal
-
-The `Files` class provides functionality for traversing the file system and retrieving lists of files and directories
-based on specified glob patterns. This allows for flexible and efficient file and directory enumeration.
-
-```csharp
-using Ramstack.Globbing.Traversal;
-
-// List all *.cs files
-var files = Files.EnumerateFiles(@"/path/to/directory", "**/*.cs");
-foreach (var file in files)
- Console.WriteLine(file);
-
-// List all *.cs files except in tests directory
-var files = Files.EnumerateFiles(@"/path/to/directory", "**/*.cs", "tests");
-foreach (var file in files)
- Console.WriteLine(file);
-```
-Here, the first argument is the traversal root, while the glob patterns are matched against the **relative path from that root**.
-For example, `**/*.cs` matches `src/app.cs`, not `/path/to/directory/src/app.cs`.
-
-Support for multiple patterns is also included:
-
-```csharp
-using Ramstack.Globbing.Traversal;
-
-// List all *.cs files
-var files = Files.EnumerateFiles(@"/path/to/directory", ["src/**/*.cs", "lib/**/*.cs"], ["**/tests"]);
-foreach (var file in files)
- Console.WriteLine(file);
-```
-
-There are overloads that take a `TraversalOptions` allowing you to set additional options when traversing the file system,
-such as:
-- Filtering out specific attributes
-- Ignoring inaccessible files
-- Maximum recursion depth
-
-These methods are quite efficient in terms of speed, memory consumption, and GC pressure.
-Here are the benchmarking results for the [dotnet/runtime](https://github.com/dotnet/runtime) repository folder, which contained
-59194 files at the time of testing. The search was for `*.md` files:
-
-```
-BenchmarkDotNet v0.13.12, Windows 11 (10.0.22631.3880/23H2/2023Update/SunValley3)
-AMD Ryzen 9 5900X, 1 CPU, 24 logical and 12 physical cores
-.NET SDK 9.0.100-preview.6.24328.19
- [Host] : .NET 8.0.7 (8.0.724.31311), X64 RyuJIT AVX2
- Job-GMSEBO : .NET 8.0.7 (8.0.724.31311), X64 RyuJIT AVX2
-
-Runtime=.NET 8.0
-
-| Method | Mean | Error | StdDev | Gen0 | Gen1 | Allocated |
-|----------------------------------- |---------:|--------:|--------:|----------:|---------:|----------:|
-| >> Ramstack_Files_EnumerateFiles | 154.4 ms | 0.67 ms | 0.59 ms | - | - | 2.33 MB |
-| Microsoft_Directory_EnumerateFiles | 149.1 ms | 0.74 ms | 0.66 ms | - | - | 2.33 MB |
-| Microsoft_FileSystemGlobbing | 176.6 ms | 1.16 ms | 1.08 ms | 2000.0000 | 333.3333 | 35.99 MB |
-```
-
-As you can see, the code is as fast as a direct search using `Directory.EnumerateFiles` and consumes the same amount of memory.
-This makes sense, since the implementation of `Files.EnumerateFiles` uses the same `FileSystemEnumerable` class.
-
-Also, corresponding extension methods added for `DirectoryInfo`, which also allow you to leverage
-the full power of glob patterns when searching for files.
-
-## Custom File System Support
-
-The `FileTreeEnumerable` class provides support for custom file systems with glob pattern matching capabilities.
-Here is an example of its usage:
-```csharp
-// --------------------------------------------------------------------
-// As an example, we'll use the existing DirectoryInfo/FileInfo classes
-
-var root = new DirectoryInfo(@"D:\Projects\dotnet.runtime");
-var enumeration = new FileTreeEnumerable(root)
-{
- Patterns = ["**/*.cs"],
- Excludes = ["**/{bin,obj}"],
- FileNameSelector = info => info.Name,
- ShouldRecursePredicate = info => info is DirectoryInfo,
- // The following predicate used to filter the files
- ShouldIncludePredicate = info => info is FileInfo,
- ChildrenSelector = info => ((DirectoryInfo)info).EnumerateFileSystemInfos(),
- // Returns the full path of the file
- ResultSelector = info => info.FullName
-};
-
-// Prints all csharp files
-foreach (string filePath in enumeration)
- Console.WriteLine(filePath);
-```
-`Patterns` and `Excludes` are evaluated against paths relative to the supplied root entry.
-
-### Asynchronous Enumeration
-The `FileTreeAsyncEnumerable` class provides similar functionality to `FileTreeEnumerable`,
-but supports asynchronous enumeration for remote file systems as an example.
-
-Here's an example of how to use `FileTreeAsyncEnumerable`:
-
-```csharp
-// ---------------------------------------------------
-// Assuming we have an IAsyncFileSystem implementation
-
-var root = cloudFS.GetDirectory(@"/projects/dotnet.runtime");
-var enumeration = new FileTreeAsyncEnumerable(root)
-{
- Patterns = ["**/*.cs"],
- Excludes = ["**/{bin,obj}"],
- FileNameSelector = entry => entry.Name,
- ShouldRecursePredicate = entry => entry is IDirectory,
- ShouldIncludePredicate = entry => entry is IFile,
- ChildrenSelector = (entry, token) => ((IDirectory)entry).GetFileEntriesAsync(token),
- ResultSelector = entry => entry.FullPath
-};
-
-// Prints all csharp files asynchronously
-await foreach (string filePath in enumeration)
- Console.WriteLine(filePath);
-```
-
-
-## Supported versions
-
-| | Version |
-|------|----------------|
-| .NET | 6, 7, 8, 9, 10 |
-
-## Contributions
-
-Bug reports and contributions are welcome.
-
-## License
-This package is released as open source under the **MIT License**. See the [LICENSE](LICENSE) file for more details.
+# Ramstack.Globbing
+[](https://nuget.org/packages/Ramstack.Globbing)
+[](https://github.com/rameel/ramstack.globbing/blob/main/LICENSE)
+
+Fast and zero-allocation .NET globbing library for matching file paths using [glob patterns](https://en.wikipedia.org/wiki/Glob_(programming)).
+No external dependencies.
+
+## Getting Started
+
+To install the `Ramstack.Globbing` [NuGet package](https://www.nuget.org/packages/Ramstack.Globbing) to your project, run the following command:
+```console
+dotnet add package Ramstack.Globbing
+```
+
+## Usage
+
+```csharp
+bool result = Matcher.IsMatch("wiki/section-1/start.md", "wiki/**/*.md");
+```
+The `IsMatch` method attempts to match the specified path against the provided wildcard pattern.
+
+Matching is **case-sensitive**.
+
+`Matcher.IsMatch` compares path strings as-is and treats both `path` and `pattern` as **relative paths** in the same logical namespace.
+Absolute or rooted-looking strings are not handled specially: leading and trailing separators are ignored, so they are matched the same way as relative paths.
+
+The `.` and `..` segments have no special meaning and are matched as ordinary path segments.
+Parent-directory navigation is not supported.
+
+Matching APIs are **thread-safe** and can be used concurrently from multiple threads.
+
+By default, the system's default path separators are used. You can override this behavior by specifying one of the following flags:
+
+| Name | Description |
+|---------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
+| Auto | Automatically determines whether to treat backslashes (`\`) as escape sequences or path separators based on the platform's separator convention. |
+| Windows | Treats backslashes (`\`) as path separators instead of escape sequences.
Provides behavior consistent with Windows-style paths.
Both backslashes (`\`) and forward slashes (`/`) are considered as path separators in this mode. |
+| Unix | Treats backslashes (`\`) as escape sequences, allowing for special character escaping.
Provides behavior consistent with Unix-style paths. |
+
+Example with a specific flag:
+```csharp
+bool result = Matcher.IsMatch("wiki/section-1/start.md", @"wiki\**\*.md", MatchFlags.Windows);
+```
+
+## Patterns
+From [Wikipedia](https://en.wikipedia.org/wiki/Glob_(programming)#Syntax)
+
+| Pattern | Description | Example | Matches | Does not match |
+|---------|------------------------------------------------------------------------------|--------------|----------------------------------------------------------|---------------------------------------|
+| * | matches any number of any characters including none | Law* | Law, Laws, or Lawyer | GrokLaw, La, Law/foo or aw |
+| | | \*Law\* | Law, GrokLaw, or Lawyer. | La, or aw |
+| ? | matches any single character | ?at | Cat, cat, Bat or bat | at |
+| [abc] | matches one character given in the bracket | [CB]at | Cat or Bat | cat, bat or CBat |
+| [a-z] | matches one character from the (locale-dependent) range given in the bracket | Letter[0-9] | Letter0, Letter1, Letter2 up to Letter9 | Letters, Letter or Letter10 |
+| [!abc] | matches one character that is not given in the bracket | [!C]at | Bat, bat, or cat | Cat |
+| [!a-z] | matches one character that is not from the range given in the bracket | Letter[!3-5] | Letter1, Letter2, Letter6 up to Letter9 and Letterx etc. | Letter3, Letter4, Letter5 or Letterxx |
+
+### Pattern-specific for directories
+
+| Pattern | Description | Example | Matches | Does not match |
+|---------|-----------------------------------------------------|---------|--------------------------------|----------------|
+| ** | matches any number of path segments including none | **/Law | dir1/dir2/Law, dir1/Law or Law | dir1/La |
+
+### Brace patterns
+
+Brace patterns allow for matching multiple alternatives in a single pattern. Here are some key features:
+
+| Pattern | Description | Example | Matches | Does not match |
+|----------------|------------------------------------------|---------------------|-------------------------------------------------|----------------|
+| {a,b,c} | matches any of the comma-separated terms | file.{jpg,png} | file.jpg, file.png | file.gif |
+| {src,test{s,}} | supports nested brace patterns | {src,test{s,}}/*.cs | src/main.cs, tests/unit.cs, test/integration.cs | doc/readme.cs |
+| {main,,test} | supports empty alternatives | {main,,test}1.txt | main1.txt, test1.txt, 1.txt | file1.txt |
+| {[sS]rc,test*} | supports full glob pattern within braces | {[sS]rc,test*}/*.cs | src/app.cs, Src/main.cs, testing/script.cs | lib/util.cs |
+
+* Empty alternatives are valid, e.g., `{src,test,}` will also match paths without the listed prefixes.
+* Brace patterns can be nested, allowing for complex matching scenarios.
+* Full glob patterns can be used within braces, providing powerful and flexible matching capabilities.
+
+## Escaping characters
+
+The meta characters `?`, `*`, `[`, `\` can be escaped by using the `[]`, which means *match one character listed in the bracket*.
+* `[[]` matches the literal `[`
+* `[*]` matches the literal `*`
+
+This works when using any `MatchFlags` (`Windows` or `Unix`).
+When using `MatchFlags.Unix`, an additional escape character (`\`) is available:
+* `\[` matches the literal `[`
+* `\*` matches the literal `*`
+
+## Notes
+* Leading and trailing path separators are ignored.
+* Consecutive path separators are counted as one separator.
+* Matching is case-sensitive.
+* `Matcher.IsMatch` treats both `path` and `pattern` as relative paths. Absolute or rooted-looking strings are not handled specially.
+* The `.` and `..` segments are treated as ordinary path segments; parent-directory navigation is not supported.
+
+### Special cases
+* At the root level, an empty path segment is valid, which can be represented by patterns like "*".
+* At any deeper level, an empty segment indicates that a required directory or file is missing,
+ making the path invalid for patterns expecting something at that level.
+
+| Pattern | Matches | Does not match | Explanation |
+|----------|-------------|----------------|-------------------------------------------------------------------------------------|
+| `*` | `foo`, `""` | | Matches everything, e.g. empty string |
+| `*/*` | `a/b`,`b/c` | `a`,`b`,`foo` | Requires at least one directory level, so `a` is not a match |
+| `*/{,b}` | `a/b` | `a`,`b`,`foo` | Requires a directory or a specific file `b` at the next level, so `a` doesn't match |
+
+:bulb: This means that the patterns `*/{}` and `*/{,}` cannot match any path due to the rule: an empty segment is not allowed beyond the root level.
+
+## Optimizations
+We use optimizations that prevent quadratic behavior in scenarios like the pattern `a*a*a*a*a*a*a*a*a*c`
+matching against the text `aaaaaaaaaaaaaaa...aaaa...aaa`.
+Similarly, for the `a/**/a/**/a/**/.../a/**/a/**/a/**/b` pattern matching against `a/a/a/a/.../a/.../a`.
+
+## File traversal
+
+The `Files` class provides functionality for traversing the file system and retrieving lists of files and directories
+based on specified glob patterns. This allows for flexible and efficient file and directory enumeration.
+
+```csharp
+using Ramstack.Globbing.Traversal;
+
+// List all *.cs files
+var files = Files.EnumerateFiles(@"/path/to/directory", "**/*.cs");
+foreach (var file in files)
+ Console.WriteLine(file);
+
+// List all *.cs files except in tests directory
+var files = Files.EnumerateFiles(@"/path/to/directory", "**/*.cs", "tests");
+foreach (var file in files)
+ Console.WriteLine(file);
+```
+Here, the first argument is the traversal root, while the glob patterns are matched against the **relative path from that root**.
+For example, `**/*.cs` matches `src/app.cs`, not `/path/to/directory/src/app.cs`.
+
+Support for multiple patterns is also included:
+
+```csharp
+using Ramstack.Globbing.Traversal;
+
+// List all *.cs files
+var files = Files.EnumerateFiles(@"/path/to/directory", ["src/**/*.cs", "lib/**/*.cs"], ["**/tests"]);
+foreach (var file in files)
+ Console.WriteLine(file);
+```
+
+There are overloads that take a `TraversalOptions` allowing you to set additional options when traversing the file system,
+such as:
+- Filtering out specific attributes
+- Ignoring inaccessible files
+- Maximum recursion depth
+
+These methods are quite efficient in terms of speed, memory consumption, and GC pressure.
+Here are the benchmarking results for the [dotnet/runtime](https://github.com/dotnet/runtime) repository folder, which contained
+59194 files at the time of testing. The search was for `*.md` files:
+
+```
+BenchmarkDotNet v0.13.12, Windows 11 (10.0.22631.3880/23H2/2023Update/SunValley3)
+AMD Ryzen 9 5900X, 1 CPU, 24 logical and 12 physical cores
+.NET SDK 9.0.100-preview.6.24328.19
+ [Host] : .NET 8.0.7 (8.0.724.31311), X64 RyuJIT AVX2
+ Job-GMSEBO : .NET 8.0.7 (8.0.724.31311), X64 RyuJIT AVX2
+
+Runtime=.NET 8.0
+
+| Method | Mean | Error | StdDev | Gen0 | Gen1 | Allocated |
+|----------------------------------- |---------:|--------:|--------:|----------:|---------:|----------:|
+| >> Ramstack_Files_EnumerateFiles | 154.4 ms | 0.67 ms | 0.59 ms | - | - | 2.33 MB |
+| Microsoft_Directory_EnumerateFiles | 149.1 ms | 0.74 ms | 0.66 ms | - | - | 2.33 MB |
+| Microsoft_FileSystemGlobbing | 176.6 ms | 1.16 ms | 1.08 ms | 2000.0000 | 333.3333 | 35.99 MB |
+```
+
+As you can see, the code is as fast as a direct search using `Directory.EnumerateFiles` and consumes the same amount of memory.
+This makes sense, since the implementation of `Files.EnumerateFiles` uses the same `FileSystemEnumerable` class.
+
+Also, corresponding extension methods added for `DirectoryInfo`, which also allow you to leverage
+the full power of glob patterns when searching for files.
+
+## Custom File System Support
+
+The `FileTreeEnumerable` class provides support for custom file systems with glob pattern matching capabilities.
+Here is an example of its usage:
+```csharp
+// --------------------------------------------------------------------
+// As an example, we'll use the existing DirectoryInfo/FileInfo classes
+
+var root = new DirectoryInfo(@"D:\Projects\dotnet.runtime");
+var enumeration = new FileTreeEnumerable(root)
+{
+ Patterns = ["**/*.cs"],
+ Excludes = ["**/{bin,obj}"],
+ FileNameSelector = info => info.Name,
+ ShouldRecursePredicate = info => info is DirectoryInfo,
+ // The following predicate used to filter the files
+ ShouldIncludePredicate = info => info is FileInfo,
+ ChildrenSelector = info => ((DirectoryInfo)info).EnumerateFileSystemInfos(),
+ // Returns the full path of the file
+ ResultSelector = info => info.FullName
+};
+
+// Prints all csharp files
+foreach (string filePath in enumeration)
+ Console.WriteLine(filePath);
+```
+`Patterns` and `Excludes` are evaluated against paths relative to the supplied root entry.
+
+### Asynchronous Enumeration
+The `FileTreeAsyncEnumerable` class provides similar functionality to `FileTreeEnumerable`,
+but supports asynchronous enumeration for remote file systems as an example.
+
+Here's an example of how to use `FileTreeAsyncEnumerable`:
+
+```csharp
+// ---------------------------------------------------
+// Assuming we have an IAsyncFileSystem implementation
+
+var root = cloudFS.GetDirectory(@"/projects/dotnet.runtime");
+var enumeration = new FileTreeAsyncEnumerable(root)
+{
+ Patterns = ["**/*.cs"],
+ Excludes = ["**/{bin,obj}"],
+ FileNameSelector = entry => entry.Name,
+ ShouldRecursePredicate = entry => entry is IDirectory,
+ ShouldIncludePredicate = entry => entry is IFile,
+ ChildrenSelector = (entry, token) => ((IDirectory)entry).GetFileEntriesAsync(token),
+ ResultSelector = entry => entry.FullPath
+};
+
+// Prints all csharp files asynchronously
+await foreach (string filePath in enumeration)
+ Console.WriteLine(filePath);
+```
+
+
+## Supported versions
+
+| | Version |
+|------|----------------|
+| .NET | 6, 7, 8, 9, 10 |
+
+## Contributions
+
+Bug reports and contributions are welcome.
+
+## License
+This package is released as open source under the **MIT License**. See the [LICENSE](LICENSE) file for more details.
diff --git a/Ramstack.Globbing.Tests/MatcherTests.cs b/Ramstack.Globbing.Tests/MatcherTests.cs
index 79e5d07..a3b7f66 100644
--- a/Ramstack.Globbing.Tests/MatcherTests.cs
+++ b/Ramstack.Globbing.Tests/MatcherTests.cs
@@ -1,494 +1,494 @@
-namespace Ramstack.Globbing;
-
-[TestFixture]
-public class MatcherTests
-{
- [TestCase("", "", ExpectedResult = true)]
- [TestCase("main.c", "main.c", ExpectedResult = true)]
- [TestCase("main.h", "main.c", ExpectedResult = false)]
- [TestCase("", "main.c", ExpectedResult = false)]
- [TestCase("main.c", "", ExpectedResult = false)]
-
- [TestCase("main.?", "main.c", ExpectedResult = true)]
- [TestCase("*.c", "main.c", ExpectedResult = true)]
- [TestCase("main.*", "main.c", ExpectedResult = true)]
- [TestCase("m*n.*", "main.c", ExpectedResult = true)]
- [TestCase("m*in.c*", "main.c", ExpectedResult = true)]
- [TestCase("*", "", ExpectedResult = true)]
-
- [TestCase("Law*", "Law", ExpectedResult = true)]
- [TestCase("Law*", "Laws", ExpectedResult = true)]
- [TestCase("Law*", "Lawyer", ExpectedResult = true)]
- [TestCase("Law*", "GrokLaw", ExpectedResult = false)]
- [TestCase("Law*", "La", ExpectedResult = false)]
- [TestCase("Law*", "aw", ExpectedResult = false)]
-
- [TestCase("*Law", "Law", ExpectedResult = true)]
- [TestCase("*Law", "GrokLaw", ExpectedResult = true)]
- [TestCase("*Law", "La", ExpectedResult = false)]
- [TestCase("*Law", "Grok", ExpectedResult = false)]
-
- [TestCase("*Law*", "Law", ExpectedResult = true)]
- [TestCase("*Law*", "Lawyer", ExpectedResult = true)]
- [TestCase("*Law*", "GrokLaw", ExpectedResult = true)]
- [TestCase("*Law*", "La", ExpectedResult = false)]
- [TestCase("*Law*", "aw", ExpectedResult = false)]
-
- [TestCase("main.{c}", "main.c", ExpectedResult = true)]
- [TestCase("main.{c}", "main.h", ExpectedResult = false)]
- [TestCase("main.{c,h}", "main.c", ExpectedResult = true)]
- [TestCase("main.{c,h}", "main.h", ExpectedResult = true)]
- [TestCase("main.{c,h}", "main.d", ExpectedResult = false)]
- [TestCase("main.{c,h}.bak", "main.c.bak", ExpectedResult = true)]
- [TestCase("main{.c,.h,}.bak", "main.h.bak", ExpectedResult = true)]
- [TestCase("main{.c,.h,}.bak", "main.bak", ExpectedResult = true)]
- [TestCase("main{.c,.h,}.bak", "main.c", ExpectedResult = false)]
- [TestCase("main{.c,.h,}.bak", "main.h", ExpectedResult = false)]
- [TestCase("main{.c,.h,}.bak", "main.d", ExpectedResult = false)]
- [TestCase("{{a,b},{c,d}}", "a", ExpectedResult = true)]
- [TestCase("{{a,b},{c,d}}", "b", ExpectedResult = true)]
- [TestCase("{{a,b},{c,d}}", "c", ExpectedResult = true)]
- [TestCase("{{a,b},{c,d}}", "d", ExpectedResult = true)]
- [TestCase("main.{{{cs},{h}}}", "main.cs", ExpectedResult = true)]
- [TestCase("main.{{{cs},{h}}}", "main.h", ExpectedResult = true)]
- [TestCase("main.{{{cs},{h}}}", "main.d", ExpectedResult = false)]
-
- [TestCase("main.{c,cp,cpp}", "main.c", ExpectedResult = true)]
- [TestCase("main.{c,cp,cpp}", "main.cp", ExpectedResult = true)]
- [TestCase("main.{c,cp,cpp}", "main.cpp", ExpectedResult = true)]
-
- [TestCase("m.{c,cp,cpp}.bak", "m.c.bak", ExpectedResult = true)]
- [TestCase("m.{c,cp,cpp}.bak", "m.cp.bak", ExpectedResult = true)]
- [TestCase("m.{c,cp,cpp}.bak", "m.cpp.bak", ExpectedResult = true)]
- [TestCase("m.{c,cp,cpp}.bak", "m.cpp", ExpectedResult = false)]
- [TestCase("m.{c,cp,cpp}.bak", "m.css.bak", ExpectedResult = false)]
-
- [TestCase("main{.c,.h,}", "main", ExpectedResult = true)]
- [TestCase("main{.c,.h,}", "main.c", ExpectedResult = true)]
- [TestCase("main{.c,.h,}", "main.h", ExpectedResult = true)]
- [TestCase("main{.c,.h,}", "main.d", ExpectedResult = false)]
-
- [TestCase("m{.c,.h,}.bak", "m.bak", ExpectedResult = true)]
- [TestCase("m{.c,.h,}.bak", "m.c.bak", ExpectedResult = true)]
- [TestCase("m{.c,.h,}.bak", "m.h.bak", ExpectedResult = true)]
- [TestCase("m{.c,.h,}.bak", "m.d.bak", ExpectedResult = false)]
- [TestCase("m{.c,.h,}.bak", "a.c.bak", ExpectedResult = false)]
- [TestCase("m{.c,.h,}.bak", "a.bak", ExpectedResult = false)]
- [TestCase("m{.c,.h,}.bak", "a.zip", ExpectedResult = false)]
-
- [TestCase("**", "", ExpectedResult = true)]
- [TestCase("***", "", ExpectedResult = true)]
- [TestCase("****", "", ExpectedResult = true)]
- [TestCase("{}", "", ExpectedResult = true)]
- [TestCase("{}{}", "", ExpectedResult = true)]
- [TestCase("{}{}{}", "", ExpectedResult = true)]
- [TestCase("*{}*{}*{}*{}", "", ExpectedResult = true)]
- [TestCase("*{}{}**{}{}**{}{}", "", ExpectedResult = true)]
- [TestCase("*{}**{}{}**", "", ExpectedResult = true)]
- [TestCase("{,}", "", ExpectedResult = true)]
- [TestCase("{,,,,,}", "", ExpectedResult = true)]
- [TestCase("{{{{},{},{},{}}}}", "", ExpectedResult = true)]
-
- [TestCase("a*", "a", ExpectedResult = true)]
- [TestCase("a**", "a", ExpectedResult = true)]
- [TestCase("a***", "a", ExpectedResult = true)]
- [TestCase("a****", "a", ExpectedResult = true)]
- [TestCase("a{}", "a", ExpectedResult = true)]
- [TestCase("a{}{}", "a", ExpectedResult = true)]
- [TestCase("a{}{}{}", "a", ExpectedResult = true)]
- [TestCase("a*{}*{}*{}*{}", "a", ExpectedResult = true)]
- [TestCase("a*{}{}**{}{}**{}{}", "a", ExpectedResult = true)]
- [TestCase("a*{}**{}{}**", "a", ExpectedResult = true)]
-
- [TestCase("a*b", "a", ExpectedResult = false)]
- [TestCase("a{}b", "a", ExpectedResult = false)]
- [TestCase("a{,}b", "a", ExpectedResult = false)]
- [TestCase("a{}}", "a", ExpectedResult = false)]
- [TestCase("*b", "", ExpectedResult = false)]
- [TestCase("{}b", "", ExpectedResult = false)]
- [TestCase("{,}b", "", ExpectedResult = false)]
- [TestCase("{}}", "", ExpectedResult = false)]
-
- [TestCase("a*", "ab", ExpectedResult = true)]
- [TestCase("a**", "ab", ExpectedResult = true)]
- [TestCase("a***", "ab", ExpectedResult = true)]
- [TestCase("a****", "ab", ExpectedResult = true)]
- [TestCase("a{}", "ab", ExpectedResult = false)]
- [TestCase("a{}{}", "ab", ExpectedResult = false)]
- [TestCase("a{}{}{}", "ab", ExpectedResult = false)]
- [TestCase("a{,b}{,c}{,d}", "a", ExpectedResult = true)]
- [TestCase("a{,b}{,c}{,d}", "ab", ExpectedResult = true)]
- [TestCase("a{,b}{,c}", "abc", ExpectedResult = true)]
- [TestCase("a{,b}{,c}{,d}", "abc", ExpectedResult = true)]
- [TestCase("a{,b}{,c}{,d}", "abd", ExpectedResult = true)]
- [TestCase("a{,b}{,c}", "ab", ExpectedResult = true)]
- [TestCase("a{,b}{,c}", "ac", ExpectedResult = true)]
- [TestCase("a{,b}{,c}", "ad", ExpectedResult = false)]
- [TestCase("a*{}*{}*{}*{}", "ab", ExpectedResult = true)]
- [TestCase("a*{}{}**{}{}**{}{}", "ab", ExpectedResult = true)]
- [TestCase("a*{}**{}{}**", "ab", ExpectedResult = true)]
- [TestCase("a*{}{}{b}", "ab", ExpectedResult = true)]
- [TestCase("{a}{b}{c}", "abc", ExpectedResult = true)]
-
- [TestCase("{,a}", "a", ExpectedResult = true)]
- [TestCase("{,,,,a}", "a", ExpectedResult = true)]
- [TestCase("{,,,,a}", "a", ExpectedResult = true)]
- [TestCase("{a,,,,}", "a", ExpectedResult = true)]
- [TestCase("{,a,}", "a", ExpectedResult = true)]
- [TestCase("{{},{},{},a}", "a", ExpectedResult = true)]
- [TestCase("{{},{},{,a}}", "a", ExpectedResult = true)]
- [TestCase("{{{}},{,{{,{,a}}}}}", "a", ExpectedResult = true)]
- [TestCase("{{{}},{,{{,{,a}}}}}", "b", ExpectedResult = false)]
- [TestCase("{,a}", "b", ExpectedResult = false)]
- [TestCase("{,,,,a}b", "ab", ExpectedResult = true)]
- [TestCase("{{},{},{,{,a}}}b", "ab", ExpectedResult = true)]
- [TestCase("{a}", "", ExpectedResult = false)]
- [TestCase("{a{}}", "", ExpectedResult = false)]
- [TestCase("t{a{}}", "t", ExpectedResult = false)]
-
- [TestCase("[a]", "", ExpectedResult = false)]
- [TestCase("main.[c]", "main.c", ExpectedResult = true)]
- [TestCase("main.[c]", "main.d", ExpectedResult = false)]
- [TestCase("main.[dch]", "main.c", ExpectedResult = true)]
- [TestCase("main.[dch]", "main.d", ExpectedResult = true)]
- [TestCase("main.[dch]", "main.h", ExpectedResult = true)]
- [TestCase("main.[c-d]", "main.c", ExpectedResult = true)]
- [TestCase("main.[c-d]", "main.d", ExpectedResult = true)]
- [TestCase("main.[c-dh]", "main.c", ExpectedResult = true)]
- [TestCase("main.[c-dh]", "main.d", ExpectedResult = true)]
- [TestCase("main.[c-dh]", "main.h", ExpectedResult = true)]
- [TestCase("main.[a-z0-9]", "main.h", ExpectedResult = true)]
- [TestCase("main.[a-z0-9]", "main.a", ExpectedResult = true)]
- [TestCase("main.[a-z0-9]", "main.z", ExpectedResult = true)]
- [TestCase("main.[a-z0-9]", "main.0", ExpectedResult = true)]
- [TestCase("main.[a-z0-9]", "main.5", ExpectedResult = true)]
- [TestCase("main.[a-z0-9]", "main.9", ExpectedResult = true)]
- [TestCase("main.[A-Fa-f0-9]", "main.C", ExpectedResult = true)]
- [TestCase("main.[A-Fa-f0-9]", "main.c", ExpectedResult = true)]
- [TestCase("main.[A-Fa-f0-9]", "main.5", ExpectedResult = true)]
- [TestCase("main.[A-Fa-f0-9]", "main.-", ExpectedResult = false)]
- [TestCase("main.[A-Fa-f0-9]", "main.z", ExpectedResult = false)]
- [TestCase("main.[A-Fa-f0-9]", "main.Z", ExpectedResult = false)]
- [TestCase("main.[A-Fa-f0-9]", "main.@", ExpectedResult = false)]
- [TestCase("main.[A-Fa-f0-9-]", "main.-", ExpectedResult = true)]
- [TestCase("[a-c-e-g]", "-", ExpectedResult = true)]
- [TestCase("[a-c-e-g]", "a", ExpectedResult = true)]
- [TestCase("[a-c-e-g]", "b", ExpectedResult = true)]
- [TestCase("[a-c-e-g]", "c", ExpectedResult = true)]
- [TestCase("[a-c-e-g]", "e", ExpectedResult = true)]
- [TestCase("[a-c-e-g]", "f", ExpectedResult = true)]
- [TestCase("[a-c-e-g]", "g", ExpectedResult = true)]
- [TestCase("[a-c-e-g]", "d", ExpectedResult = false)]
- [TestCase("[]0-346-8[]", "0", ExpectedResult = true)]
- [TestCase("[]0-346-8[]", "2", ExpectedResult = true)]
- [TestCase("[]0-346-8[]", "3", ExpectedResult = true)]
- [TestCase("[]0-346-8[]", "4", ExpectedResult = true)]
- [TestCase("[]0-346-8[]", "5", ExpectedResult = false)]
- [TestCase("[]0-346-8[]", "6", ExpectedResult = true)]
- [TestCase("[]0-346-8[]", "7", ExpectedResult = true)]
- [TestCase("[]0-346-8[]", "8", ExpectedResult = true)]
- [TestCase("[]0-346-8[]", "]", ExpectedResult = true)]
- [TestCase("[]0-346-8[]", "[", ExpectedResult = true)]
-
- [TestCase("[!0-9]", "a", ExpectedResult = true)]
- [TestCase("[!0-9]", "Z", ExpectedResult = true)]
- [TestCase("[!0-9]", "@", ExpectedResult = true)]
- [TestCase("[!0-9]", "-", ExpectedResult = true)]
- [TestCase("[!0-9]", "0", ExpectedResult = false)]
- [TestCase("[!0-9]", "5", ExpectedResult = false)]
- [TestCase("[!0-9]", "9", ExpectedResult = false)]
- [TestCase("[!a-z0-9]", "0", ExpectedResult = false)]
- [TestCase("[!a-z0-9]", "9", ExpectedResult = false)]
- [TestCase("[!a-z0-9]", "a", ExpectedResult = false)]
- [TestCase("[!a-z0-9]", "f", ExpectedResult = false)]
- [TestCase("[!a-z0-9]", "A", ExpectedResult = true)]
- [TestCase("[!a-z0-9]", "-", ExpectedResult = true)]
- [TestCase("[!a-z0-9-]", "-", ExpectedResult = false)]
-
- [TestCase("[CB]at", "Cat", ExpectedResult = true)]
- [TestCase("[CB]at", "Bat", ExpectedResult = true)]
- [TestCase("[CB]at", "CBat", ExpectedResult = false)]
-
- [TestCase("[][!]", "]", ExpectedResult = true)]
- [TestCase("[][!]", "[", ExpectedResult = true)]
- [TestCase("[][!]", "!", ExpectedResult = true)]
- [TestCase("[][!]", "5", ExpectedResult = false)]
- [TestCase("[", "[", ExpectedResult = false)]
- [TestCase("[a", "[a", ExpectedResult = false)]
- [TestCase("]", "]", ExpectedResult = true)]
- [TestCase("a]", "a]", ExpectedResult = true)]
- [TestCase("[?]", "?", ExpectedResult = true)]
- [TestCase("[*]", "*", ExpectedResult = true)]
- [TestCase("[{]", "{", ExpectedResult = true)]
- [TestCase("[}]", "}", ExpectedResult = true)]
-
- [TestCase("[--0]", "-", ExpectedResult = true)]
- [TestCase("[--0]", ".", ExpectedResult = true)]
- [TestCase("[--0]", "0", ExpectedResult = true)]
- [TestCase("[--0]", "/", ExpectedResult = false)]
- [TestCase("[--0]", "a", ExpectedResult = false)]
- [TestCase("[--0]", "1", ExpectedResult = false)]
-
- [TestCase("[!]a-]", "b", ExpectedResult = true)]
- [TestCase("[!]a-]", "]", ExpectedResult = false)]
- [TestCase("[!]a-]", "a", ExpectedResult = false)]
- [TestCase("[!]a-]", "-", ExpectedResult = false)]
-
- [TestCase(@"[[?*\]", "[", ExpectedResult = true)]
- [TestCase(@"[[?*\]", "?", ExpectedResult = true)]
- [TestCase(@"[[?*\]", "*", ExpectedResult = true)]
- [TestCase(@"[[?*\]", "\\", ExpectedResult = true)]
- [TestCase(@"[[?*\]", "a", ExpectedResult = false)]
- [TestCase(@"[[?*\]", "0", ExpectedResult = false)]
-
- [TestCase(@"\*", "*", ExpectedResult = true)]
- [TestCase(@"main.\*", "main.*", ExpectedResult = true)]
- [TestCase(@"\main.c", "main.c", ExpectedResult = true)]
- [TestCase(@"\[", "[", ExpectedResult = true)]
- [TestCase(@"\[\?\{name]", "[?{name]", ExpectedResult = true)]
- [TestCase(@"\a\b\c\d\e\f", "abcdef", ExpectedResult = true)]
- [TestCase(@"\*", "a", ExpectedResult = false)]
- [TestCase(@"\?", "?", ExpectedResult = true)]
- [TestCase(@"\?", "a", ExpectedResult = false)]
- [TestCase(@"main.\?", "main.c", ExpectedResult = false)]
- [TestCase(@"*\?", "main?", ExpectedResult = true)]
- [TestCase(@"*\?", "main", ExpectedResult = false)]
- [TestCase(@"a\", @"a\", ExpectedResult = false)]
-
- [TestCase("[Зз]емля", "Земля", ExpectedResult = true)]
- [TestCase("[Зз]емля", "земля", ExpectedResult = true)]
-
- [TestCase("*.[a-z]", "main.c", ExpectedResult = true)]
- [TestCase("*.{[a-z]}", "main.c", ExpectedResult = true)]
- [TestCase("*.{[a-z],p?[a-z]}", "main.c", ExpectedResult = true)]
- [TestCase("*.{[a-z],p?[a-z]}", "main.pdb", ExpectedResult = true)]
- [TestCase("*.{[a-z],p?[a-z]}", "main.pdf", ExpectedResult = true)]
- [TestCase("*.{[a-z],p?[a-z]}", "main.pas", ExpectedResult = true)]
- [TestCase("*.{[a-z],p?{[a-z]}}", "main.pas", ExpectedResult = true)]
- [TestCase("*.{{[a-z]},p?[a-z]}", "main.c", ExpectedResult = true)]
- [TestCase("*.{{[a-z]},p?[a-z]}", "main.pas", ExpectedResult = true)]
-
- [TestCase("{", "{", ExpectedResult = false)]
- [TestCase("{a", "{a", ExpectedResult = false)]
- [TestCase("}", "}", ExpectedResult = true)]
- [TestCase("}a", "}a", ExpectedResult = true)]
-
- [TestCase("main.{a,*}", "main.a", ExpectedResult = true)]
- [TestCase("main.{a,*}", "main.c", ExpectedResult = true)]
- [TestCase("main.{a,*}", "main.cpp", ExpectedResult = true)]
-
- [TestCase("main.{a,*}.bak", "main.a.bak", ExpectedResult = false)]
- [TestCase("main.{a,*}.bak", "main.c.bak", ExpectedResult = false)]
- [TestCase("*{,cs}", "main.cs", ExpectedResult = true)]
- [TestCase("*{,cs}", "main", ExpectedResult = true)]
- [TestCase("*{,cs}", "main.c", ExpectedResult = true)]
- [TestCase("*{,cs}", "main.cpp", ExpectedResult = true)]
- [TestCase("*{,*}", "main.bak", ExpectedResult = true)]
- [TestCase("{*.cs,*.txt}", "main.cs", ExpectedResult = true)]
- [TestCase("{*.cs,*.txt}", "main.txt", ExpectedResult = true)]
- [TestCase("{*.cs,*.txt}", "main.c", ExpectedResult = false)]
- [TestCase("{*a,b}", "b", ExpectedResult = true)]
- [TestCase("main.{*a,b}", "main.b", ExpectedResult = true)]
-
- [TestCase("*.{[a-z],p?[a-z]}", "main.0", ExpectedResult = false)]
- [TestCase("*.{[a-z],p?[a-z]}", "main.pd", ExpectedResult = false)]
- [TestCase("*.{[a-z],p?[a-z]}", "main.exe", ExpectedResult = false)]
- [TestCase("*.[a-z]", "main.0", ExpectedResult = false)]
- [TestCase("*.{[a-z]}", "main.0", ExpectedResult = false)]
-
- [TestCase("a*", "aaaaaa", ExpectedResult = true)]
- [TestCase("a**", "aaaaaa", ExpectedResult = true)]
- [TestCase("a***", "aaaaaa", ExpectedResult = true)]
- [TestCase("abc*", "abcabc", ExpectedResult = true)]
- [TestCase("*abc", "abcabc", ExpectedResult = true)]
- [TestCase("*abc*", "abcabc", ExpectedResult = true)]
- [TestCase("**abc*", "abcabc", ExpectedResult = true)]
- [TestCase("*ac*ae*ag*", "abacadaeafag", ExpectedResult = true)]
- [TestCase("*ab*[cd]*e*f*g*", "abacadaeafag", ExpectedResult = true)]
- public bool IsMatchSegment(string pattern, string value) =>
- Matcher.IsMatch(value, pattern, MatchFlags.Unix);
-
- [TestCase("/dir", "/dir", ExpectedResult = true)]
- [TestCase("dir", "dir", ExpectedResult = true)]
- [TestCase("/dir", "dir/", ExpectedResult = true)]
- [TestCase("dir/", "/dir", ExpectedResult = true)]
- [TestCase("dir/", "dir/", ExpectedResult = true)]
- [TestCase("dir", "/dir/", ExpectedResult = true)]
-
- [TestCase("dir1/dir2/file.cs", "/dir1/dir2/file.cs", ExpectedResult = true)]
- [TestCase("dir1/dir2/file.cs", "/dir1/dir2/file.ps", ExpectedResult = false)]
- [TestCase("dir1/*/file.cs", "/dir1/dir2/file.cs", ExpectedResult = true)]
- [TestCase("*/*/*.{cs,ps,c}", "/dir1/dir2/file.ps", ExpectedResult = true)]
- [TestCase("*/*/*.{cs,ps,c}", "/dir1/dir2/file.js", ExpectedResult = false)]
- [TestCase("dir1/{d2,d3}/file.cs", "/dir1/d2/file.cs", ExpectedResult = true)]
- [TestCase("dir1/{d2,d3}/file.cs", "/dir1/d3/file.cs", ExpectedResult = true)]
- [TestCase("dir1/{d2,d3}/file.cs", "/dir1/d4/file.cs", ExpectedResult = false)]
- [TestCase("*/*/*", "/dir1/dir2/file", ExpectedResult = true)]
- [TestCase("*/*/*", "/d1/d2/d3/d4", ExpectedResult = false)]
- [TestCase("a/b/c", "/a///b///c//", ExpectedResult = true)]
- [TestCase("a/b/c", "/a///b///c////", ExpectedResult = true)]
- [TestCase("///a////b/c////", "/a///b///c////", ExpectedResult = true)]
-
- [TestCase("*/*", "a/b", ExpectedResult = true)]
- [TestCase("*/*", "a", ExpectedResult = false)]
- [TestCase("*/*", "a/", ExpectedResult = false)]
- [TestCase("*/*/", "a", ExpectedResult = false)]
- [TestCase("*/*/{,}", "a/b", ExpectedResult = false)]
- [TestCase("*/*/*", "", ExpectedResult = false)]
- [TestCase("*/*/*", "a", ExpectedResult = false)]
- [TestCase("*/*/*", "a/b", ExpectedResult = false)]
- [TestCase("*/*/*", "a/b/c", ExpectedResult = true)]
- [TestCase("a/b/c", "", ExpectedResult = false)]
- [TestCase("a/b/c", "a", ExpectedResult = false)]
- [TestCase("a/b/c", "a/b", ExpectedResult = false)]
- [TestCase("a/b/c", "a/b/c", ExpectedResult = true)]
-
- [TestCase("*/{,b}", "a/b", ExpectedResult = true)]
- [TestCase("*/{,b}", "a", ExpectedResult = false)]
- [TestCase("*/{,b}", "a/", ExpectedResult = false)]
- [TestCase("*/{,}", "a", ExpectedResult = false)]
- [TestCase("*/{,}", "a/", ExpectedResult = false)]
- [TestCase("*/{,}", "a/b", ExpectedResult = false)]
- [TestCase("*/{}", "a", ExpectedResult = false)]
- [TestCase("*/{}", "a/", ExpectedResult = false)]
- [TestCase("*/{}", "a/b", ExpectedResult = false)]
-
- [TestCase("", "", ExpectedResult = true)]
- [TestCase("", "a", ExpectedResult = false)]
- [TestCase("/", "a", ExpectedResult = false)]
-
- [TestCase("*", "", ExpectedResult = true)]
- [TestCase("**", "", ExpectedResult = true)]
- [TestCase("a/b/**", "", ExpectedResult = false)]
- [TestCase("a/b/**", "a", ExpectedResult = false)]
- [TestCase("a/b/**", "a/b", ExpectedResult = true)]
- [TestCase("a/b/**", "a/b/c", ExpectedResult = true)]
- [TestCase("a/b/**", "a/b/c/d", ExpectedResult = true)]
- [TestCase("a/b/**/*", "", ExpectedResult = false)]
- [TestCase("a/b/**/*", "a", ExpectedResult = false)]
- [TestCase("a/b/**/*", "a/b", ExpectedResult = true)]
- [TestCase("a/b/**/*", "a/b/c", ExpectedResult = true)]
- [TestCase("a/b/**/*", "a/b/c/d", ExpectedResult = true)]
- [TestCase("**/*", "", ExpectedResult = true)]
- [TestCase("a/**/c/d", "a/b/c/d", ExpectedResult = true)]
- [TestCase("a/**/c/d", "a/c/d", ExpectedResult = true)]
- [TestCase("a/**/c/d", "a/b/e/f/c/d", ExpectedResult = true)]
- [TestCase("a/**/c/d", "a/b/c/d/e", ExpectedResult = false)]
- [TestCase("a/**/c/**/d", "a/b/c/d", ExpectedResult = true)]
- [TestCase("a/**/c/**/d", "a/c/d", ExpectedResult = true)]
- [TestCase("a/**/c/**/d", "a/b/e/f/c/g/c/d", ExpectedResult = true)]
- [TestCase("a/**/c/**/d", "a/c/d/a/c/d/a/c/d/", ExpectedResult = true)]
- [TestCase("a/**/c/**/d", "a/c/d/a/c/d/a/c/f/", ExpectedResult = false)]
- [TestCase("a/**/c/**/d", "a/c/d/a/c/d/a/c/d/f/", ExpectedResult = false)]
- [TestCase("a/**/c/**/d", "a/c/d/e", ExpectedResult = false)]
- [TestCase("a/**/c/**/d", "b/c/d/e", ExpectedResult = false)]
- [TestCase("a/**/c/**/d", "a/c/c/f", ExpectedResult = false)]
- [TestCase("a/**/c/**/d", "a/c/e", ExpectedResult = false)]
- [TestCase("a/**/c/**/d", "a/e/c", ExpectedResult = false)]
- [TestCase("**", "a", ExpectedResult = true)]
- [TestCase("**", "a/b/c", ExpectedResult = true)]
- [TestCase("**/*", "a", ExpectedResult = true)]
- [TestCase("**/*", "a/b/c", ExpectedResult = true)]
-
- [TestCase("{src,test{s,}}/*.cs", "src/main.cs", ExpectedResult = true)]
- [TestCase("{src,test{s,}}/*.cs", "test/main.cs", ExpectedResult = true)]
- [TestCase("{src,test{s,}}/*.cs", "tests/main.cs", ExpectedResult = true)]
- [TestCase("{src,test{s,}}/*.cs", "test2/main.cs", ExpectedResult = false)]
- [TestCase("{src,test{s,}}/*.cs", "tests/main.c", ExpectedResult = false)]
- [TestCase("{src,,test}/file.txt", "src/file.txt", ExpectedResult = true)]
- [TestCase("{src,,test}/file.txt", "src/file.txt", ExpectedResult = true)]
- [TestCase("{a,,b}1/file.txt", "a1/file.txt", ExpectedResult = true)]
- [TestCase("{a,,b}1/file.txt", "b1/file.txt", ExpectedResult = true)]
- [TestCase("{a,,b}1/file.txt", "1/file.txt", ExpectedResult = true)]
- [TestCase("{a,,b}1/file.txt", "a/file.txt", ExpectedResult = false)]
- [TestCase("{a,,b}1/file.txt", "a1/readme.txt", ExpectedResult = false)]
- [TestCase("{a,,b}1/file.txt", "doc/file.txt", ExpectedResult = false)]
- [TestCase("{[sS]rc,test*}/*.cs", "src/app.cs", ExpectedResult = true)]
- [TestCase("{[sS]rc,test*}/*.cs", "src/app.cs", ExpectedResult = true)]
- [TestCase("{[sS]rc,test*}/*.cs", "Src/app.cs", ExpectedResult = true)]
- [TestCase("{[sS]rc,test*}/*.cs", "test/app.cs", ExpectedResult = true)]
- [TestCase("{[sS]rc,test*}/*.cs", "tests/app.cs", ExpectedResult = true)]
- [TestCase("{[sS]rc,test*}/*.cs", "unittest/app.cs", ExpectedResult = false)]
- [TestCase("{[sS]rc,test*}/*.cs", "test/app.cpp", ExpectedResult = false)]
- public bool IsMatch(string pattern, string path) =>
- Matcher.IsMatch(path, pattern, MatchFlags.Unix);
-
- [TestCase(@"\a\b\*\d\e", "ab*de", ExpectedResult = true)]
- [TestCase(@"\a\b\*\d\e", "abcde", ExpectedResult = false)]
- public bool IsMatch_Unix(string pattern, string path) =>
- Matcher.IsMatch(path, pattern, MatchFlags.Unix);
-
- [TestCase(@"\a\b\*\d\e", @"\a\b\c\d\e", ExpectedResult = true)]
- [TestCase(@"\a\b\*\d\e", @"/a/b\c/d/e", ExpectedResult = true)]
- [TestCase(@"/a/b/*\d/e", @"\a\b/c\d\e\", ExpectedResult = true)]
- [TestCase(@"\a\b\*\d\e", @"\a\b\c\d\e\f", ExpectedResult = false)]
- public bool IsMatch_Windows(string pattern, string path) =>
- Matcher.IsMatch(path, pattern, MatchFlags.Windows);
-
- [TestCase("", ExpectedResult = true)]
- [TestCase("*", ExpectedResult = true)]
- [TestCase("**", ExpectedResult = true)]
- [TestCase("{,a}", ExpectedResult = true)]
- [TestCase("abc", ExpectedResult = false)]
- [TestCase("*.cs", ExpectedResult = false)]
- [TestCase("*/*", ExpectedResult = false)]
- [TestCase("{a", ExpectedResult = false)]
- public bool IsMatch_EmptySpanPath(string pattern) =>
- // ReadOnlySpan.Empty is backed by a null reference
- Matcher.IsMatch(ReadOnlySpan.Empty, pattern.AsSpan(), MatchFlags.Unix);
-
- [TestCase("[a-b]", 4, "a")]
- [TestCase("[a-b]", 4, "b")]
- [TestCase("[!a]", 2, "a")]
- [TestCase("[a-]", 3, "a")]
- [TestCase(@"a\?", 2, "ax")]
- [TestCase(@"a\b", 2, "ab")]
- public void IsMatch_PatternSlice_IgnoresCharsBeyondSlice(string text, int length, string path)
- {
- var expected = Matcher.IsMatch(path, text[..length], MatchFlags.Unix);
- var actual = Matcher.IsMatch(path.AsSpan(), text.AsSpan(0, length), MatchFlags.Unix);
-
- Assert.That(actual, Is.EqualTo(expected));
- }
-
- [TestCase(MatchFlags.Unix)]
- [TestCase(MatchFlags.Windows)]
- public void IsMatch_DoesNotReadBeyondBuffers(MatchFlags flags)
- {
- if (!GuardedBuffer.IsSupported)
- Assert.Ignore("Guard pages are not supported on this platform.");
-
- // A read past the end of either buffer terminates the test host with an AccessViolationException.
- string[] patterns =
- [
- "", "[", "[!", "[a", "[!a", "[a-", "[!a-", "[a-b", "[a-b]", "[!a-b]", "[a-]",
- @"\", @"a\", @"\a", @"*\", "*[", "*[a-", "{", "{a", "{a,", "{a,b", "{a,b}", "{*a,b}",
- "{[a-", "{[a-,b}", "*", "**", "a*", "*a", "?", "**/", "a/**", "**/a", "*/*", "a/[",
- ];
-
- string[] paths = ["", "a", "b", "-", "ab", "a/b", "a/", @"a\"];
-
- Assert.Multiple(() =>
- {
- foreach (var pattern in patterns)
- foreach (var path in paths)
- {
- using var p = new GuardedBuffer(pattern);
- using var v = new GuardedBuffer(path);
-
- var expected = Matcher.IsMatch(path, pattern, flags);
- var actual = Matcher.IsMatch(v.Span, p.Span, flags);
-
- Assert.That(actual, Is.EqualTo(expected), $"pattern: \"{pattern}\", path: \"{path}\"");
- }
- });
- }
-
- [Test]
- public void Bang()
- {
- Matcher.IsMatch(new string('a', 10000) + ".txt", "*.txt");
- Matcher.IsMatch(new string('a', 200), "a*a*a*a*a*a*a*a*a*a*a*a*a*a*b");
- Matcher.IsMatch(string.Join("/", Enumerable.Repeat("a", 200)), "a/**/a/**/a/**/a/**/a/**/a/**/a/**/a/**/a/**/a/**/a/**/a/**/a/**/b");
- }
-}
+namespace Ramstack.Globbing;
+
+[TestFixture]
+public class MatcherTests
+{
+ [TestCase("", "", ExpectedResult = true)]
+ [TestCase("main.c", "main.c", ExpectedResult = true)]
+ [TestCase("main.h", "main.c", ExpectedResult = false)]
+ [TestCase("", "main.c", ExpectedResult = false)]
+ [TestCase("main.c", "", ExpectedResult = false)]
+
+ [TestCase("main.?", "main.c", ExpectedResult = true)]
+ [TestCase("*.c", "main.c", ExpectedResult = true)]
+ [TestCase("main.*", "main.c", ExpectedResult = true)]
+ [TestCase("m*n.*", "main.c", ExpectedResult = true)]
+ [TestCase("m*in.c*", "main.c", ExpectedResult = true)]
+ [TestCase("*", "", ExpectedResult = true)]
+
+ [TestCase("Law*", "Law", ExpectedResult = true)]
+ [TestCase("Law*", "Laws", ExpectedResult = true)]
+ [TestCase("Law*", "Lawyer", ExpectedResult = true)]
+ [TestCase("Law*", "GrokLaw", ExpectedResult = false)]
+ [TestCase("Law*", "La", ExpectedResult = false)]
+ [TestCase("Law*", "aw", ExpectedResult = false)]
+
+ [TestCase("*Law", "Law", ExpectedResult = true)]
+ [TestCase("*Law", "GrokLaw", ExpectedResult = true)]
+ [TestCase("*Law", "La", ExpectedResult = false)]
+ [TestCase("*Law", "Grok", ExpectedResult = false)]
+
+ [TestCase("*Law*", "Law", ExpectedResult = true)]
+ [TestCase("*Law*", "Lawyer", ExpectedResult = true)]
+ [TestCase("*Law*", "GrokLaw", ExpectedResult = true)]
+ [TestCase("*Law*", "La", ExpectedResult = false)]
+ [TestCase("*Law*", "aw", ExpectedResult = false)]
+
+ [TestCase("main.{c}", "main.c", ExpectedResult = true)]
+ [TestCase("main.{c}", "main.h", ExpectedResult = false)]
+ [TestCase("main.{c,h}", "main.c", ExpectedResult = true)]
+ [TestCase("main.{c,h}", "main.h", ExpectedResult = true)]
+ [TestCase("main.{c,h}", "main.d", ExpectedResult = false)]
+ [TestCase("main.{c,h}.bak", "main.c.bak", ExpectedResult = true)]
+ [TestCase("main{.c,.h,}.bak", "main.h.bak", ExpectedResult = true)]
+ [TestCase("main{.c,.h,}.bak", "main.bak", ExpectedResult = true)]
+ [TestCase("main{.c,.h,}.bak", "main.c", ExpectedResult = false)]
+ [TestCase("main{.c,.h,}.bak", "main.h", ExpectedResult = false)]
+ [TestCase("main{.c,.h,}.bak", "main.d", ExpectedResult = false)]
+ [TestCase("{{a,b},{c,d}}", "a", ExpectedResult = true)]
+ [TestCase("{{a,b},{c,d}}", "b", ExpectedResult = true)]
+ [TestCase("{{a,b},{c,d}}", "c", ExpectedResult = true)]
+ [TestCase("{{a,b},{c,d}}", "d", ExpectedResult = true)]
+ [TestCase("main.{{{cs},{h}}}", "main.cs", ExpectedResult = true)]
+ [TestCase("main.{{{cs},{h}}}", "main.h", ExpectedResult = true)]
+ [TestCase("main.{{{cs},{h}}}", "main.d", ExpectedResult = false)]
+
+ [TestCase("main.{c,cp,cpp}", "main.c", ExpectedResult = true)]
+ [TestCase("main.{c,cp,cpp}", "main.cp", ExpectedResult = true)]
+ [TestCase("main.{c,cp,cpp}", "main.cpp", ExpectedResult = true)]
+
+ [TestCase("m.{c,cp,cpp}.bak", "m.c.bak", ExpectedResult = true)]
+ [TestCase("m.{c,cp,cpp}.bak", "m.cp.bak", ExpectedResult = true)]
+ [TestCase("m.{c,cp,cpp}.bak", "m.cpp.bak", ExpectedResult = true)]
+ [TestCase("m.{c,cp,cpp}.bak", "m.cpp", ExpectedResult = false)]
+ [TestCase("m.{c,cp,cpp}.bak", "m.css.bak", ExpectedResult = false)]
+
+ [TestCase("main{.c,.h,}", "main", ExpectedResult = true)]
+ [TestCase("main{.c,.h,}", "main.c", ExpectedResult = true)]
+ [TestCase("main{.c,.h,}", "main.h", ExpectedResult = true)]
+ [TestCase("main{.c,.h,}", "main.d", ExpectedResult = false)]
+
+ [TestCase("m{.c,.h,}.bak", "m.bak", ExpectedResult = true)]
+ [TestCase("m{.c,.h,}.bak", "m.c.bak", ExpectedResult = true)]
+ [TestCase("m{.c,.h,}.bak", "m.h.bak", ExpectedResult = true)]
+ [TestCase("m{.c,.h,}.bak", "m.d.bak", ExpectedResult = false)]
+ [TestCase("m{.c,.h,}.bak", "a.c.bak", ExpectedResult = false)]
+ [TestCase("m{.c,.h,}.bak", "a.bak", ExpectedResult = false)]
+ [TestCase("m{.c,.h,}.bak", "a.zip", ExpectedResult = false)]
+
+ [TestCase("**", "", ExpectedResult = true)]
+ [TestCase("***", "", ExpectedResult = true)]
+ [TestCase("****", "", ExpectedResult = true)]
+ [TestCase("{}", "", ExpectedResult = true)]
+ [TestCase("{}{}", "", ExpectedResult = true)]
+ [TestCase("{}{}{}", "", ExpectedResult = true)]
+ [TestCase("*{}*{}*{}*{}", "", ExpectedResult = true)]
+ [TestCase("*{}{}**{}{}**{}{}", "", ExpectedResult = true)]
+ [TestCase("*{}**{}{}**", "", ExpectedResult = true)]
+ [TestCase("{,}", "", ExpectedResult = true)]
+ [TestCase("{,,,,,}", "", ExpectedResult = true)]
+ [TestCase("{{{{},{},{},{}}}}", "", ExpectedResult = true)]
+
+ [TestCase("a*", "a", ExpectedResult = true)]
+ [TestCase("a**", "a", ExpectedResult = true)]
+ [TestCase("a***", "a", ExpectedResult = true)]
+ [TestCase("a****", "a", ExpectedResult = true)]
+ [TestCase("a{}", "a", ExpectedResult = true)]
+ [TestCase("a{}{}", "a", ExpectedResult = true)]
+ [TestCase("a{}{}{}", "a", ExpectedResult = true)]
+ [TestCase("a*{}*{}*{}*{}", "a", ExpectedResult = true)]
+ [TestCase("a*{}{}**{}{}**{}{}", "a", ExpectedResult = true)]
+ [TestCase("a*{}**{}{}**", "a", ExpectedResult = true)]
+
+ [TestCase("a*b", "a", ExpectedResult = false)]
+ [TestCase("a{}b", "a", ExpectedResult = false)]
+ [TestCase("a{,}b", "a", ExpectedResult = false)]
+ [TestCase("a{}}", "a", ExpectedResult = false)]
+ [TestCase("*b", "", ExpectedResult = false)]
+ [TestCase("{}b", "", ExpectedResult = false)]
+ [TestCase("{,}b", "", ExpectedResult = false)]
+ [TestCase("{}}", "", ExpectedResult = false)]
+
+ [TestCase("a*", "ab", ExpectedResult = true)]
+ [TestCase("a**", "ab", ExpectedResult = true)]
+ [TestCase("a***", "ab", ExpectedResult = true)]
+ [TestCase("a****", "ab", ExpectedResult = true)]
+ [TestCase("a{}", "ab", ExpectedResult = false)]
+ [TestCase("a{}{}", "ab", ExpectedResult = false)]
+ [TestCase("a{}{}{}", "ab", ExpectedResult = false)]
+ [TestCase("a{,b}{,c}{,d}", "a", ExpectedResult = true)]
+ [TestCase("a{,b}{,c}{,d}", "ab", ExpectedResult = true)]
+ [TestCase("a{,b}{,c}", "abc", ExpectedResult = true)]
+ [TestCase("a{,b}{,c}{,d}", "abc", ExpectedResult = true)]
+ [TestCase("a{,b}{,c}{,d}", "abd", ExpectedResult = true)]
+ [TestCase("a{,b}{,c}", "ab", ExpectedResult = true)]
+ [TestCase("a{,b}{,c}", "ac", ExpectedResult = true)]
+ [TestCase("a{,b}{,c}", "ad", ExpectedResult = false)]
+ [TestCase("a*{}*{}*{}*{}", "ab", ExpectedResult = true)]
+ [TestCase("a*{}{}**{}{}**{}{}", "ab", ExpectedResult = true)]
+ [TestCase("a*{}**{}{}**", "ab", ExpectedResult = true)]
+ [TestCase("a*{}{}{b}", "ab", ExpectedResult = true)]
+ [TestCase("{a}{b}{c}", "abc", ExpectedResult = true)]
+
+ [TestCase("{,a}", "a", ExpectedResult = true)]
+ [TestCase("{,,,,a}", "a", ExpectedResult = true)]
+ [TestCase("{,,,,a}", "a", ExpectedResult = true)]
+ [TestCase("{a,,,,}", "a", ExpectedResult = true)]
+ [TestCase("{,a,}", "a", ExpectedResult = true)]
+ [TestCase("{{},{},{},a}", "a", ExpectedResult = true)]
+ [TestCase("{{},{},{,a}}", "a", ExpectedResult = true)]
+ [TestCase("{{{}},{,{{,{,a}}}}}", "a", ExpectedResult = true)]
+ [TestCase("{{{}},{,{{,{,a}}}}}", "b", ExpectedResult = false)]
+ [TestCase("{,a}", "b", ExpectedResult = false)]
+ [TestCase("{,,,,a}b", "ab", ExpectedResult = true)]
+ [TestCase("{{},{},{,{,a}}}b", "ab", ExpectedResult = true)]
+ [TestCase("{a}", "", ExpectedResult = false)]
+ [TestCase("{a{}}", "", ExpectedResult = false)]
+ [TestCase("t{a{}}", "t", ExpectedResult = false)]
+
+ [TestCase("[a]", "", ExpectedResult = false)]
+ [TestCase("main.[c]", "main.c", ExpectedResult = true)]
+ [TestCase("main.[c]", "main.d", ExpectedResult = false)]
+ [TestCase("main.[dch]", "main.c", ExpectedResult = true)]
+ [TestCase("main.[dch]", "main.d", ExpectedResult = true)]
+ [TestCase("main.[dch]", "main.h", ExpectedResult = true)]
+ [TestCase("main.[c-d]", "main.c", ExpectedResult = true)]
+ [TestCase("main.[c-d]", "main.d", ExpectedResult = true)]
+ [TestCase("main.[c-dh]", "main.c", ExpectedResult = true)]
+ [TestCase("main.[c-dh]", "main.d", ExpectedResult = true)]
+ [TestCase("main.[c-dh]", "main.h", ExpectedResult = true)]
+ [TestCase("main.[a-z0-9]", "main.h", ExpectedResult = true)]
+ [TestCase("main.[a-z0-9]", "main.a", ExpectedResult = true)]
+ [TestCase("main.[a-z0-9]", "main.z", ExpectedResult = true)]
+ [TestCase("main.[a-z0-9]", "main.0", ExpectedResult = true)]
+ [TestCase("main.[a-z0-9]", "main.5", ExpectedResult = true)]
+ [TestCase("main.[a-z0-9]", "main.9", ExpectedResult = true)]
+ [TestCase("main.[A-Fa-f0-9]", "main.C", ExpectedResult = true)]
+ [TestCase("main.[A-Fa-f0-9]", "main.c", ExpectedResult = true)]
+ [TestCase("main.[A-Fa-f0-9]", "main.5", ExpectedResult = true)]
+ [TestCase("main.[A-Fa-f0-9]", "main.-", ExpectedResult = false)]
+ [TestCase("main.[A-Fa-f0-9]", "main.z", ExpectedResult = false)]
+ [TestCase("main.[A-Fa-f0-9]", "main.Z", ExpectedResult = false)]
+ [TestCase("main.[A-Fa-f0-9]", "main.@", ExpectedResult = false)]
+ [TestCase("main.[A-Fa-f0-9-]", "main.-", ExpectedResult = true)]
+ [TestCase("[a-c-e-g]", "-", ExpectedResult = true)]
+ [TestCase("[a-c-e-g]", "a", ExpectedResult = true)]
+ [TestCase("[a-c-e-g]", "b", ExpectedResult = true)]
+ [TestCase("[a-c-e-g]", "c", ExpectedResult = true)]
+ [TestCase("[a-c-e-g]", "e", ExpectedResult = true)]
+ [TestCase("[a-c-e-g]", "f", ExpectedResult = true)]
+ [TestCase("[a-c-e-g]", "g", ExpectedResult = true)]
+ [TestCase("[a-c-e-g]", "d", ExpectedResult = false)]
+ [TestCase("[]0-346-8[]", "0", ExpectedResult = true)]
+ [TestCase("[]0-346-8[]", "2", ExpectedResult = true)]
+ [TestCase("[]0-346-8[]", "3", ExpectedResult = true)]
+ [TestCase("[]0-346-8[]", "4", ExpectedResult = true)]
+ [TestCase("[]0-346-8[]", "5", ExpectedResult = false)]
+ [TestCase("[]0-346-8[]", "6", ExpectedResult = true)]
+ [TestCase("[]0-346-8[]", "7", ExpectedResult = true)]
+ [TestCase("[]0-346-8[]", "8", ExpectedResult = true)]
+ [TestCase("[]0-346-8[]", "]", ExpectedResult = true)]
+ [TestCase("[]0-346-8[]", "[", ExpectedResult = true)]
+
+ [TestCase("[!0-9]", "a", ExpectedResult = true)]
+ [TestCase("[!0-9]", "Z", ExpectedResult = true)]
+ [TestCase("[!0-9]", "@", ExpectedResult = true)]
+ [TestCase("[!0-9]", "-", ExpectedResult = true)]
+ [TestCase("[!0-9]", "0", ExpectedResult = false)]
+ [TestCase("[!0-9]", "5", ExpectedResult = false)]
+ [TestCase("[!0-9]", "9", ExpectedResult = false)]
+ [TestCase("[!a-z0-9]", "0", ExpectedResult = false)]
+ [TestCase("[!a-z0-9]", "9", ExpectedResult = false)]
+ [TestCase("[!a-z0-9]", "a", ExpectedResult = false)]
+ [TestCase("[!a-z0-9]", "f", ExpectedResult = false)]
+ [TestCase("[!a-z0-9]", "A", ExpectedResult = true)]
+ [TestCase("[!a-z0-9]", "-", ExpectedResult = true)]
+ [TestCase("[!a-z0-9-]", "-", ExpectedResult = false)]
+
+ [TestCase("[CB]at", "Cat", ExpectedResult = true)]
+ [TestCase("[CB]at", "Bat", ExpectedResult = true)]
+ [TestCase("[CB]at", "CBat", ExpectedResult = false)]
+
+ [TestCase("[][!]", "]", ExpectedResult = true)]
+ [TestCase("[][!]", "[", ExpectedResult = true)]
+ [TestCase("[][!]", "!", ExpectedResult = true)]
+ [TestCase("[][!]", "5", ExpectedResult = false)]
+ [TestCase("[", "[", ExpectedResult = false)]
+ [TestCase("[a", "[a", ExpectedResult = false)]
+ [TestCase("]", "]", ExpectedResult = true)]
+ [TestCase("a]", "a]", ExpectedResult = true)]
+ [TestCase("[?]", "?", ExpectedResult = true)]
+ [TestCase("[*]", "*", ExpectedResult = true)]
+ [TestCase("[{]", "{", ExpectedResult = true)]
+ [TestCase("[}]", "}", ExpectedResult = true)]
+
+ [TestCase("[--0]", "-", ExpectedResult = true)]
+ [TestCase("[--0]", ".", ExpectedResult = true)]
+ [TestCase("[--0]", "0", ExpectedResult = true)]
+ [TestCase("[--0]", "/", ExpectedResult = false)]
+ [TestCase("[--0]", "a", ExpectedResult = false)]
+ [TestCase("[--0]", "1", ExpectedResult = false)]
+
+ [TestCase("[!]a-]", "b", ExpectedResult = true)]
+ [TestCase("[!]a-]", "]", ExpectedResult = false)]
+ [TestCase("[!]a-]", "a", ExpectedResult = false)]
+ [TestCase("[!]a-]", "-", ExpectedResult = false)]
+
+ [TestCase(@"[[?*\]", "[", ExpectedResult = true)]
+ [TestCase(@"[[?*\]", "?", ExpectedResult = true)]
+ [TestCase(@"[[?*\]", "*", ExpectedResult = true)]
+ [TestCase(@"[[?*\]", "\\", ExpectedResult = true)]
+ [TestCase(@"[[?*\]", "a", ExpectedResult = false)]
+ [TestCase(@"[[?*\]", "0", ExpectedResult = false)]
+
+ [TestCase(@"\*", "*", ExpectedResult = true)]
+ [TestCase(@"main.\*", "main.*", ExpectedResult = true)]
+ [TestCase(@"\main.c", "main.c", ExpectedResult = true)]
+ [TestCase(@"\[", "[", ExpectedResult = true)]
+ [TestCase(@"\[\?\{name]", "[?{name]", ExpectedResult = true)]
+ [TestCase(@"\a\b\c\d\e\f", "abcdef", ExpectedResult = true)]
+ [TestCase(@"\*", "a", ExpectedResult = false)]
+ [TestCase(@"\?", "?", ExpectedResult = true)]
+ [TestCase(@"\?", "a", ExpectedResult = false)]
+ [TestCase(@"main.\?", "main.c", ExpectedResult = false)]
+ [TestCase(@"*\?", "main?", ExpectedResult = true)]
+ [TestCase(@"*\?", "main", ExpectedResult = false)]
+ [TestCase(@"a\", @"a\", ExpectedResult = false)]
+
+ [TestCase("[Зз]емля", "Земля", ExpectedResult = true)]
+ [TestCase("[Зз]емля", "земля", ExpectedResult = true)]
+
+ [TestCase("*.[a-z]", "main.c", ExpectedResult = true)]
+ [TestCase("*.{[a-z]}", "main.c", ExpectedResult = true)]
+ [TestCase("*.{[a-z],p?[a-z]}", "main.c", ExpectedResult = true)]
+ [TestCase("*.{[a-z],p?[a-z]}", "main.pdb", ExpectedResult = true)]
+ [TestCase("*.{[a-z],p?[a-z]}", "main.pdf", ExpectedResult = true)]
+ [TestCase("*.{[a-z],p?[a-z]}", "main.pas", ExpectedResult = true)]
+ [TestCase("*.{[a-z],p?{[a-z]}}", "main.pas", ExpectedResult = true)]
+ [TestCase("*.{{[a-z]},p?[a-z]}", "main.c", ExpectedResult = true)]
+ [TestCase("*.{{[a-z]},p?[a-z]}", "main.pas", ExpectedResult = true)]
+
+ [TestCase("{", "{", ExpectedResult = false)]
+ [TestCase("{a", "{a", ExpectedResult = false)]
+ [TestCase("}", "}", ExpectedResult = true)]
+ [TestCase("}a", "}a", ExpectedResult = true)]
+
+ [TestCase("main.{a,*}", "main.a", ExpectedResult = true)]
+ [TestCase("main.{a,*}", "main.c", ExpectedResult = true)]
+ [TestCase("main.{a,*}", "main.cpp", ExpectedResult = true)]
+
+ [TestCase("main.{a,*}.bak", "main.a.bak", ExpectedResult = false)]
+ [TestCase("main.{a,*}.bak", "main.c.bak", ExpectedResult = false)]
+ [TestCase("*{,cs}", "main.cs", ExpectedResult = true)]
+ [TestCase("*{,cs}", "main", ExpectedResult = true)]
+ [TestCase("*{,cs}", "main.c", ExpectedResult = true)]
+ [TestCase("*{,cs}", "main.cpp", ExpectedResult = true)]
+ [TestCase("*{,*}", "main.bak", ExpectedResult = true)]
+ [TestCase("{*.cs,*.txt}", "main.cs", ExpectedResult = true)]
+ [TestCase("{*.cs,*.txt}", "main.txt", ExpectedResult = true)]
+ [TestCase("{*.cs,*.txt}", "main.c", ExpectedResult = false)]
+ [TestCase("{*a,b}", "b", ExpectedResult = true)]
+ [TestCase("main.{*a,b}", "main.b", ExpectedResult = true)]
+
+ [TestCase("*.{[a-z],p?[a-z]}", "main.0", ExpectedResult = false)]
+ [TestCase("*.{[a-z],p?[a-z]}", "main.pd", ExpectedResult = false)]
+ [TestCase("*.{[a-z],p?[a-z]}", "main.exe", ExpectedResult = false)]
+ [TestCase("*.[a-z]", "main.0", ExpectedResult = false)]
+ [TestCase("*.{[a-z]}", "main.0", ExpectedResult = false)]
+
+ [TestCase("a*", "aaaaaa", ExpectedResult = true)]
+ [TestCase("a**", "aaaaaa", ExpectedResult = true)]
+ [TestCase("a***", "aaaaaa", ExpectedResult = true)]
+ [TestCase("abc*", "abcabc", ExpectedResult = true)]
+ [TestCase("*abc", "abcabc", ExpectedResult = true)]
+ [TestCase("*abc*", "abcabc", ExpectedResult = true)]
+ [TestCase("**abc*", "abcabc", ExpectedResult = true)]
+ [TestCase("*ac*ae*ag*", "abacadaeafag", ExpectedResult = true)]
+ [TestCase("*ab*[cd]*e*f*g*", "abacadaeafag", ExpectedResult = true)]
+ public bool IsMatchSegment(string pattern, string value) =>
+ Matcher.IsMatch(value, pattern, MatchFlags.Unix);
+
+ [TestCase("/dir", "/dir", ExpectedResult = true)]
+ [TestCase("dir", "dir", ExpectedResult = true)]
+ [TestCase("/dir", "dir/", ExpectedResult = true)]
+ [TestCase("dir/", "/dir", ExpectedResult = true)]
+ [TestCase("dir/", "dir/", ExpectedResult = true)]
+ [TestCase("dir", "/dir/", ExpectedResult = true)]
+
+ [TestCase("dir1/dir2/file.cs", "/dir1/dir2/file.cs", ExpectedResult = true)]
+ [TestCase("dir1/dir2/file.cs", "/dir1/dir2/file.ps", ExpectedResult = false)]
+ [TestCase("dir1/*/file.cs", "/dir1/dir2/file.cs", ExpectedResult = true)]
+ [TestCase("*/*/*.{cs,ps,c}", "/dir1/dir2/file.ps", ExpectedResult = true)]
+ [TestCase("*/*/*.{cs,ps,c}", "/dir1/dir2/file.js", ExpectedResult = false)]
+ [TestCase("dir1/{d2,d3}/file.cs", "/dir1/d2/file.cs", ExpectedResult = true)]
+ [TestCase("dir1/{d2,d3}/file.cs", "/dir1/d3/file.cs", ExpectedResult = true)]
+ [TestCase("dir1/{d2,d3}/file.cs", "/dir1/d4/file.cs", ExpectedResult = false)]
+ [TestCase("*/*/*", "/dir1/dir2/file", ExpectedResult = true)]
+ [TestCase("*/*/*", "/d1/d2/d3/d4", ExpectedResult = false)]
+ [TestCase("a/b/c", "/a///b///c//", ExpectedResult = true)]
+ [TestCase("a/b/c", "/a///b///c////", ExpectedResult = true)]
+ [TestCase("///a////b/c////", "/a///b///c////", ExpectedResult = true)]
+
+ [TestCase("*/*", "a/b", ExpectedResult = true)]
+ [TestCase("*/*", "a", ExpectedResult = false)]
+ [TestCase("*/*", "a/", ExpectedResult = false)]
+ [TestCase("*/*/", "a", ExpectedResult = false)]
+ [TestCase("*/*/{,}", "a/b", ExpectedResult = false)]
+ [TestCase("*/*/*", "", ExpectedResult = false)]
+ [TestCase("*/*/*", "a", ExpectedResult = false)]
+ [TestCase("*/*/*", "a/b", ExpectedResult = false)]
+ [TestCase("*/*/*", "a/b/c", ExpectedResult = true)]
+ [TestCase("a/b/c", "", ExpectedResult = false)]
+ [TestCase("a/b/c", "a", ExpectedResult = false)]
+ [TestCase("a/b/c", "a/b", ExpectedResult = false)]
+ [TestCase("a/b/c", "a/b/c", ExpectedResult = true)]
+
+ [TestCase("*/{,b}", "a/b", ExpectedResult = true)]
+ [TestCase("*/{,b}", "a", ExpectedResult = false)]
+ [TestCase("*/{,b}", "a/", ExpectedResult = false)]
+ [TestCase("*/{,}", "a", ExpectedResult = false)]
+ [TestCase("*/{,}", "a/", ExpectedResult = false)]
+ [TestCase("*/{,}", "a/b", ExpectedResult = false)]
+ [TestCase("*/{}", "a", ExpectedResult = false)]
+ [TestCase("*/{}", "a/", ExpectedResult = false)]
+ [TestCase("*/{}", "a/b", ExpectedResult = false)]
+
+ [TestCase("", "", ExpectedResult = true)]
+ [TestCase("", "a", ExpectedResult = false)]
+ [TestCase("/", "a", ExpectedResult = false)]
+
+ [TestCase("*", "", ExpectedResult = true)]
+ [TestCase("**", "", ExpectedResult = true)]
+ [TestCase("a/b/**", "", ExpectedResult = false)]
+ [TestCase("a/b/**", "a", ExpectedResult = false)]
+ [TestCase("a/b/**", "a/b", ExpectedResult = true)]
+ [TestCase("a/b/**", "a/b/c", ExpectedResult = true)]
+ [TestCase("a/b/**", "a/b/c/d", ExpectedResult = true)]
+ [TestCase("a/b/**/*", "", ExpectedResult = false)]
+ [TestCase("a/b/**/*", "a", ExpectedResult = false)]
+ [TestCase("a/b/**/*", "a/b", ExpectedResult = true)]
+ [TestCase("a/b/**/*", "a/b/c", ExpectedResult = true)]
+ [TestCase("a/b/**/*", "a/b/c/d", ExpectedResult = true)]
+ [TestCase("**/*", "", ExpectedResult = true)]
+ [TestCase("a/**/c/d", "a/b/c/d", ExpectedResult = true)]
+ [TestCase("a/**/c/d", "a/c/d", ExpectedResult = true)]
+ [TestCase("a/**/c/d", "a/b/e/f/c/d", ExpectedResult = true)]
+ [TestCase("a/**/c/d", "a/b/c/d/e", ExpectedResult = false)]
+ [TestCase("a/**/c/**/d", "a/b/c/d", ExpectedResult = true)]
+ [TestCase("a/**/c/**/d", "a/c/d", ExpectedResult = true)]
+ [TestCase("a/**/c/**/d", "a/b/e/f/c/g/c/d", ExpectedResult = true)]
+ [TestCase("a/**/c/**/d", "a/c/d/a/c/d/a/c/d/", ExpectedResult = true)]
+ [TestCase("a/**/c/**/d", "a/c/d/a/c/d/a/c/f/", ExpectedResult = false)]
+ [TestCase("a/**/c/**/d", "a/c/d/a/c/d/a/c/d/f/", ExpectedResult = false)]
+ [TestCase("a/**/c/**/d", "a/c/d/e", ExpectedResult = false)]
+ [TestCase("a/**/c/**/d", "b/c/d/e", ExpectedResult = false)]
+ [TestCase("a/**/c/**/d", "a/c/c/f", ExpectedResult = false)]
+ [TestCase("a/**/c/**/d", "a/c/e", ExpectedResult = false)]
+ [TestCase("a/**/c/**/d", "a/e/c", ExpectedResult = false)]
+ [TestCase("**", "a", ExpectedResult = true)]
+ [TestCase("**", "a/b/c", ExpectedResult = true)]
+ [TestCase("**/*", "a", ExpectedResult = true)]
+ [TestCase("**/*", "a/b/c", ExpectedResult = true)]
+
+ [TestCase("{src,test{s,}}/*.cs", "src/main.cs", ExpectedResult = true)]
+ [TestCase("{src,test{s,}}/*.cs", "test/main.cs", ExpectedResult = true)]
+ [TestCase("{src,test{s,}}/*.cs", "tests/main.cs", ExpectedResult = true)]
+ [TestCase("{src,test{s,}}/*.cs", "test2/main.cs", ExpectedResult = false)]
+ [TestCase("{src,test{s,}}/*.cs", "tests/main.c", ExpectedResult = false)]
+ [TestCase("{src,,test}/file.txt", "src/file.txt", ExpectedResult = true)]
+ [TestCase("{src,,test}/file.txt", "src/file.txt", ExpectedResult = true)]
+ [TestCase("{a,,b}1/file.txt", "a1/file.txt", ExpectedResult = true)]
+ [TestCase("{a,,b}1/file.txt", "b1/file.txt", ExpectedResult = true)]
+ [TestCase("{a,,b}1/file.txt", "1/file.txt", ExpectedResult = true)]
+ [TestCase("{a,,b}1/file.txt", "a/file.txt", ExpectedResult = false)]
+ [TestCase("{a,,b}1/file.txt", "a1/readme.txt", ExpectedResult = false)]
+ [TestCase("{a,,b}1/file.txt", "doc/file.txt", ExpectedResult = false)]
+ [TestCase("{[sS]rc,test*}/*.cs", "src/app.cs", ExpectedResult = true)]
+ [TestCase("{[sS]rc,test*}/*.cs", "src/app.cs", ExpectedResult = true)]
+ [TestCase("{[sS]rc,test*}/*.cs", "Src/app.cs", ExpectedResult = true)]
+ [TestCase("{[sS]rc,test*}/*.cs", "test/app.cs", ExpectedResult = true)]
+ [TestCase("{[sS]rc,test*}/*.cs", "tests/app.cs", ExpectedResult = true)]
+ [TestCase("{[sS]rc,test*}/*.cs", "unittest/app.cs", ExpectedResult = false)]
+ [TestCase("{[sS]rc,test*}/*.cs", "test/app.cpp", ExpectedResult = false)]
+ public bool IsMatch(string pattern, string path) =>
+ Matcher.IsMatch(path, pattern, MatchFlags.Unix);
+
+ [TestCase(@"\a\b\*\d\e", "ab*de", ExpectedResult = true)]
+ [TestCase(@"\a\b\*\d\e", "abcde", ExpectedResult = false)]
+ public bool IsMatch_Unix(string pattern, string path) =>
+ Matcher.IsMatch(path, pattern, MatchFlags.Unix);
+
+ [TestCase(@"\a\b\*\d\e", @"\a\b\c\d\e", ExpectedResult = true)]
+ [TestCase(@"\a\b\*\d\e", @"/a/b\c/d/e", ExpectedResult = true)]
+ [TestCase(@"/a/b/*\d/e", @"\a\b/c\d\e\", ExpectedResult = true)]
+ [TestCase(@"\a\b\*\d\e", @"\a\b\c\d\e\f", ExpectedResult = false)]
+ public bool IsMatch_Windows(string pattern, string path) =>
+ Matcher.IsMatch(path, pattern, MatchFlags.Windows);
+
+ [TestCase("", ExpectedResult = true)]
+ [TestCase("*", ExpectedResult = true)]
+ [TestCase("**", ExpectedResult = true)]
+ [TestCase("{,a}", ExpectedResult = true)]
+ [TestCase("abc", ExpectedResult = false)]
+ [TestCase("*.cs", ExpectedResult = false)]
+ [TestCase("*/*", ExpectedResult = false)]
+ [TestCase("{a", ExpectedResult = false)]
+ public bool IsMatch_EmptySpanPath(string pattern) =>
+ // ReadOnlySpan.Empty is backed by a null reference
+ Matcher.IsMatch(ReadOnlySpan.Empty, pattern.AsSpan(), MatchFlags.Unix);
+
+ [TestCase("[a-b]", 4, "a")]
+ [TestCase("[a-b]", 4, "b")]
+ [TestCase("[!a]", 2, "a")]
+ [TestCase("[a-]", 3, "a")]
+ [TestCase(@"a\?", 2, "ax")]
+ [TestCase(@"a\b", 2, "ab")]
+ public void IsMatch_PatternSlice_IgnoresCharsBeyondSlice(string text, int length, string path)
+ {
+ var expected = Matcher.IsMatch(path, text[..length], MatchFlags.Unix);
+ var actual = Matcher.IsMatch(path.AsSpan(), text.AsSpan(0, length), MatchFlags.Unix);
+
+ Assert.That(actual, Is.EqualTo(expected));
+ }
+
+ [TestCase(MatchFlags.Unix)]
+ [TestCase(MatchFlags.Windows)]
+ public void IsMatch_DoesNotReadBeyondBuffers(MatchFlags flags)
+ {
+ if (!GuardedBuffer.IsSupported)
+ Assert.Ignore("Guard pages are not supported on this platform.");
+
+ // A read past the end of either buffer terminates the test host with an AccessViolationException.
+ string[] patterns =
+ [
+ "", "[", "[!", "[a", "[!a", "[a-", "[!a-", "[a-b", "[a-b]", "[!a-b]", "[a-]",
+ @"\", @"a\", @"\a", @"*\", "*[", "*[a-", "{", "{a", "{a,", "{a,b", "{a,b}", "{*a,b}",
+ "{[a-", "{[a-,b}", "*", "**", "a*", "*a", "?", "**/", "a/**", "**/a", "*/*", "a/[",
+ ];
+
+ string[] paths = ["", "a", "b", "-", "ab", "a/b", "a/", @"a\"];
+
+ Assert.Multiple(() =>
+ {
+ foreach (var pattern in patterns)
+ foreach (var path in paths)
+ {
+ using var p = new GuardedBuffer(pattern);
+ using var v = new GuardedBuffer(path);
+
+ var expected = Matcher.IsMatch(path, pattern, flags);
+ var actual = Matcher.IsMatch(v.Span, p.Span, flags);
+
+ Assert.That(actual, Is.EqualTo(expected), $"pattern: \"{pattern}\", path: \"{path}\"");
+ }
+ });
+ }
+
+ [Test]
+ public void Bang()
+ {
+ Matcher.IsMatch(new string('a', 10000) + ".txt", "*.txt");
+ Matcher.IsMatch(new string('a', 200), "a*a*a*a*a*a*a*a*a*a*a*a*a*a*b");
+ Matcher.IsMatch(string.Join("/", Enumerable.Repeat("a", 200)), "a/**/a/**/a/**/a/**/a/**/a/**/a/**/a/**/a/**/a/**/a/**/a/**/a/**/b");
+ }
+}
diff --git a/Ramstack.Globbing.Tests/Ramstack.Globbing.Tests.csproj b/Ramstack.Globbing.Tests/Ramstack.Globbing.Tests.csproj
index 4ee52d6..cd920dc 100644
--- a/Ramstack.Globbing.Tests/Ramstack.Globbing.Tests.csproj
+++ b/Ramstack.Globbing.Tests/Ramstack.Globbing.Tests.csproj
@@ -1,31 +1,31 @@
-
-
- net6.0
- enable
- enable
- true
- preview
- Ramstack.Globbing
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
+
+
+ net6.0
+ enable
+ enable
+ true
+ preview
+ Ramstack.Globbing
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/Ramstack.Globbing.Tests/SimdConfigurationTests.cs b/Ramstack.Globbing.Tests/SimdConfigurationTests.cs
index e76671b..52b77d4 100644
--- a/Ramstack.Globbing.Tests/SimdConfigurationTests.cs
+++ b/Ramstack.Globbing.Tests/SimdConfigurationTests.cs
@@ -1,29 +1,29 @@
-using System.Runtime.InteropServices;
-using System.Runtime.Intrinsics.Arm;
-using System.Runtime.Intrinsics.X86;
-
-namespace Ramstack.Globbing;
-
-[TestFixture]
-public class SimdConfigurationTests
-{
- [Test]
- public void VerifySimdConfiguration()
- {
- if (Environment.GetEnvironmentVariable("DOTNET_EnableHWIntrinsic") == "0")
- {
- Assert.That(Sse2.IsSupported, Is.False);
- Assert.That(Sse41.IsSupported, Is.False);
- Assert.That(Avx2.IsSupported, Is.False);
- Assert.That(AdvSimd.Arm64.IsSupported, Is.False);
- Assert.That(AdvSimd.IsSupported, Is.False);
- }
-
- if (RuntimeInformation.ProcessArchitecture == Architecture.X64 && Environment.GetEnvironmentVariable("DOTNET_EnableAVX2") == "0")
- {
- Assert.That(Sse2.IsSupported, Is.True);
- Assert.That(Sse41.IsSupported, Is.True);
- Assert.That(Avx2.IsSupported, Is.False);
- }
- }
-}
+using System.Runtime.InteropServices;
+using System.Runtime.Intrinsics.Arm;
+using System.Runtime.Intrinsics.X86;
+
+namespace Ramstack.Globbing;
+
+[TestFixture]
+public class SimdConfigurationTests
+{
+ [Test]
+ public void VerifySimdConfiguration()
+ {
+ if (Environment.GetEnvironmentVariable("DOTNET_EnableHWIntrinsic") == "0")
+ {
+ Assert.That(Sse2.IsSupported, Is.False);
+ Assert.That(Sse41.IsSupported, Is.False);
+ Assert.That(Avx2.IsSupported, Is.False);
+ Assert.That(AdvSimd.Arm64.IsSupported, Is.False);
+ Assert.That(AdvSimd.IsSupported, Is.False);
+ }
+
+ if (RuntimeInformation.ProcessArchitecture == Architecture.X64 && Environment.GetEnvironmentVariable("DOTNET_EnableAVX2") == "0")
+ {
+ Assert.That(Sse2.IsSupported, Is.True);
+ Assert.That(Sse41.IsSupported, Is.True);
+ Assert.That(Avx2.IsSupported, Is.False);
+ }
+ }
+}
diff --git a/Ramstack.Globbing.Tests/Traversal/FileTreeAsyncEnumerableTests.cs b/Ramstack.Globbing.Tests/Traversal/FileTreeAsyncEnumerableTests.cs
index 42d52e8..5e22bac 100644
--- a/Ramstack.Globbing.Tests/Traversal/FileTreeAsyncEnumerableTests.cs
+++ b/Ramstack.Globbing.Tests/Traversal/FileTreeAsyncEnumerableTests.cs
@@ -1,81 +1,81 @@
-using Ramstack.Globbing.Traversal.Helpers;
-
-namespace Ramstack.Globbing.Traversal;
-
-[TestFixture]
-public class FileTreeAsyncEnumerableTests
-{
- private readonly TempFileStorage _storage = new();
-
- [OneTimeTearDown]
- public void Cleanup() =>
- _storage.Dispose();
-
- [Test]
- public async Task Enumerate_Files()
- {
- var enumerable = new FileTreeAsyncEnumerable(new DirectoryInfo(_storage.Root))
- {
- Patterns = ["**"],
- Flags = MatchFlags.Auto,
- FileNameSelector = info => info.Name,
- ShouldRecursePredicate = info => info is DirectoryInfo,
- ShouldIncludePredicate = info => info is FileInfo,
- ResultSelector = info => info.FullName,
- ChildrenSelector = (info, _) => ((DirectoryInfo)info).EnumerateFileSystemInfos().ToAsyncEnumerable()
- }.OrderBy(p => p);
-
- var expected = Directory
- .EnumerateFiles(_storage.Root, "*", SearchOption.AllDirectories)
- .OrderBy(p => p);
-
- Assert.That(
- await enumerable.ToArrayAsync(),
- Is.EquivalentTo(expected));
- }
-
- [Test]
- public async Task Enumerate_Directories()
- {
- var enumerable = new FileTreeAsyncEnumerable(new DirectoryInfo(_storage.Root))
- {
- Patterns = ["**"],
- Flags = MatchFlags.Auto,
- FileNameSelector = info => info.Name,
- ShouldRecursePredicate = info => info is DirectoryInfo,
- ShouldIncludePredicate = info => info is DirectoryInfo,
- ResultSelector = info => info.FullName,
- ChildrenSelector = (info, _) => ((DirectoryInfo)info).EnumerateFileSystemInfos().ToAsyncEnumerable()
- }.OrderBy(p => p);
-
- var expected = Directory
- .EnumerateDirectories(_storage.Root, "*", SearchOption.AllDirectories)
- .OrderBy(p => p);
-
- Assert.That(
- await enumerable.ToArrayAsync(),
- Is.EquivalentTo(expected));
- }
-
- [Test]
- public async Task Enumerate_Both()
- {
- var enumerable = new FileTreeAsyncEnumerable(new DirectoryInfo(_storage.Root))
- {
- Patterns = ["**"],
- Flags = MatchFlags.Auto,
- FileNameSelector = info => info.Name,
- ShouldRecursePredicate = info => info is DirectoryInfo,
- ResultSelector = info => info.FullName,
- ChildrenSelector = (info, _) => ((DirectoryInfo)info).EnumerateFileSystemInfos().ToAsyncEnumerable(),
- }.OrderBy(p => p);
-
- var expected = Directory
- .EnumerateFileSystemEntries(_storage.Root, "*", SearchOption.AllDirectories)
- .OrderBy(p => p);
-
- Assert.That(
- await enumerable.ToArrayAsync(),
- Is.EquivalentTo(expected));
- }
-}
+using Ramstack.Globbing.Traversal.Helpers;
+
+namespace Ramstack.Globbing.Traversal;
+
+[TestFixture]
+public class FileTreeAsyncEnumerableTests
+{
+ private readonly TempFileStorage _storage = new();
+
+ [OneTimeTearDown]
+ public void Cleanup() =>
+ _storage.Dispose();
+
+ [Test]
+ public async Task Enumerate_Files()
+ {
+ var enumerable = new FileTreeAsyncEnumerable(new DirectoryInfo(_storage.Root))
+ {
+ Patterns = ["**"],
+ Flags = MatchFlags.Auto,
+ FileNameSelector = info => info.Name,
+ ShouldRecursePredicate = info => info is DirectoryInfo,
+ ShouldIncludePredicate = info => info is FileInfo,
+ ResultSelector = info => info.FullName,
+ ChildrenSelector = (info, _) => ((DirectoryInfo)info).EnumerateFileSystemInfos().ToAsyncEnumerable()
+ }.OrderBy(p => p);
+
+ var expected = Directory
+ .EnumerateFiles(_storage.Root, "*", SearchOption.AllDirectories)
+ .OrderBy(p => p);
+
+ Assert.That(
+ await enumerable.ToArrayAsync(),
+ Is.EquivalentTo(expected));
+ }
+
+ [Test]
+ public async Task Enumerate_Directories()
+ {
+ var enumerable = new FileTreeAsyncEnumerable(new DirectoryInfo(_storage.Root))
+ {
+ Patterns = ["**"],
+ Flags = MatchFlags.Auto,
+ FileNameSelector = info => info.Name,
+ ShouldRecursePredicate = info => info is DirectoryInfo,
+ ShouldIncludePredicate = info => info is DirectoryInfo,
+ ResultSelector = info => info.FullName,
+ ChildrenSelector = (info, _) => ((DirectoryInfo)info).EnumerateFileSystemInfos().ToAsyncEnumerable()
+ }.OrderBy(p => p);
+
+ var expected = Directory
+ .EnumerateDirectories(_storage.Root, "*", SearchOption.AllDirectories)
+ .OrderBy(p => p);
+
+ Assert.That(
+ await enumerable.ToArrayAsync(),
+ Is.EquivalentTo(expected));
+ }
+
+ [Test]
+ public async Task Enumerate_Both()
+ {
+ var enumerable = new FileTreeAsyncEnumerable(new DirectoryInfo(_storage.Root))
+ {
+ Patterns = ["**"],
+ Flags = MatchFlags.Auto,
+ FileNameSelector = info => info.Name,
+ ShouldRecursePredicate = info => info is DirectoryInfo,
+ ResultSelector = info => info.FullName,
+ ChildrenSelector = (info, _) => ((DirectoryInfo)info).EnumerateFileSystemInfos().ToAsyncEnumerable(),
+ }.OrderBy(p => p);
+
+ var expected = Directory
+ .EnumerateFileSystemEntries(_storage.Root, "*", SearchOption.AllDirectories)
+ .OrderBy(p => p);
+
+ Assert.That(
+ await enumerable.ToArrayAsync(),
+ Is.EquivalentTo(expected));
+ }
+}
diff --git a/Ramstack.Globbing.Tests/Traversal/FileTreeEnumerableTests.cs b/Ramstack.Globbing.Tests/Traversal/FileTreeEnumerableTests.cs
index b85a16d..1530adc 100644
--- a/Ramstack.Globbing.Tests/Traversal/FileTreeEnumerableTests.cs
+++ b/Ramstack.Globbing.Tests/Traversal/FileTreeEnumerableTests.cs
@@ -1,75 +1,75 @@
-using Ramstack.Globbing.Traversal.Helpers;
-
-namespace Ramstack.Globbing.Traversal;
-
-[TestFixture]
-public class FileTreeEnumerableTests
-{
- private readonly TempFileStorage _storage = new();
-
- [OneTimeTearDown]
- public void Cleanup() =>
- _storage.Dispose();
-
- [Test]
- public void Enumerate_Files()
- {
- var enumerable = new FileTreeEnumerable(new DirectoryInfo(_storage.Root))
- {
- Patterns = ["**"],
- Flags = MatchFlags.Auto,
- FileNameSelector = info => info.Name,
- ShouldRecursePredicate = info => info is DirectoryInfo,
- ShouldIncludePredicate = info => info is FileInfo,
- ResultSelector = info => info.FullName,
- ChildrenSelector = info => ((DirectoryInfo)info).EnumerateFileSystemInfos()
- }.OrderBy(p => p);
-
- var expected = Directory
- .EnumerateFiles(_storage.Root, "*", SearchOption.AllDirectories)
- .OrderBy(p => p);
-
- Assert.That(enumerable, Is.EquivalentTo(expected));
- }
-
- [Test]
- public void Enumerate_Directories()
- {
- var enumerable = new FileTreeEnumerable(new DirectoryInfo(_storage.Root))
- {
- Patterns = ["**"],
- Flags = MatchFlags.Auto,
- FileNameSelector = info => info.Name,
- ShouldRecursePredicate = info => info is DirectoryInfo,
- ShouldIncludePredicate = info => info is DirectoryInfo,
- ResultSelector = info => info.FullName,
- ChildrenSelector = info => ((DirectoryInfo)info).EnumerateFileSystemInfos()
- }.OrderBy(p => p);
-
- var expected = Directory
- .EnumerateDirectories(_storage.Root, "*", SearchOption.AllDirectories)
- .OrderBy(p => p);
-
- Assert.That(enumerable, Is.EquivalentTo(expected));
- }
-
- [Test]
- public void Enumerate_Both()
- {
- var enumerable = new FileTreeEnumerable(new DirectoryInfo(_storage.Root))
- {
- Patterns = ["**"],
- Flags = MatchFlags.Auto,
- FileNameSelector = info => info.Name,
- ShouldRecursePredicate = info => info is DirectoryInfo,
- ResultSelector = info => info.FullName,
- ChildrenSelector = info => ((DirectoryInfo)info).EnumerateFileSystemInfos()
- }.OrderBy(p => p);
-
- var expected = Directory
- .EnumerateFileSystemEntries(_storage.Root, "*", SearchOption.AllDirectories)
- .OrderBy(p => p);
-
- Assert.That(enumerable, Is.EquivalentTo(expected));
- }
-}
+using Ramstack.Globbing.Traversal.Helpers;
+
+namespace Ramstack.Globbing.Traversal;
+
+[TestFixture]
+public class FileTreeEnumerableTests
+{
+ private readonly TempFileStorage _storage = new();
+
+ [OneTimeTearDown]
+ public void Cleanup() =>
+ _storage.Dispose();
+
+ [Test]
+ public void Enumerate_Files()
+ {
+ var enumerable = new FileTreeEnumerable(new DirectoryInfo(_storage.Root))
+ {
+ Patterns = ["**"],
+ Flags = MatchFlags.Auto,
+ FileNameSelector = info => info.Name,
+ ShouldRecursePredicate = info => info is DirectoryInfo,
+ ShouldIncludePredicate = info => info is FileInfo,
+ ResultSelector = info => info.FullName,
+ ChildrenSelector = info => ((DirectoryInfo)info).EnumerateFileSystemInfos()
+ }.OrderBy(p => p);
+
+ var expected = Directory
+ .EnumerateFiles(_storage.Root, "*", SearchOption.AllDirectories)
+ .OrderBy(p => p);
+
+ Assert.That(enumerable, Is.EquivalentTo(expected));
+ }
+
+ [Test]
+ public void Enumerate_Directories()
+ {
+ var enumerable = new FileTreeEnumerable(new DirectoryInfo(_storage.Root))
+ {
+ Patterns = ["**"],
+ Flags = MatchFlags.Auto,
+ FileNameSelector = info => info.Name,
+ ShouldRecursePredicate = info => info is DirectoryInfo,
+ ShouldIncludePredicate = info => info is DirectoryInfo,
+ ResultSelector = info => info.FullName,
+ ChildrenSelector = info => ((DirectoryInfo)info).EnumerateFileSystemInfos()
+ }.OrderBy(p => p);
+
+ var expected = Directory
+ .EnumerateDirectories(_storage.Root, "*", SearchOption.AllDirectories)
+ .OrderBy(p => p);
+
+ Assert.That(enumerable, Is.EquivalentTo(expected));
+ }
+
+ [Test]
+ public void Enumerate_Both()
+ {
+ var enumerable = new FileTreeEnumerable(new DirectoryInfo(_storage.Root))
+ {
+ Patterns = ["**"],
+ Flags = MatchFlags.Auto,
+ FileNameSelector = info => info.Name,
+ ShouldRecursePredicate = info => info is DirectoryInfo,
+ ResultSelector = info => info.FullName,
+ ChildrenSelector = info => ((DirectoryInfo)info).EnumerateFileSystemInfos()
+ }.OrderBy(p => p);
+
+ var expected = Directory
+ .EnumerateFileSystemEntries(_storage.Root, "*", SearchOption.AllDirectories)
+ .OrderBy(p => p);
+
+ Assert.That(enumerable, Is.EquivalentTo(expected));
+ }
+}
diff --git a/Ramstack.Globbing.Tests/Traversal/FilesTests.cs b/Ramstack.Globbing.Tests/Traversal/FilesTests.cs
index 150e1ef..8de32ec 100644
--- a/Ramstack.Globbing.Tests/Traversal/FilesTests.cs
+++ b/Ramstack.Globbing.Tests/Traversal/FilesTests.cs
@@ -1,256 +1,256 @@
-using System.Text.RegularExpressions;
-
-using Ramstack.Globbing.Traversal.Helpers;
-
-namespace Ramstack.Globbing.Traversal;
-
-[TestFixture]
-public class FilesTests
-{
- private readonly TempFileStorage _storage = new();
-
- [OneTimeTearDown]
- public void Cleanup() =>
- _storage.Dispose();
-
- [Test]
- public void EnumerateFiles_Default_IncludesHidden()
- {
- var count = Files
- .EnumerateFiles(_storage.Root, "**")
- .Count();
-
- Assert.That(count, Is.EqualTo(_storage.FileList.Count));
- }
-
- [Test]
- public void EnumerateDirectories_Default_IncludesHidden()
- {
- var count = Files
- .EnumerateDirectories(_storage.Root, "**")
- .Count();
-
- var expected = Directory
- .EnumerateDirectories(_storage.Root, "*", SearchOption.AllDirectories)
- .Count();
-
- Assert.That(count, Is.EqualTo(expected));
- }
-
- [Test]
- public void EnumerateEntries_Default_IncludesHidden()
- {
- var count = Files
- .EnumerateFileSystemEntries(_storage.Root, "**")
- .Count();
-
- var expected = Directory
- .EnumerateFileSystemEntries(_storage.Root, "*", SearchOption.AllDirectories)
- .Count();
-
- Assert.That(count, Is.EqualTo(expected));
- }
-
- [Test]
- public void EnumerateFiles_OneLevel()
- {
- var list = Files
- .EnumerateFiles(_storage.Root, "project/*")
- .OrderBy(p => p);
-
- var expected = Directory
- .EnumerateFiles(Path.Combine(_storage.Root, "project"))
- .OrderBy(p => p);
-
- Assert.That(list, Is.EquivalentTo(expected));
- }
-
- [Test]
- public void EnumerateDirectories_OneLevel()
- {
- var list = Files
- .EnumerateDirectories(_storage.Root, "project/*")
- .OrderBy(p => p);
-
- var expected = Directory
- .EnumerateDirectories(Path.Combine(_storage.Root, "project"))
- .OrderBy(p => p);
-
- Assert.That(list, Is.EquivalentTo(expected));
- }
-
- [TestCase("cs")]
- [TestCase("csproj")]
- [TestCase("json")]
- [TestCase("log")]
- [TestCase("dat")]
- [TestCase("tmp")]
- [TestCase("ps1")]
- [TestCase("sh")]
- [TestCase("bat")]
- [TestCase("md")]
- [TestCase("sln")]
- [TestCase("dll")]
- [TestCase("nupkg")]
- [TestCase("vb")]
- public void EnumerateFiles_ByExtension(string ext)
- {
- var list = Files
- .EnumerateFiles(_storage.Root, $"**/*.{ext}")
- .OrderBy(p => p);
-
- var expected = Directory
- .EnumerateFiles(_storage.Root, $"*.{ext}", SearchOption.AllDirectories)
- .OrderBy(p => p);
-
- Assert.That(list, Is.EquivalentTo(expected));
- }
-
- [Test]
- public void EnumerateFiles_BraceExtension()
- {
- var list = Files
- .EnumerateFiles(_storage.Root, "**/*.{log,dat}")
- .OrderBy(p => p);
-
- var expected = Directory
- .EnumerateFiles(_storage.Root, "*", SearchOption.AllDirectories)
- .Where(p => Path.GetExtension(p) is ".log" or ".dat")
- .OrderBy(p => p);
-
- Assert.That(list, Is.EquivalentTo(expected));
- }
-
- [Test]
- public void EnumerateFiles_Set()
- {
- var list = Files
- .EnumerateFiles(_storage.Root, "**/tests/[a-zA-Z]*/*.xml")
- .OrderBy(p => p);
-
- var expected = Directory
- .EnumerateFiles(Path.Combine(_storage.Root, "project", "tests"), "*.xml", SearchOption.AllDirectories)
- .OrderBy(p => p);
-
- Assert.That(list, Is.EquivalentTo(expected));
- }
-
- [Test]
- public void EnumerateFiles_Logs()
- {
- var list = Files
- .EnumerateFiles(_storage.Root, "**/logs/**/*.log")
- .OrderBy(p => p);
-
- var expected = Directory
- .EnumerateFiles(_storage.Root, "*.log", SearchOption.AllDirectories)
- .OrderBy(p => p);
-
- Assert.That(list, Is.EquivalentTo(expected));
- }
-
- [Test]
- public void EnumerateFiles_Temps()
- {
- var list = Files
- .EnumerateFiles(_storage.Root, "**/{hidden{,-folder}}/**/*.{tmp,dat}")
- .OrderBy(p => p);
-
- var expected = Directory
- .EnumerateFiles(_storage.Root, "*", SearchOption.AllDirectories)
- .Where(p => Regex.IsMatch(p, @"\b(hidden|hidden-folder)\b"))
- .OrderBy(p => p);
-
- Assert.That(list, Is.EquivalentTo(expected));
- }
-
- [TestCase(@"**/{hidden{,-folder}}/**/*.{tmp,dat}")]
- [TestCase(@"**\{hidden{,-folder}}\**\*.{tmp,dat}")]
- [TestCase(@"project/**/{hidden{,-folder}}/**/*.{tmp,dat}")]
- [TestCase(@"project\**\{hidden{,-folder}}\**\*.{tmp,dat}")]
- public void EnumerateFiles_NoEscaping(string pattern)
- {
- var list = Files
- .EnumerateFiles(_storage.Root, pattern, flags: MatchFlags.Windows)
- .OrderBy(p => p);
-
- var expected = Directory
- .EnumerateFiles(_storage.Root, "*", SearchOption.AllDirectories)
- .Where(p => Regex.IsMatch(p, @"\b(hidden|hidden-folder)\b"))
- .OrderBy(p => p);
-
- Assert.That(list, Is.EquivalentTo(expected));
- }
-
- [TestCase(@"project/**/dataset-\[data]-\{1}.csv")]
- [TestCase(@"project/**/dataset-\[data\]-\{1\}.csv")]
- [TestCase(@"project/**/dataset-\[*]-\{[0-9]}.csv")]
- [TestCase(@"project/**/dataset-*.csv")]
- public void EnumerateFiles_Escaping(string pattern)
- {
- var list = Files
- .EnumerateFiles(_storage.Root, pattern, flags: MatchFlags.Unix)
- .OrderBy(p => p)
- .ToList();
-
- var expected = Directory
- .EnumerateFiles(Path.Combine(_storage.Root, "project", "data", "raw"), "dataset-*", SearchOption.AllDirectories)
- .OrderBy(p => p);
-
- Assert.That(list.Count, Is.EqualTo(1));
- Assert.That(list, Is.EquivalentTo(expected));
- }
-
- [Test]
- public void EnumerateFiles_Uniqueness()
- {
- var list = Files.EnumerateFiles(_storage.Root, ["/project/**/faq.docx", "**/faq.*", "**/faq.docx"]);
- Assert.That(list.Count(), Is.EqualTo(1));
- }
-
- [Test]
- public void EnumerateFiles_Excludes()
- {
- var list = Files
- .EnumerateFiles(_storage.Root,
- patterns: ["**/assets/*.{png,jp*g}", "**/assets/styles/*.css", "**/assets/**"],
- excludes: ["**/*.ttf"]);
-
- Assert.That(list.Count(), Is.EqualTo(6));
- }
-
- [Test]
- public void EnumerateFiles_ExcludeWins()
- {
- var list = Files
- .EnumerateFiles(_storage.Root,
- pattern: "**/assets/*.css",
- exclude: "**/assets/*.css");
-
- Assert.That(list.Count(), Is.EqualTo(0));
- }
-
- [Test]
- public void EnumerateDirectories_Patterns()
- {
- var list = Files
- .EnumerateDirectories(_storage.Root,
- pattern: "**/assets/{images,fonts,styles}/**",
- exclude: "**/assets/images");
-
- // excluded: images, images/backgrounds
- Assert.That(list.Count(), Is.EqualTo(2));
- }
-
- [Test]
- public void EnumerateEntries_Patterns()
- {
- var list = Files
- .EnumerateFileSystemEntries(_storage.Root,
- pattern: "**/assets/{images,fonts,styles}/**",
- exclude: "**/assets/images");
-
- // excluded: images, images/backgrounds
- Assert.That(list.Count(), Is.EqualTo(6));
- }
-}
+using System.Text.RegularExpressions;
+
+using Ramstack.Globbing.Traversal.Helpers;
+
+namespace Ramstack.Globbing.Traversal;
+
+[TestFixture]
+public class FilesTests
+{
+ private readonly TempFileStorage _storage = new();
+
+ [OneTimeTearDown]
+ public void Cleanup() =>
+ _storage.Dispose();
+
+ [Test]
+ public void EnumerateFiles_Default_IncludesHidden()
+ {
+ var count = Files
+ .EnumerateFiles(_storage.Root, "**")
+ .Count();
+
+ Assert.That(count, Is.EqualTo(_storage.FileList.Count));
+ }
+
+ [Test]
+ public void EnumerateDirectories_Default_IncludesHidden()
+ {
+ var count = Files
+ .EnumerateDirectories(_storage.Root, "**")
+ .Count();
+
+ var expected = Directory
+ .EnumerateDirectories(_storage.Root, "*", SearchOption.AllDirectories)
+ .Count();
+
+ Assert.That(count, Is.EqualTo(expected));
+ }
+
+ [Test]
+ public void EnumerateEntries_Default_IncludesHidden()
+ {
+ var count = Files
+ .EnumerateFileSystemEntries(_storage.Root, "**")
+ .Count();
+
+ var expected = Directory
+ .EnumerateFileSystemEntries(_storage.Root, "*", SearchOption.AllDirectories)
+ .Count();
+
+ Assert.That(count, Is.EqualTo(expected));
+ }
+
+ [Test]
+ public void EnumerateFiles_OneLevel()
+ {
+ var list = Files
+ .EnumerateFiles(_storage.Root, "project/*")
+ .OrderBy(p => p);
+
+ var expected = Directory
+ .EnumerateFiles(Path.Combine(_storage.Root, "project"))
+ .OrderBy(p => p);
+
+ Assert.That(list, Is.EquivalentTo(expected));
+ }
+
+ [Test]
+ public void EnumerateDirectories_OneLevel()
+ {
+ var list = Files
+ .EnumerateDirectories(_storage.Root, "project/*")
+ .OrderBy(p => p);
+
+ var expected = Directory
+ .EnumerateDirectories(Path.Combine(_storage.Root, "project"))
+ .OrderBy(p => p);
+
+ Assert.That(list, Is.EquivalentTo(expected));
+ }
+
+ [TestCase("cs")]
+ [TestCase("csproj")]
+ [TestCase("json")]
+ [TestCase("log")]
+ [TestCase("dat")]
+ [TestCase("tmp")]
+ [TestCase("ps1")]
+ [TestCase("sh")]
+ [TestCase("bat")]
+ [TestCase("md")]
+ [TestCase("sln")]
+ [TestCase("dll")]
+ [TestCase("nupkg")]
+ [TestCase("vb")]
+ public void EnumerateFiles_ByExtension(string ext)
+ {
+ var list = Files
+ .EnumerateFiles(_storage.Root, $"**/*.{ext}")
+ .OrderBy(p => p);
+
+ var expected = Directory
+ .EnumerateFiles(_storage.Root, $"*.{ext}", SearchOption.AllDirectories)
+ .OrderBy(p => p);
+
+ Assert.That(list, Is.EquivalentTo(expected));
+ }
+
+ [Test]
+ public void EnumerateFiles_BraceExtension()
+ {
+ var list = Files
+ .EnumerateFiles(_storage.Root, "**/*.{log,dat}")
+ .OrderBy(p => p);
+
+ var expected = Directory
+ .EnumerateFiles(_storage.Root, "*", SearchOption.AllDirectories)
+ .Where(p => Path.GetExtension(p) is ".log" or ".dat")
+ .OrderBy(p => p);
+
+ Assert.That(list, Is.EquivalentTo(expected));
+ }
+
+ [Test]
+ public void EnumerateFiles_Set()
+ {
+ var list = Files
+ .EnumerateFiles(_storage.Root, "**/tests/[a-zA-Z]*/*.xml")
+ .OrderBy(p => p);
+
+ var expected = Directory
+ .EnumerateFiles(Path.Combine(_storage.Root, "project", "tests"), "*.xml", SearchOption.AllDirectories)
+ .OrderBy(p => p);
+
+ Assert.That(list, Is.EquivalentTo(expected));
+ }
+
+ [Test]
+ public void EnumerateFiles_Logs()
+ {
+ var list = Files
+ .EnumerateFiles(_storage.Root, "**/logs/**/*.log")
+ .OrderBy(p => p);
+
+ var expected = Directory
+ .EnumerateFiles(_storage.Root, "*.log", SearchOption.AllDirectories)
+ .OrderBy(p => p);
+
+ Assert.That(list, Is.EquivalentTo(expected));
+ }
+
+ [Test]
+ public void EnumerateFiles_Temps()
+ {
+ var list = Files
+ .EnumerateFiles(_storage.Root, "**/{hidden{,-folder}}/**/*.{tmp,dat}")
+ .OrderBy(p => p);
+
+ var expected = Directory
+ .EnumerateFiles(_storage.Root, "*", SearchOption.AllDirectories)
+ .Where(p => Regex.IsMatch(p, @"\b(hidden|hidden-folder)\b"))
+ .OrderBy(p => p);
+
+ Assert.That(list, Is.EquivalentTo(expected));
+ }
+
+ [TestCase(@"**/{hidden{,-folder}}/**/*.{tmp,dat}")]
+ [TestCase(@"**\{hidden{,-folder}}\**\*.{tmp,dat}")]
+ [TestCase(@"project/**/{hidden{,-folder}}/**/*.{tmp,dat}")]
+ [TestCase(@"project\**\{hidden{,-folder}}\**\*.{tmp,dat}")]
+ public void EnumerateFiles_NoEscaping(string pattern)
+ {
+ var list = Files
+ .EnumerateFiles(_storage.Root, pattern, flags: MatchFlags.Windows)
+ .OrderBy(p => p);
+
+ var expected = Directory
+ .EnumerateFiles(_storage.Root, "*", SearchOption.AllDirectories)
+ .Where(p => Regex.IsMatch(p, @"\b(hidden|hidden-folder)\b"))
+ .OrderBy(p => p);
+
+ Assert.That(list, Is.EquivalentTo(expected));
+ }
+
+ [TestCase(@"project/**/dataset-\[data]-\{1}.csv")]
+ [TestCase(@"project/**/dataset-\[data\]-\{1\}.csv")]
+ [TestCase(@"project/**/dataset-\[*]-\{[0-9]}.csv")]
+ [TestCase(@"project/**/dataset-*.csv")]
+ public void EnumerateFiles_Escaping(string pattern)
+ {
+ var list = Files
+ .EnumerateFiles(_storage.Root, pattern, flags: MatchFlags.Unix)
+ .OrderBy(p => p)
+ .ToList();
+
+ var expected = Directory
+ .EnumerateFiles(Path.Combine(_storage.Root, "project", "data", "raw"), "dataset-*", SearchOption.AllDirectories)
+ .OrderBy(p => p);
+
+ Assert.That(list.Count, Is.EqualTo(1));
+ Assert.That(list, Is.EquivalentTo(expected));
+ }
+
+ [Test]
+ public void EnumerateFiles_Uniqueness()
+ {
+ var list = Files.EnumerateFiles(_storage.Root, ["/project/**/faq.docx", "**/faq.*", "**/faq.docx"]);
+ Assert.That(list.Count(), Is.EqualTo(1));
+ }
+
+ [Test]
+ public void EnumerateFiles_Excludes()
+ {
+ var list = Files
+ .EnumerateFiles(_storage.Root,
+ patterns: ["**/assets/*.{png,jp*g}", "**/assets/styles/*.css", "**/assets/**"],
+ excludes: ["**/*.ttf"]);
+
+ Assert.That(list.Count(), Is.EqualTo(6));
+ }
+
+ [Test]
+ public void EnumerateFiles_ExcludeWins()
+ {
+ var list = Files
+ .EnumerateFiles(_storage.Root,
+ pattern: "**/assets/*.css",
+ exclude: "**/assets/*.css");
+
+ Assert.That(list.Count(), Is.EqualTo(0));
+ }
+
+ [Test]
+ public void EnumerateDirectories_Patterns()
+ {
+ var list = Files
+ .EnumerateDirectories(_storage.Root,
+ pattern: "**/assets/{images,fonts,styles}/**",
+ exclude: "**/assets/images");
+
+ // excluded: images, images/backgrounds
+ Assert.That(list.Count(), Is.EqualTo(2));
+ }
+
+ [Test]
+ public void EnumerateEntries_Patterns()
+ {
+ var list = Files
+ .EnumerateFileSystemEntries(_storage.Root,
+ pattern: "**/assets/{images,fonts,styles}/**",
+ exclude: "**/assets/images");
+
+ // excluded: images, images/backgrounds
+ Assert.That(list.Count(), Is.EqualTo(6));
+ }
+}
diff --git a/Ramstack.Globbing.Tests/Traversal/Helpers/TempFileStorage.cs b/Ramstack.Globbing.Tests/Traversal/Helpers/TempFileStorage.cs
index 303413c..7280acc 100644
--- a/Ramstack.Globbing.Tests/Traversal/Helpers/TempFileStorage.cs
+++ b/Ramstack.Globbing.Tests/Traversal/Helpers/TempFileStorage.cs
@@ -1,115 +1,117 @@
-namespace Ramstack.Globbing.Traversal.Helpers;
-
-public sealed class TempFileStorage : IDisposable
-{
- public string Root { get; }
- public IReadOnlyList FileList { get; }
-
- public TempFileStorage()
- {
- var root = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());
- var list = new[]
- {
- "project/docs/user_manual.pdf",
- "project/docs/api_reference.md",
- "project/docs/troubleshooting/common_issues.txt",
- "project/docs/troubleshooting/faq.docx",
-
- "project/docs_generated/html/index.html",
- "project/docs_generated/html/api.html",
- "project/docs_generated/pdf/documentation.pdf",
-
- "project/src/App/App.csproj",
- "project/src/App/Program.cs",
- "project/src/App/Utils.cs",
- "project/src/Modules/Module1/Module1.cs",
- "project/src/Modules/Module1/Module1.csproj",
- "project/src/Modules/Module1/Submodule/Submodule1.cs",
- "project/src/Modules/Module1/Submodule/Submodule2.cs",
- "project/src/Modules/Module1/Submodule/Submodule.csproj",
- "project/src/Modules/Module2/Module2.cs",
- "project/src/Modules/Module2/Module2.csproj",
- "project/src/App.sln",
-
- "project/tests/TestMain.cs",
- "project/tests/TestUtils.cs",
- "project/tests/Tests.csproj",
- "project/tests/Fixtures/Module.cs",
- "project/tests/Fixtures/SampleData.json",
- "project/tests/Fixtures/MockResponses.xml",
-
- "project/data/raw/dataset1.csv",
- "project/data/raw/dataset2.csv",
- "project/data/raw/dataset-[data]-{1}.csv",
- "project/data/processed/cleaned_data.csv",
- "project/data/processed/aggregated_results.json",
-
- "project/data/temp/temp_file1.tmp",
- "project/data/temp/temp_file2.tmp",
- "project/data/temp/ac/b2/34/2d/7e/temp_file2.tmp",
- "project/data/temp/hidden-folder/temp_1.tmp",
- "project/data/temp/hidden-folder/temp_2.tmp",
- "project/data/temp/hidden/temp_hidden3.dat",
- "project/data/temp/hidden/temp_hidden4.dat",
-
- "project/scripts/setup.p1",
- "project/scripts/deploy.ps1",
- "project/scripts/build.bat",
- "project/scripts/build.sh",
-
- "project/logs/app.log",
- "project/logs/error.log",
- "project/logs/archive/2019/01/app_2019-01.log",
- "project/logs/archive/2019/02/app_2019-02.log",
- "project/logs/archive/2019/03/app_2019-03.log",
-
- "project/config/production.json",
- "project/config/development.json",
- "project/config/test.json",
-
- "project/assets/images/logo.png",
- "project/assets/images/icon.svg",
- "project/assets/images/backgrounds/light.jpg",
- "project/assets/images/backgrounds/dark.jpeg",
-
- "project/assets/fonts/opensans.ttf",
- "project/assets/fonts/roboto.ttf",
- "project/assets/styles/main.css",
- "project/assets/styles/print.css",
-
- "project/packages/Ramstack.Globbing.2.1.0/lib/net60/Ramstack.Globbing.dll",
- "project/packages/Ramstack.Globbing.2.1.0/Ramstack.Globbing.2.1.0.nupkg",
-
- "project/.gitignore",
- "project/.editorconfig",
- "project/README.md",
- "project/global.json",
- "project/nuget.config",
- }
- .Select(p => Path.Combine(root, p))
- .ToArray();
-
- var directories = list
- .Select(p => Path.GetDirectoryName(p)!)
- .Distinct()
- .ToArray();
-
- foreach (var path in directories)
- Directory.CreateDirectory(path);
-
- foreach (var path in list)
- File.WriteAllText(path, $"Automatically generated for testing on {DateTime.Now:s}");
-
- var hiddenFolder = directories.First(p => p.Contains("hidden-folder"));
- File.SetAttributes(hiddenFolder, FileAttributes.Hidden);
-
- foreach (var hiddenFile in list.Where(p => p.Contains("temp_hidden")))
- File.SetAttributes(hiddenFile, FileAttributes.Hidden);
-
- Root = root;
- FileList = list;
- }
-
- public void Dispose() =>
- Directory.Delete(Root, true);
-}
+namespace Ramstack.Globbing.Traversal.Helpers;
+
+public sealed class TempFileStorage : IDisposable
+{
+ public string Root { get; }
+ public IReadOnlyList FileList { get; }
+
+ public TempFileStorage()
+ {
+ var root = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());
+ string[] files =
+ [
+ "project/docs/user_manual.pdf",
+ "project/docs/api_reference.md",
+ "project/docs/troubleshooting/common_issues.txt",
+ "project/docs/troubleshooting/faq.docx",
+
+ "project/docs_generated/html/index.html",
+ "project/docs_generated/html/api.html",
+ "project/docs_generated/pdf/documentation.pdf",
+
+ "project/src/App/App.csproj",
+ "project/src/App/Program.cs",
+ "project/src/App/Utils.cs",
+ "project/src/Modules/Module1/Module1.cs",
+ "project/src/Modules/Module1/Module1.csproj",
+ "project/src/Modules/Module1/Submodule/Submodule1.cs",
+ "project/src/Modules/Module1/Submodule/Submodule2.cs",
+ "project/src/Modules/Module1/Submodule/Submodule.csproj",
+ "project/src/Modules/Module2/Module2.cs",
+ "project/src/Modules/Module2/Module2.csproj",
+ "project/src/App.sln",
+
+ "project/tests/TestMain.cs",
+ "project/tests/TestUtils.cs",
+ "project/tests/Tests.csproj",
+ "project/tests/Fixtures/Module.cs",
+ "project/tests/Fixtures/SampleData.json",
+ "project/tests/Fixtures/MockResponses.xml",
+
+ "project/data/raw/dataset1.csv",
+ "project/data/raw/dataset2.csv",
+ "project/data/raw/dataset-[data]-{1}.csv",
+ "project/data/processed/cleaned_data.csv",
+ "project/data/processed/aggregated_results.json",
+
+ "project/data/temp/temp_file1.tmp",
+ "project/data/temp/temp_file2.tmp",
+ "project/data/temp/ac/b2/34/2d/7e/temp_file2.tmp",
+ "project/data/temp/hidden-folder/temp_1.tmp",
+ "project/data/temp/hidden-folder/temp_2.tmp",
+ "project/data/temp/hidden/temp_hidden3.dat",
+ "project/data/temp/hidden/temp_hidden4.dat",
+
+ "project/scripts/setup.p1",
+ "project/scripts/deploy.ps1",
+ "project/scripts/build.bat",
+ "project/scripts/build.sh",
+
+ "project/logs/app.log",
+ "project/logs/error.log",
+ "project/logs/archive/2019/01/app_2019-01.log",
+ "project/logs/archive/2019/02/app_2019-02.log",
+ "project/logs/archive/2019/03/app_2019-03.log",
+
+ "project/config/production.json",
+ "project/config/development.json",
+ "project/config/test.json",
+
+ "project/assets/images/logo.png",
+ "project/assets/images/icon.svg",
+ "project/assets/images/backgrounds/light.jpg",
+ "project/assets/images/backgrounds/dark.jpeg",
+
+ "project/assets/fonts/opensans.ttf",
+ "project/assets/fonts/roboto.ttf",
+ "project/assets/styles/main.css",
+ "project/assets/styles/print.css",
+
+ "project/packages/Ramstack.Globbing.2.1.0/lib/net60/Ramstack.Globbing.dll",
+ "project/packages/Ramstack.Globbing.2.1.0/Ramstack.Globbing.2.1.0.nupkg",
+
+ "project/.gitignore",
+ "project/.editorconfig",
+ "project/README.md",
+ "project/global.json",
+ "project/nuget.config",
+ ];
+
+ var list = files
+ .Select(p => Path.Combine(root, p))
+ .ToArray();
+
+ var directories = list
+ .Select(p => Path.GetDirectoryName(p)!)
+ .Distinct()
+ .ToArray();
+
+ foreach (var path in directories)
+ Directory.CreateDirectory(path);
+
+ foreach (var path in list)
+ File.WriteAllText(path, $"Automatically generated for testing on {DateTime.Now:s}");
+
+ var hiddenFolder = directories.First(p => p.Contains("hidden-folder"));
+ File.SetAttributes(hiddenFolder, FileAttributes.Hidden);
+
+ foreach (var hiddenFile in list.Where(p => p.Contains("temp_hidden")))
+ File.SetAttributes(hiddenFile, FileAttributes.Hidden);
+
+ Root = root;
+ FileList = list;
+ }
+
+ public void Dispose() =>
+ Directory.Delete(Root, true);
+}
diff --git a/Ramstack.Globbing.Tests/Traversal/PathHelperTests.Converting.cs b/Ramstack.Globbing.Tests/Traversal/PathHelperTests.Converting.cs
index 45f200e..39ed061 100644
--- a/Ramstack.Globbing.Tests/Traversal/PathHelperTests.Converting.cs
+++ b/Ramstack.Globbing.Tests/Traversal/PathHelperTests.Converting.cs
@@ -1,72 +1,72 @@
-using Ramstack.Globbing.Internal;
-
-namespace Ramstack.Globbing.Traversal;
-
-partial class PathHelperTests
-{
- [Test]
- public void ConvertPathToPosixStyle_NothingChange()
- {
- for (var n = 0; n < 512; n++)
- {
- var original = new string('\\', n + 16).ToCharArray().AsSpan();
- var span = original[8..^8];
- span.Fill('a');
-
- var expected = original.ToString();
- PathHelper.ConvertPathToPosixStyle(span);
-
- Assert.That(original.ToString(), Is.EqualTo(expected));
- }
- }
-
- [Test]
- public void ConvertPathToPosixStyle_ChangesAll()
- {
- for (var n = 0; n < 512; n++)
- {
- var original = new string('@', n + 16).ToCharArray().AsSpan();
- var span = original[8..^8];
- span.Fill('\\');
-
- var expected = original.ToString().Replace('\\', '/').Replace('@', '\\');
- PathHelper.ConvertPathToPosixStyle(span);
-
- Assert.That(original.ToString().Replace('@', '\\'), Is.EqualTo(expected));
- }
- }
-
- [Test]
- public void ConvertPathToPosixStyle_ForwardSlashes()
- {
- for (var n = 0; n < 512; n++)
- {
- var original = new string('@', n + 16).ToCharArray().AsSpan();
- var span = original[8..^8];
- span.Fill('/');
-
- var expected = original.ToString().Replace('\\', '/').Replace('@', '\\');
- PathHelper.ConvertPathToPosixStyle(span);
-
- Assert.That(original.ToString().Replace('@', '\\'), Is.EqualTo(expected));
- }
- }
-
- [Test]
- public void ConvertPathToPosixStyle_RareChanges()
- {
- for (var n = 0; n < 512; n++)
- {
- var original = new string('@', n + 16).ToCharArray().AsSpan();
- var span = original[8..^8];
- for (var i = 0; i < span.Length; i++)
- if (i % 7 == 0)
- span[i] = '\\';
-
- var expected = original.ToString().Replace('\\', '/').Replace('@', '\\');
- PathHelper.ConvertPathToPosixStyle(span);
-
- Assert.That(original.ToString().Replace('@', '\\'), Is.EqualTo(expected));
- }
- }
-}
+using Ramstack.Globbing.Internal;
+
+namespace Ramstack.Globbing.Traversal;
+
+partial class PathHelperTests
+{
+ [Test]
+ public void ConvertPathToPosixStyle_NothingChange()
+ {
+ for (var n = 0; n < 512; n++)
+ {
+ var original = new string('\\', n + 16).ToCharArray().AsSpan();
+ var span = original[8..^8];
+ span.Fill('a');
+
+ var expected = original.ToString();
+ PathHelper.ConvertPathToPosixStyle(span);
+
+ Assert.That(original.ToString(), Is.EqualTo(expected));
+ }
+ }
+
+ [Test]
+ public void ConvertPathToPosixStyle_ChangesAll()
+ {
+ for (var n = 0; n < 512; n++)
+ {
+ var original = new string('@', n + 16).ToCharArray().AsSpan();
+ var span = original[8..^8];
+ span.Fill('\\');
+
+ var expected = original.ToString().Replace('\\', '/').Replace('@', '\\');
+ PathHelper.ConvertPathToPosixStyle(span);
+
+ Assert.That(original.ToString().Replace('@', '\\'), Is.EqualTo(expected));
+ }
+ }
+
+ [Test]
+ public void ConvertPathToPosixStyle_ForwardSlashes()
+ {
+ for (var n = 0; n < 512; n++)
+ {
+ var original = new string('@', n + 16).ToCharArray().AsSpan();
+ var span = original[8..^8];
+ span.Fill('/');
+
+ var expected = original.ToString().Replace('\\', '/').Replace('@', '\\');
+ PathHelper.ConvertPathToPosixStyle(span);
+
+ Assert.That(original.ToString().Replace('@', '\\'), Is.EqualTo(expected));
+ }
+ }
+
+ [Test]
+ public void ConvertPathToPosixStyle_RareChanges()
+ {
+ for (var n = 0; n < 512; n++)
+ {
+ var original = new string('@', n + 16).ToCharArray().AsSpan();
+ var span = original[8..^8];
+ for (var i = 0; i < span.Length; i++)
+ if (i % 7 == 0)
+ span[i] = '\\';
+
+ var expected = original.ToString().Replace('\\', '/').Replace('@', '\\');
+ PathHelper.ConvertPathToPosixStyle(span);
+
+ Assert.That(original.ToString().Replace('@', '\\'), Is.EqualTo(expected));
+ }
+ }
+}
diff --git a/Ramstack.Globbing.Tests/Traversal/PathHelperTests.cs b/Ramstack.Globbing.Tests/Traversal/PathHelperTests.cs
index d452388..87eb520 100644
--- a/Ramstack.Globbing.Tests/Traversal/PathHelperTests.cs
+++ b/Ramstack.Globbing.Tests/Traversal/PathHelperTests.cs
@@ -1,198 +1,198 @@
-using Ramstack.Globbing.Internal;
-
-namespace Ramstack.Globbing.Traversal;
-
-[TestFixture]
-public partial class PathHelperTests
-{
- [TestCase("", 1)]
- [TestCase("//", 1)]
- [TestCase("/dir1", 1)]
- [TestCase("dir1", 1)]
- [TestCase("dir1/", 1)]
- [TestCase("/directory_1", 1)]
- [TestCase("directory_1", 1)]
- [TestCase("directory_1/", 1)]
- [TestCase("/dir1/dir2/", 2)]
- [TestCase("dir1/dir2", 2)]
- [TestCase("dir1/dir2/", 2)]
- [TestCase("///dir1/dir2////", 2)]
- [TestCase("/directory_1/directory_2/", 2)]
- [TestCase("directory_1/directory_2", 2)]
- [TestCase("directory_1/directory_2/", 2)]
- [TestCase("///directory_1/directory_2////", 2)]
- [TestCase("/1/2/3/4/5/6/project/src/tests", 9)]
- public void CountPathSegments(string path, int expected)
- {
- Assert.That(
- PathHelper.CountPathSegments(path, MatchFlags.Windows),
- Is.EqualTo(expected));
-
- Assert.That(
- PathHelper.CountPathSegments(path, MatchFlags.Unix),
- Is.EqualTo(expected));
-
- Assert.That(
- PathHelper.CountPathSegments(path.Replace('/', '\\'), MatchFlags.Windows),
- Is.EqualTo(expected));
- }
-
- [TestCase("/dir1/dir2/", 1, "/dir1")]
- [TestCase("/dir1/dir2/", 2, "/dir1/dir2")]
- [TestCase("/dir1/dir2/", 3, "/dir1/dir2/")]
- [TestCase("/dir1/dir2/", 9, "/dir1/dir2/")]
- [TestCase("dir1/dir2/", 1, "dir1")]
- [TestCase("dir1/dir2/", 2, "dir1/dir2")]
- [TestCase("dir1/dir2/", 3, "dir1/dir2/")]
- [TestCase("dir1/dir2/", 9, "dir1/dir2/")]
- [TestCase("dir1/dir2", 1, "dir1")]
- [TestCase("dir1/dir2", 2, "dir1/dir2")]
- [TestCase("dir1/dir2", 3, "dir1/dir2")]
- [TestCase("dir1/dir2", 9, "dir1/dir2")]
- [TestCase("/1/2/3/4/5/6/7/8/", 1, "/1")]
- [TestCase("/1/2/3/4/5/6/7/8/", 2, "/1/2")]
- [TestCase("/1/2/3/4/5/6/7/8/", 3, "/1/2/3")]
- [TestCase("/1/2/3/4/5/6/7/8/", 4, "/1/2/3/4")]
- [TestCase("/1/2/3/4/5/6/7/8/", 5, "/1/2/3/4/5")]
- [TestCase("/1/2/3/4/5/6/7/8/", 6, "/1/2/3/4/5/6")]
- [TestCase("/1/2/3/4/5/6/7/8/", 7, "/1/2/3/4/5/6/7")]
- [TestCase("/1/2/3/4/5/6/7/8/", 8, "/1/2/3/4/5/6/7/8")]
- [TestCase("/1/2/3/4/5/6/7/8/", 9, "/1/2/3/4/5/6/7/8/")]
- [TestCase("/1/2/3/4/5/6/7/8/", 10, "/1/2/3/4/5/6/7/8/")]
- [TestCase("", 1, "")]
- [TestCase("", 2, "")]
- [TestCase("", 3, "")]
- [TestCase("/", 1, "/")]
- [TestCase("/", 2, "/")]
- [TestCase("/", 3, "/")]
- [TestCase("////", 2, "////")]
- [TestCase("////dir1/dir2////", 1, "////dir1")]
- [TestCase("////dir1/dir2////", 2, "////dir1/dir2")]
- [TestCase("////dir1/dir2////", 3, "////dir1/dir2////")]
- [TestCase("**", 1, "**")]
- [TestCase("**", 2, "**")]
- [TestCase("**", 3, "**")]
- [TestCase("/**", 1, "/**")]
- [TestCase("/**", 2, "/**")]
- [TestCase("/**", 3, "/**")]
- [TestCase("**/", 1, "**")]
- [TestCase("**/", 2, "**")]
- [TestCase("**/", 3, "**")]
- [TestCase("/**/", 1, "/**")]
- [TestCase("/**/", 2, "/**")]
- [TestCase("/**/", 3, "/**")]
- [TestCase("**/dir1/dir2", 1, "**")]
- [TestCase("**/dir1/dir2", 2, "**")]
- [TestCase("**/dir1/dir2", 3, "**")]
- [TestCase("**/dir1/dir2", 4, "**")]
- [TestCase("/**/dir1/dir2", 1, "/**")]
- [TestCase("/**/dir1/dir2", 2, "/**")]
- [TestCase("/**/dir1/dir2", 3, "/**")]
- [TestCase("/**/dir1/dir2", 4, "/**")]
- [TestCase("**/long_directory_name_1/long_directory_name_2", 1, "**")]
- [TestCase("**/long_directory_name_1/long_directory_name_2", 2, "**")]
- [TestCase("**/long_directory_name_1/long_directory_name_2", 3, "**")]
- [TestCase("**/long_directory_name_1/long_directory_name_2", 4, "**")]
- [TestCase("/**/long_directory_name_1/long_directory_name_2", 1, "/**")]
- [TestCase("/**/long_directory_name_1/long_directory_name_2", 2, "/**")]
- [TestCase("/**/long_directory_name_1/long_directory_name_2", 3, "/**")]
- [TestCase("/**/long_directory_name_1/long_directory_name_2", 4, "/**")]
- [TestCase("dir1/**/dir2/dir3", 1, "dir1")]
- [TestCase("dir1/**/dir2/dir3", 2, "dir1/**")]
- [TestCase("dir1/**/dir2/dir3", 3, "dir1/**")]
- [TestCase("dir1/**/dir2/dir3", 4, "dir1/**")]
- [TestCase("long_directory_name_1/**/long_directory_name_2/long_directory_name_3", 1, "long_directory_name_1")]
- [TestCase("long_directory_name_1/**/long_directory_name_2/long_directory_name_3", 2, "long_directory_name_1/**")]
- [TestCase("long_directory_name_1/**/long_directory_name_2/long_directory_name_3", 3, "long_directory_name_1/**")]
- [TestCase("long_directory_name_1/**/long_directory_name_2/long_directory_name_3", 4, "long_directory_name_1/**")]
- public void GetPartialPattern(string path, int depth, string expected)
- {
- Assert.That(
- PathHelper.GetPartialPattern(path, MatchFlags.Windows, depth).ToString(),
- Is.EqualTo(expected));
-
- Assert.That(
- PathHelper.GetPartialPattern(path, MatchFlags.Unix, depth).ToString(),
- Is.EqualTo(expected));
-
- path = path.Replace('/', '\\');
- expected = expected.Replace('/', '\\');
-
- Assert.That(
- PathHelper.GetPartialPattern(path, MatchFlags.Windows, depth).ToString(),
- Is.EqualTo(expected));
- }
-
- [Test]
- public void CountPathSegments_Generated()
- {
- foreach (var (path, slash, f) in GeneratePaths())
- {
- var expected = Math.Max(1, path.Split(slash, StringSplitOptions.RemoveEmptyEntries).Length);
- var count = PathHelper.CountPathSegments(path, f);
-
- Assert.That(count, Is.EqualTo(expected));
- }
- }
-
- [Test]
- public void GetPartialPattern_Generated()
- {
- foreach (var (path, slash, f) in GeneratePaths().OrderBy(_ => Random.Shared.Next()).Take(500))
- {
- var count = PathHelper.CountPathSegments(path, f);
- for (var depth = 1; depth <= count * 2; depth++)
- {
- var result = PathHelper
- .GetPartialPattern(path, f, depth)
- .ToString()
- .Split(slash, StringSplitOptions.RemoveEmptyEntries);
-
- var expected = path
- .Split(slash, StringSplitOptions.RemoveEmptyEntries)
- .Take(depth);
-
- Assert.That(result, Is.EquivalentTo(expected));
- }
- }
- }
-
- private static IEnumerable<(string path, char slash, MatchFlags flags)> GeneratePaths()
- {
- var flags = new[]
- {
- ('/', MatchFlags.Unix),
- ('/', MatchFlags.Windows),
- ('\\', MatchFlags.Windows)
- };
-
- foreach (var (s, f) in flags)
- {
- for (var r = 1; r < 5; r++)
- for (var n = 1; n < 37; n++)
- {
- var slash = new string(s, r);
- var segments = new string[n];
-
- for (var l = 0; l < 43; l++)
- {
- segments.AsSpan().Fill(new string('a', l));
-
- var path = string.Join(slash, segments);
- for (var v = 0; v < 4; v++)
- {
- path = v switch
- {
- 0 => path,
- 1 => slash + path,
- 2 => slash + path + slash,
- _ => path + slash
- };
-
- yield return (path, s, f);
- }
- }
- }
- }
- }
-}
+using Ramstack.Globbing.Internal;
+
+namespace Ramstack.Globbing.Traversal;
+
+[TestFixture]
+public partial class PathHelperTests
+{
+ [TestCase("", 1)]
+ [TestCase("//", 1)]
+ [TestCase("/dir1", 1)]
+ [TestCase("dir1", 1)]
+ [TestCase("dir1/", 1)]
+ [TestCase("/directory_1", 1)]
+ [TestCase("directory_1", 1)]
+ [TestCase("directory_1/", 1)]
+ [TestCase("/dir1/dir2/", 2)]
+ [TestCase("dir1/dir2", 2)]
+ [TestCase("dir1/dir2/", 2)]
+ [TestCase("///dir1/dir2////", 2)]
+ [TestCase("/directory_1/directory_2/", 2)]
+ [TestCase("directory_1/directory_2", 2)]
+ [TestCase("directory_1/directory_2/", 2)]
+ [TestCase("///directory_1/directory_2////", 2)]
+ [TestCase("/1/2/3/4/5/6/project/src/tests", 9)]
+ public void CountPathSegments(string path, int expected)
+ {
+ Assert.That(
+ PathHelper.CountPathSegments(path, MatchFlags.Windows),
+ Is.EqualTo(expected));
+
+ Assert.That(
+ PathHelper.CountPathSegments(path, MatchFlags.Unix),
+ Is.EqualTo(expected));
+
+ Assert.That(
+ PathHelper.CountPathSegments(path.Replace('/', '\\'), MatchFlags.Windows),
+ Is.EqualTo(expected));
+ }
+
+ [TestCase("/dir1/dir2/", 1, "/dir1")]
+ [TestCase("/dir1/dir2/", 2, "/dir1/dir2")]
+ [TestCase("/dir1/dir2/", 3, "/dir1/dir2/")]
+ [TestCase("/dir1/dir2/", 9, "/dir1/dir2/")]
+ [TestCase("dir1/dir2/", 1, "dir1")]
+ [TestCase("dir1/dir2/", 2, "dir1/dir2")]
+ [TestCase("dir1/dir2/", 3, "dir1/dir2/")]
+ [TestCase("dir1/dir2/", 9, "dir1/dir2/")]
+ [TestCase("dir1/dir2", 1, "dir1")]
+ [TestCase("dir1/dir2", 2, "dir1/dir2")]
+ [TestCase("dir1/dir2", 3, "dir1/dir2")]
+ [TestCase("dir1/dir2", 9, "dir1/dir2")]
+ [TestCase("/1/2/3/4/5/6/7/8/", 1, "/1")]
+ [TestCase("/1/2/3/4/5/6/7/8/", 2, "/1/2")]
+ [TestCase("/1/2/3/4/5/6/7/8/", 3, "/1/2/3")]
+ [TestCase("/1/2/3/4/5/6/7/8/", 4, "/1/2/3/4")]
+ [TestCase("/1/2/3/4/5/6/7/8/", 5, "/1/2/3/4/5")]
+ [TestCase("/1/2/3/4/5/6/7/8/", 6, "/1/2/3/4/5/6")]
+ [TestCase("/1/2/3/4/5/6/7/8/", 7, "/1/2/3/4/5/6/7")]
+ [TestCase("/1/2/3/4/5/6/7/8/", 8, "/1/2/3/4/5/6/7/8")]
+ [TestCase("/1/2/3/4/5/6/7/8/", 9, "/1/2/3/4/5/6/7/8/")]
+ [TestCase("/1/2/3/4/5/6/7/8/", 10, "/1/2/3/4/5/6/7/8/")]
+ [TestCase("", 1, "")]
+ [TestCase("", 2, "")]
+ [TestCase("", 3, "")]
+ [TestCase("/", 1, "/")]
+ [TestCase("/", 2, "/")]
+ [TestCase("/", 3, "/")]
+ [TestCase("////", 2, "////")]
+ [TestCase("////dir1/dir2////", 1, "////dir1")]
+ [TestCase("////dir1/dir2////", 2, "////dir1/dir2")]
+ [TestCase("////dir1/dir2////", 3, "////dir1/dir2////")]
+ [TestCase("**", 1, "**")]
+ [TestCase("**", 2, "**")]
+ [TestCase("**", 3, "**")]
+ [TestCase("/**", 1, "/**")]
+ [TestCase("/**", 2, "/**")]
+ [TestCase("/**", 3, "/**")]
+ [TestCase("**/", 1, "**")]
+ [TestCase("**/", 2, "**")]
+ [TestCase("**/", 3, "**")]
+ [TestCase("/**/", 1, "/**")]
+ [TestCase("/**/", 2, "/**")]
+ [TestCase("/**/", 3, "/**")]
+ [TestCase("**/dir1/dir2", 1, "**")]
+ [TestCase("**/dir1/dir2", 2, "**")]
+ [TestCase("**/dir1/dir2", 3, "**")]
+ [TestCase("**/dir1/dir2", 4, "**")]
+ [TestCase("/**/dir1/dir2", 1, "/**")]
+ [TestCase("/**/dir1/dir2", 2, "/**")]
+ [TestCase("/**/dir1/dir2", 3, "/**")]
+ [TestCase("/**/dir1/dir2", 4, "/**")]
+ [TestCase("**/long_directory_name_1/long_directory_name_2", 1, "**")]
+ [TestCase("**/long_directory_name_1/long_directory_name_2", 2, "**")]
+ [TestCase("**/long_directory_name_1/long_directory_name_2", 3, "**")]
+ [TestCase("**/long_directory_name_1/long_directory_name_2", 4, "**")]
+ [TestCase("/**/long_directory_name_1/long_directory_name_2", 1, "/**")]
+ [TestCase("/**/long_directory_name_1/long_directory_name_2", 2, "/**")]
+ [TestCase("/**/long_directory_name_1/long_directory_name_2", 3, "/**")]
+ [TestCase("/**/long_directory_name_1/long_directory_name_2", 4, "/**")]
+ [TestCase("dir1/**/dir2/dir3", 1, "dir1")]
+ [TestCase("dir1/**/dir2/dir3", 2, "dir1/**")]
+ [TestCase("dir1/**/dir2/dir3", 3, "dir1/**")]
+ [TestCase("dir1/**/dir2/dir3", 4, "dir1/**")]
+ [TestCase("long_directory_name_1/**/long_directory_name_2/long_directory_name_3", 1, "long_directory_name_1")]
+ [TestCase("long_directory_name_1/**/long_directory_name_2/long_directory_name_3", 2, "long_directory_name_1/**")]
+ [TestCase("long_directory_name_1/**/long_directory_name_2/long_directory_name_3", 3, "long_directory_name_1/**")]
+ [TestCase("long_directory_name_1/**/long_directory_name_2/long_directory_name_3", 4, "long_directory_name_1/**")]
+ public void GetPartialPattern(string path, int depth, string expected)
+ {
+ Assert.That(
+ PathHelper.GetPartialPattern(path, MatchFlags.Windows, depth).ToString(),
+ Is.EqualTo(expected));
+
+ Assert.That(
+ PathHelper.GetPartialPattern(path, MatchFlags.Unix, depth).ToString(),
+ Is.EqualTo(expected));
+
+ path = path.Replace('/', '\\');
+ expected = expected.Replace('/', '\\');
+
+ Assert.That(
+ PathHelper.GetPartialPattern(path, MatchFlags.Windows, depth).ToString(),
+ Is.EqualTo(expected));
+ }
+
+ [Test]
+ public void CountPathSegments_Generated()
+ {
+ foreach (var (path, slash, f) in GeneratePaths())
+ {
+ var expected = Math.Max(1, path.Split(slash, StringSplitOptions.RemoveEmptyEntries).Length);
+ var count = PathHelper.CountPathSegments(path, f);
+
+ Assert.That(count, Is.EqualTo(expected));
+ }
+ }
+
+ [Test]
+ public void GetPartialPattern_Generated()
+ {
+ foreach (var (path, slash, f) in GeneratePaths().OrderBy(_ => Random.Shared.Next()).Take(500))
+ {
+ var count = PathHelper.CountPathSegments(path, f);
+ for (var depth = 1; depth <= count * 2; depth++)
+ {
+ var result = PathHelper
+ .GetPartialPattern(path, f, depth)
+ .ToString()
+ .Split(slash, StringSplitOptions.RemoveEmptyEntries);
+
+ var expected = path
+ .Split(slash, StringSplitOptions.RemoveEmptyEntries)
+ .Take(depth);
+
+ Assert.That(result, Is.EquivalentTo(expected));
+ }
+ }
+ }
+
+ private static IEnumerable<(string path, char slash, MatchFlags flags)> GeneratePaths()
+ {
+ var flags = new[]
+ {
+ ('/', MatchFlags.Unix),
+ ('/', MatchFlags.Windows),
+ ('\\', MatchFlags.Windows)
+ };
+
+ foreach (var (s, f) in flags)
+ {
+ for (var r = 1; r < 5; r++)
+ for (var n = 1; n < 37; n++)
+ {
+ var slash = new string(s, r);
+ var segments = new string[n];
+
+ for (var l = 0; l < 43; l++)
+ {
+ segments.AsSpan().Fill(new string('a', l));
+
+ var path = string.Join(slash, segments);
+ for (var v = 0; v < 4; v++)
+ {
+ path = v switch
+ {
+ 0 => path,
+ 1 => slash + path,
+ 2 => slash + path + slash,
+ _ => path + slash
+ };
+
+ yield return (path, s, f);
+ }
+ }
+ }
+ }
+ }
+}
diff --git a/Ramstack.Globbing/Internal/FileTreeHelper.cs b/Ramstack.Globbing/Internal/FileTreeHelper.cs
index 1ff5fb1..b92e786 100644
--- a/Ramstack.Globbing/Internal/FileTreeHelper.cs
+++ b/Ramstack.Globbing/Internal/FileTreeHelper.cs
@@ -1,43 +1,43 @@
-using System.Buffers;
-
-namespace Ramstack.Globbing.Internal;
-
-///
-/// Provides helper methods for file tree operations.
-///
-internal static class FileTreeHelper
-{
- ///
- /// Constructs the full name of a file by combining the path and the name.
- ///
- /// A buffer used for constructing the full name.
- /// It should be obtained from an array pool and will be resized if necessary.
- /// The path of the file.
- /// The name of the file.
- ///
- /// A representing the full name of the file.
- ///
- public static ReadOnlySpan GetFullName(ref char[] chars, string path, string name)
- {
- var array = chars;
- var count = path.Length + name.Length + 1;
-
- if (array.Length < count)
- {
- ArrayPool.Shared.Return(array);
- array = ArrayPool.Shared.Rent(count);
- chars = array;
-
- // Force null check to assist JIT
- _ = array.Length;
- }
-
- var fullName = array.AsSpan();
-
- path.TryCopyTo(fullName);
- fullName[path.Length] = '/';
- name.TryCopyTo(fullName.Slice(path.Length + 1));
-
- return fullName.Slice(0, count);
- }
-}
+using System.Buffers;
+
+namespace Ramstack.Globbing.Internal;
+
+///
+/// Provides helper methods for file tree operations.
+///
+internal static class FileTreeHelper
+{
+ ///
+ /// Constructs the full name of a file by combining the path and the name.
+ ///
+ /// A buffer used for constructing the full name.
+ /// It should be obtained from an array pool and will be resized if necessary.
+ /// The path of the file.
+ /// The name of the file.
+ ///
+ /// A representing the full name of the file.
+ ///
+ public static ReadOnlySpan GetFullName(ref char[] chars, string path, string name)
+ {
+ var array = chars;
+ var count = path.Length + name.Length + 1;
+
+ if (array.Length < count)
+ {
+ ArrayPool.Shared.Return(array);
+ array = ArrayPool.Shared.Rent(count);
+ chars = array;
+
+ // Force null check to assist JIT
+ _ = array.Length;
+ }
+
+ var fullName = array.AsSpan();
+
+ path.TryCopyTo(fullName);
+ fullName[path.Length] = '/';
+ name.TryCopyTo(fullName.Slice(path.Length + 1));
+
+ return fullName.Slice(0, count);
+ }
+}
diff --git a/Ramstack.Globbing/Internal/PathHelper.cs b/Ramstack.Globbing/Internal/PathHelper.cs
index 33b1aa7..69fd863 100644
--- a/Ramstack.Globbing/Internal/PathHelper.cs
+++ b/Ramstack.Globbing/Internal/PathHelper.cs
@@ -1,530 +1,530 @@
-using System.Diagnostics;
-using System.Diagnostics.CodeAnalysis;
-using System.Numerics;
-using System.Runtime.CompilerServices;
-using System.Runtime.InteropServices;
-using System.Runtime.Intrinsics;
-using System.Runtime.Intrinsics.Arm;
-using System.Runtime.Intrinsics.X86;
-
-namespace Ramstack.Globbing.Internal;
-
-///
-/// Provides helper methods for path manipulations.
-///
-[SuppressMessage("Usage", "IDE0004:Remove Unnecessary Cast")]
-[SuppressMessage("ReSharper", "RedundantCast")]
-internal static class PathHelper
-{
- ///
- /// Determines whether the specified path matches any of the specified patterns.
- ///
- /// The path to match for a match.
- /// An array of patterns to match against the path.
- /// The matching options to use.
- /// This parameter must be explicitly set to either or .
- /// is not allowed and will result in an assertion failure.
- ///
- /// if the path matches any of the patterns;
- /// otherwise, .
- ///
- public static bool IsMatch(ReadOnlySpan path, string[] patterns, MatchFlags flags)
- {
- Debug.Assert(flags != MatchFlags.Auto);
-
- foreach (var pattern in patterns)
- if (Matcher.IsMatch(path, pattern, flags))
- return true;
-
- return false;
- }
-
- ///
- /// Determines whether the specified path partially matches any of the specified patterns.
- ///
- /// The path to be partially matched.
- /// An array of patterns to match against the path.
- /// The matching options to use.
- /// This parameter must be explicitly set to either or .
- /// is not allowed and will result in an assertion failure.
- ///
- /// if the path partially matches any of the patterns;
- /// otherwise, .
- ///
- public static bool IsPartialMatch(ReadOnlySpan path, string[] patterns, MatchFlags flags)
- {
- Debug.Assert(flags != MatchFlags.Auto);
-
- var count = CountPathSegments(path, flags);
-
- foreach (var pattern in patterns)
- if (Matcher.IsMatch(path, GetPartialPattern(pattern, flags, count), flags))
- return true;
-
- return false;
- }
-
- ///
- /// Counts the number of segments in the specified path.
- ///
- /// The path to count segments for.
- /// The flags indicating the type of path separators to match.
- /// This parameter must be explicitly set to either or .
- /// is not allowed and will result in an assertion failure.
- ///
- /// The number of segments in the path.
- ///
- public static int CountPathSegments(scoped ReadOnlySpan path, MatchFlags flags)
- {
- Debug.Assert(flags != MatchFlags.Auto);
-
- var count = 0;
- var iterator = new PathSegmentIterator();
- ref var s = ref Unsafe.AsRef(in MemoryMarshal.GetReference(path));
- var length = path.Length;
-
- while (true)
- {
- var r = iterator.GetNext(ref s, length, flags);
-
- if (r.start != r.final)
- count++;
-
- if (r.final == length)
- break;
- }
-
- if (count == 0)
- count = 1;
-
- return count;
- }
-
- ///
- /// Returns a partial pattern from the specified pattern string based on the specified depth.
- ///
- /// The pattern string to extract from.
- /// The flags indicating the type of path separators to match.
- /// This parameter must be explicitly set to either or .
- /// is not allowed and will result in an assertion failure.
- /// The depth level to extract the partial pattern up to.
- ///
- /// A representing the partial pattern.
- ///
- public static ReadOnlySpan GetPartialPattern(string pattern, MatchFlags flags, int depth)
- {
- Debug.Assert(flags != MatchFlags.Auto);
- Debug.Assert(depth >= 1);
-
- if (depth < 1)
- depth = 1;
-
- var iterator = new PathSegmentIterator();
- ref var s = ref Unsafe.AsRef(in pattern.GetPinnableReference());
- var length = pattern.Length;
-
- while (true)
- {
- var r = iterator.GetNext(ref s, length, flags);
- if (r.start != r.final)
- depth--;
-
- if (depth < 1
- || r.final == length
- || IsGlobStar(ref s, r.start, r.final))
- return MemoryMarshal.CreateReadOnlySpan(ref s, r.final);
- }
-
- [MethodImpl(MethodImplOptions.AggressiveInlining)]
- static bool IsGlobStar(ref char s, int index, int final) =>
- index + 2 == final && Unsafe.ReadUnaligned(
- ref Unsafe.As(
- ref Unsafe.Add(ref s, (nint)(uint)index))) == ('*' << 16 | '*');
- }
-
- ///
- /// Converts path separators in the specified span to the Unix style (/).
- ///
- /// The path to convert.
- public static void ConvertPathToPosixStyle(Span path)
- {
- var length = (nint)(uint)path.Length;
- ref var reference = ref MemoryMarshal.GetReference(path);
- ConvertPathToPosixStyleImpl(ref reference, length);
-
- static void ConvertPathToPosixStyleImpl(ref char p, nint length)
- {
- var i = (nint)0;
-
- // The main reason for using our own implementation is that the method
- // Replace(this Span span, char oldValue, char newValue) is only available
- // starting from .NET 8. Since we need to support earlier versions of .NET,
- // we are using our own implementation.
-
- if (Sse41.IsSupported && length >= Vector128.Count)
- {
- Vector128 value;
- Vector128 mask;
- Vector128 result;
-
- var slash = Vector128.Create((ushort)'/');
- var backslash = Vector128.Create((ushort)'\\');
- var tail = length - Vector128.Count;
-
- // +------+------+------+------+------+------+---+ DATA
- // +------+ TAIL
- //
- // After the main loop, only one final vector operation
- // is needed for the 'tail' block.
-
- do
- {
- value = LoadVector128(ref p, i);
- mask = Sse2.CompareEqual(value, backslash);
- result = Sse41.BlendVariable(value, slash, mask);
- WriteVector128(ref p, i, result);
-
- i += Vector128.Count;
- }
- while (i < tail);
-
- //
- // Process remaining chars
- // NOTE: An extra one write for the 'length == Vector128.Count'
- //
-
- value = LoadVector128(ref p, tail);
- mask = Sse2.CompareEqual(value, backslash);
- result = Sse41.BlendVariable(value, slash, mask);
- WriteVector128(ref p, tail, result);
- }
- else if (AdvSimd.IsSupported && length >= Vector128.Count)
- {
- Vector128 value;
- Vector128 mask;
- Vector128 result;
-
- var slash = Vector128.Create((ushort)'/');
- var backslash = Vector128.Create((ushort)'\\');
- var tail = length - Vector128.Count;
-
- do
- {
- value = LoadVector128(ref p, i);
- mask = AdvSimd.CompareEqual(value, backslash);
- result = AdvSimd.BitwiseSelect(mask, slash, value);
- WriteVector128(ref p, i, result);
-
- i += Vector128.Count;
- }
- while (i < tail);
-
- //
- // Process remaining chars
- // NOTE: An extra one write for the 'length == Vector128.Count'
- //
- value = LoadVector128(ref p, tail);
- mask = AdvSimd.CompareEqual(value, backslash);
- result = AdvSimd.BitwiseSelect(mask, slash, value);
- WriteVector128(ref p, tail, result);
- }
- else
- {
- for (; i < length; i++)
- if (Unsafe.Add(ref p, i) == '\\')
- Unsafe.Add(ref p, i) = '/';
- }
- }
- }
-
- #region Vector helper methods
-
- ///
- /// Creates a 256-bit bitmask that allows escaping characters based on the specified flags.
- ///
- /// The flags indicating the type of path separators to match.
- /// This parameter must be explicitly set to either or .
- /// is not allowed and will result in an assertion failure.
- ///
- /// A 256-bit bitmask for escaping characters.
- ///
- private static Vector256 CreateBackslash256Bitmask(MatchFlags flags)
- {
- Debug.Assert(flags != MatchFlags.Auto);
-
- var mask = Vector256.Zero;
- if (flags == MatchFlags.Windows)
- mask = Vector256.AllBitsSet;
-
- return mask;
- }
-
- ///
- /// Creates a 128-bit bitmask that allows escaping characters based on the specified flags.
- ///
- /// The flags indicating the type of path separators to match.
- /// This parameter must be explicitly set to either or .
- /// is not allowed and will result in an assertion failure.
- ///
- /// A 128-bit bitmask for escaping characters.
- ///
- private static Vector128 CreateBackslash128Bitmask(MatchFlags flags)
- {
- Debug.Assert(flags != MatchFlags.Auto);
-
- var mask = Vector128.Zero;
- if (flags == MatchFlags.Windows)
- mask = Vector128.AllBitsSet;
-
- return mask;
- }
-
- ///
- /// Loads a 256-bit vector from the specified source.
- ///
- /// The source from which the vector will be loaded.
- /// The offset from source from which the vector will be loaded.
- ///
- /// The loaded 256-bit vector.
- ///
- [MethodImpl(MethodImplOptions.AggressiveInlining)]
- private static Vector256 LoadVector256(ref char source, nint offset) =>
- Unsafe.ReadUnaligned>(
- ref Unsafe.As(ref Unsafe.Add(ref source, offset)));
-
- ///
- /// Loads a 128-bit vector from the specified source.
- ///
- /// The source from which the vector will be loaded.
- /// The offset from source from which the vector will be loaded.
- ///
- /// The loaded 128-bit vector.
- ///
- [MethodImpl(MethodImplOptions.AggressiveInlining)]
- private static Vector128 LoadVector128(ref char source, nint offset) =>
- Unsafe.ReadUnaligned>(
- ref Unsafe.As(
- ref Unsafe.Add(ref source, offset)));
-
- ///
- /// Stores a 128-bit vector at the specified destination.
- ///
- /// The destination at which the vector will be stored.
- /// The element offset from destination from which the vector will be stored.
- /// The vector that will be stored.
- [MethodImpl(MethodImplOptions.AggressiveInlining)]
- private static void WriteVector128(ref char destination, nint offset, Vector128 value) =>
- Unsafe.WriteUnaligned(
- ref Unsafe.As(ref Unsafe.Add(ref destination, offset)),
- value);
-
- #endregion
-
- #region Inner type: PathSegmentIterator
-
- ///
- /// Provides functionality to iterate over segments of a path.
- ///
- private struct PathSegmentIterator
- {
- private int _last;
- private nint _position;
- private uint _mask;
-
- ///
- /// Initializes a new instance of the structure.
- ///
- [MethodImpl(MethodImplOptions.AggressiveInlining)]
- public PathSegmentIterator() =>
- _last = -1;
-
- ///
- /// Retrieves the next segment of the path.
- ///
- /// A reference to the starting character of the path.
- /// The total number of characters in the input path starting from .
- /// The flags indicating the type of path separators to match.
- ///
- /// A tuple containing the start and end indices of the next path segment.
- /// start indicates the beginning of the segment, and final satisfies
- /// the condition that final - start equals the length of the segment.
- /// The end of the iteration is indicated by final being equal to the length of the path.
- ///
- [MethodImpl(MethodImplOptions.AggressiveInlining)]
- public (int start, int final) GetNext(ref char source, int length, MatchFlags flags)
- {
- var start = _last + 1;
-
- while ((int)_position < length)
- {
- if ((Avx2.IsSupported || Sse2.IsSupported || AdvSimd.Arm64.IsSupported) && _mask != 0)
- {
- var offset = BitOperations.TrailingZeroCount(_mask);
- if (AdvSimd.IsSupported)
- {
- //
- // On ARM, ExtractMostSignificantBits returns a mask where each bit
- // represents one vector element (1 bit per ushort), so offset
- // directly corresponds to the element index
- //
- _last = (int)(_position + (nint)(uint)offset);
-
- //
- // Clear the bits for the current separator
- //
- _mask &= ~(1u << offset);
- }
- else
- {
- //
- // On x86, MoveMask (and ExtractMostSignificantBits on byte-based vectors)
- // returns a mask where each bit represents one byte (2 bits per ushort),
- // so we need to divide offset by 2 to get the actual element index
- //
- _last = (int)(_position + (nint)((uint)offset >> 1));
-
- //
- // Clear the bits for the current separator
- //
- _mask &= ~(0b_11u << offset);
- }
-
- //
- // Advance position to the next chunk when no separators remain in the mask
- //
- if (_mask == 0)
- {
- //
- // https://github.com/dotnet/runtime/issues/117416
- //
- // Precompute the stride size instead of calculating it inline
- // to avoid stack spilling. For some unknown reason, the JIT
- // fails to optimize properly when this is written inline, like so:
- // _position += Avx2.IsSupported
- // ? Vector256.Count
- // : Vector128.Count;
- //
-
- var stride = Avx2.IsSupported
- ? Vector256.Count
- : Vector128.Count;
-
- _position += stride;
- }
-
- return (start, _last);
- }
-
- if (Avx2.IsSupported && (int)_position + Vector256.Count <= length)
- {
- var chunk = LoadVector256(ref source, _position);
- var backslashMask = CreateBackslash256Bitmask(flags);
- var slash = Vector256.Create((ushort)'/');
- var backslash = Vector256.Create((ushort)'\\');
-
- var comparison = Avx2.Or(
- Avx2.CompareEqual(chunk, slash),
- Avx2.And(
- backslashMask,
- Avx2.CompareEqual(chunk, backslash)));
-
- //
- // Store the comparison bitmask and reuse it across iterations
- // as long as it contains non-zero bits.
- // This avoids reloading SIMD registers and repeating comparisons
- // on the same chunk of data.
- //
- _mask = (uint)Avx2.MoveMask(comparison.AsByte());
-
- //
- // Advance position to the next chunk when no separators found
- //
- if (_mask == 0)
- _position += Vector256.Count;
- }
- else if (Sse2.IsSupported && !Avx2.IsSupported && (int)_position + Vector128.Count <= length)
- {
- var chunk = LoadVector128(ref source, _position);
- var backslashMask = CreateBackslash128Bitmask(flags);
- var slash = Vector128.Create((ushort)'/');
- var backslash = Vector128.Create((ushort)'\\');
-
- var comparison = Sse2.Or(
- Sse2.CompareEqual(chunk, slash),
- Sse2.And(
- backslashMask,
- Sse2.CompareEqual(chunk, backslash)));
-
- //
- // Store the comparison bitmask and reuse it across iterations
- // as long as it contains non-zero bits.
- // This avoids reloading SIMD registers and repeating comparisons
- // on the same chunk of data.
- //
- _mask = (uint)Sse2.MoveMask(comparison.AsByte());
-
- //
- // Advance position to the next chunk when no separators found
- //
- if (_mask == 0)
- _position += Vector128.Count;
- }
- else if (AdvSimd.Arm64.IsSupported && (int)_position + Vector128.Count <= length)
- {
- var chunk = LoadVector128(ref source, _position);
- var backslashMask = CreateBackslash128Bitmask(flags);
- var slash = Vector128.Create((ushort)'/');
- var backslash = Vector128.Create((ushort)'\\');
-
- var comparison = AdvSimd.Or(
- AdvSimd.CompareEqual(chunk, slash),
- AdvSimd.And(
- backslashMask,
- AdvSimd.CompareEqual(chunk, backslash)));
-
- //
- // Store the comparison bitmask and reuse it across iterations
- // as long as it contains non-zero bits.
- // This avoids reloading SIMD registers and repeating comparisons
- // on the same chunk of data.
- //
- _mask = ExtractMostSignificantBits(comparison);
-
- //
- // Advance position to the next chunk when no separators found
- //
- if (_mask == 0)
- _position += Vector128.Count;
-
- [MethodImpl(MethodImplOptions.AggressiveInlining)]
- static uint ExtractMostSignificantBits(Vector128 v)
- {
- var sum = AdvSimd.Arm64.AddAcross(
- AdvSimd.ShiftLogical(
- AdvSimd.And(v, Vector128.Create((ushort)0x8000)),
- Vector128.Create((short)-15, -14, -13, -12, -11, -10, -9, -8)));
- return sum.ToScalar();
- }
- }
- else
- {
- for (; (int)_position < length; _position++)
- {
- var ch = Unsafe.Add(ref source, _position);
- if (ch == '/' || (ch == '\\' && flags == MatchFlags.Windows))
- {
- _last = (int)_position;
- _position++;
-
- return (start, _last);
- }
- }
- }
- }
-
- return (start, length);
- }
- }
-
- #endregion
-}
+using System.Diagnostics;
+using System.Diagnostics.CodeAnalysis;
+using System.Numerics;
+using System.Runtime.CompilerServices;
+using System.Runtime.InteropServices;
+using System.Runtime.Intrinsics;
+using System.Runtime.Intrinsics.Arm;
+using System.Runtime.Intrinsics.X86;
+
+namespace Ramstack.Globbing.Internal;
+
+///
+/// Provides helper methods for path manipulations.
+///
+[SuppressMessage("Usage", "IDE0004:Remove Unnecessary Cast")]
+[SuppressMessage("ReSharper", "RedundantCast")]
+internal static class PathHelper
+{
+ ///
+ /// Determines whether the specified path matches any of the specified patterns.
+ ///
+ /// The path to match for a match.
+ /// An array of patterns to match against the path.
+ /// The matching options to use.
+ /// This parameter must be explicitly set to either or .
+ /// is not allowed and will result in an assertion failure.
+ ///
+ /// if the path matches any of the patterns;
+ /// otherwise, .
+ ///
+ public static bool IsMatch(ReadOnlySpan path, string[] patterns, MatchFlags flags)
+ {
+ Debug.Assert(flags != MatchFlags.Auto);
+
+ foreach (var pattern in patterns)
+ if (Matcher.IsMatch(path, pattern, flags))
+ return true;
+
+ return false;
+ }
+
+ ///
+ /// Determines whether the specified path partially matches any of the specified patterns.
+ ///
+ /// The path to be partially matched.
+ /// An array of patterns to match against the path.
+ /// The matching options to use.
+ /// This parameter must be explicitly set to either or .
+ /// is not allowed and will result in an assertion failure.
+ ///
+ /// if the path partially matches any of the patterns;
+ /// otherwise, .
+ ///
+ public static bool IsPartialMatch(ReadOnlySpan path, string[] patterns, MatchFlags flags)
+ {
+ Debug.Assert(flags != MatchFlags.Auto);
+
+ var count = CountPathSegments(path, flags);
+
+ foreach (var pattern in patterns)
+ if (Matcher.IsMatch(path, GetPartialPattern(pattern, flags, count), flags))
+ return true;
+
+ return false;
+ }
+
+ ///
+ /// Counts the number of segments in the specified path.
+ ///
+ /// The path to count segments for.
+ /// The flags indicating the type of path separators to match.
+ /// This parameter must be explicitly set to either or .
+ /// is not allowed and will result in an assertion failure.
+ ///
+ /// The number of segments in the path.
+ ///
+ public static int CountPathSegments(scoped ReadOnlySpan path, MatchFlags flags)
+ {
+ Debug.Assert(flags != MatchFlags.Auto);
+
+ var count = 0;
+ var iterator = new PathSegmentIterator();
+ ref var s = ref Unsafe.AsRef(in MemoryMarshal.GetReference(path));
+ var length = path.Length;
+
+ while (true)
+ {
+ var r = iterator.GetNext(ref s, length, flags);
+
+ if (r.start != r.final)
+ count++;
+
+ if (r.final == length)
+ break;
+ }
+
+ if (count == 0)
+ count = 1;
+
+ return count;
+ }
+
+ ///
+ /// Returns a partial pattern from the specified pattern string based on the specified depth.
+ ///
+ /// The pattern string to extract from.
+ /// The flags indicating the type of path separators to match.
+ /// This parameter must be explicitly set to either or .
+ /// is not allowed and will result in an assertion failure.
+ /// The depth level to extract the partial pattern up to.
+ ///
+ /// A representing the partial pattern.
+ ///
+ public static ReadOnlySpan GetPartialPattern(string pattern, MatchFlags flags, int depth)
+ {
+ Debug.Assert(flags != MatchFlags.Auto);
+ Debug.Assert(depth >= 1);
+
+ if (depth < 1)
+ depth = 1;
+
+ var iterator = new PathSegmentIterator();
+ ref var s = ref Unsafe.AsRef(in pattern.GetPinnableReference());
+ var length = pattern.Length;
+
+ while (true)
+ {
+ var r = iterator.GetNext(ref s, length, flags);
+ if (r.start != r.final)
+ depth--;
+
+ if (depth < 1
+ || r.final == length
+ || IsGlobStar(ref s, r.start, r.final))
+ return MemoryMarshal.CreateReadOnlySpan(ref s, r.final);
+ }
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ static bool IsGlobStar(ref char s, int index, int final) =>
+ index + 2 == final && Unsafe.ReadUnaligned(
+ ref Unsafe.As(
+ ref Unsafe.Add(ref s, (nint)(uint)index))) == ('*' << 16 | '*');
+ }
+
+ ///
+ /// Converts path separators in the specified span to the Unix style (/).
+ ///
+ /// The path to convert.
+ public static void ConvertPathToPosixStyle(Span path)
+ {
+ var length = (nint)(uint)path.Length;
+ ref var reference = ref MemoryMarshal.GetReference(path);
+ ConvertPathToPosixStyleImpl(ref reference, length);
+
+ static void ConvertPathToPosixStyleImpl(ref char p, nint length)
+ {
+ var i = (nint)0;
+
+ // The main reason for using our own implementation is that the method
+ // Replace(this Span span, char oldValue, char newValue) is only available
+ // starting from .NET 8. Since we need to support earlier versions of .NET,
+ // we are using our own implementation.
+
+ if (Sse41.IsSupported && length >= Vector128.Count)
+ {
+ Vector128 value;
+ Vector128 mask;
+ Vector128 result;
+
+ var slash = Vector128.Create((ushort)'/');
+ var backslash = Vector128.Create((ushort)'\\');
+ var tail = length - Vector128.Count;
+
+ // +------+------+------+------+------+------+---+ DATA
+ // +------+ TAIL
+ //
+ // After the main loop, only one final vector operation
+ // is needed for the 'tail' block.
+
+ do
+ {
+ value = LoadVector128(ref p, i);
+ mask = Sse2.CompareEqual(value, backslash);
+ result = Sse41.BlendVariable(value, slash, mask);
+ WriteVector128(ref p, i, result);
+
+ i += Vector128.Count;
+ }
+ while (i < tail);
+
+ //
+ // Process remaining chars
+ // NOTE: An extra one write for the 'length == Vector128.Count'
+ //
+
+ value = LoadVector128(ref p, tail);
+ mask = Sse2.CompareEqual(value, backslash);
+ result = Sse41.BlendVariable(value, slash, mask);
+ WriteVector128(ref p, tail, result);
+ }
+ else if (AdvSimd.IsSupported && length >= Vector128.Count)
+ {
+ Vector128 value;
+ Vector128 mask;
+ Vector128 result;
+
+ var slash = Vector128.Create((ushort)'/');
+ var backslash = Vector128.Create((ushort)'\\');
+ var tail = length - Vector128.Count;
+
+ do
+ {
+ value = LoadVector128(ref p, i);
+ mask = AdvSimd.CompareEqual(value, backslash);
+ result = AdvSimd.BitwiseSelect(mask, slash, value);
+ WriteVector128(ref p, i, result);
+
+ i += Vector128.Count;
+ }
+ while (i < tail);
+
+ //
+ // Process remaining chars
+ // NOTE: An extra one write for the 'length == Vector128.Count'
+ //
+ value = LoadVector128(ref p, tail);
+ mask = AdvSimd.CompareEqual(value, backslash);
+ result = AdvSimd.BitwiseSelect(mask, slash, value);
+ WriteVector128(ref p, tail, result);
+ }
+ else
+ {
+ for (; i < length; i++)
+ if (Unsafe.Add(ref p, i) == '\\')
+ Unsafe.Add(ref p, i) = '/';
+ }
+ }
+ }
+
+ #region Vector helper methods
+
+ ///
+ /// Creates a 256-bit bitmask that allows escaping characters based on the specified flags.
+ ///
+ /// The flags indicating the type of path separators to match.
+ /// This parameter must be explicitly set to either or .
+ /// is not allowed and will result in an assertion failure.
+ ///
+ /// A 256-bit bitmask for escaping characters.
+ ///
+ private static Vector256 CreateBackslash256Bitmask(MatchFlags flags)
+ {
+ Debug.Assert(flags != MatchFlags.Auto);
+
+ var mask = Vector256.Zero;
+ if (flags == MatchFlags.Windows)
+ mask = Vector256.AllBitsSet;
+
+ return mask;
+ }
+
+ ///
+ /// Creates a 128-bit bitmask that allows escaping characters based on the specified flags.
+ ///
+ /// The flags indicating the type of path separators to match.
+ /// This parameter must be explicitly set to either or .
+ /// is not allowed and will result in an assertion failure.
+ ///
+ /// A 128-bit bitmask for escaping characters.
+ ///
+ private static Vector128 CreateBackslash128Bitmask(MatchFlags flags)
+ {
+ Debug.Assert(flags != MatchFlags.Auto);
+
+ var mask = Vector128.Zero;
+ if (flags == MatchFlags.Windows)
+ mask = Vector128.AllBitsSet;
+
+ return mask;
+ }
+
+ ///
+ /// Loads a 256-bit vector from the specified source.
+ ///
+ /// The source from which the vector will be loaded.
+ /// The offset from source from which the vector will be loaded.
+ ///
+ /// The loaded 256-bit vector.
+ ///
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ private static Vector256 LoadVector256(ref char source, nint offset) =>
+ Unsafe.ReadUnaligned>(
+ ref Unsafe.As(ref Unsafe.Add(ref source, offset)));
+
+ ///
+ /// Loads a 128-bit vector from the specified source.
+ ///
+ /// The source from which the vector will be loaded.
+ /// The offset from source from which the vector will be loaded.
+ ///
+ /// The loaded 128-bit vector.
+ ///
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ private static Vector128 LoadVector128(ref char source, nint offset) =>
+ Unsafe.ReadUnaligned>(
+ ref Unsafe.As(
+ ref Unsafe.Add(ref source, offset)));
+
+ ///
+ /// Stores a 128-bit vector at the specified destination.
+ ///
+ /// The destination at which the vector will be stored.
+ /// The element offset from destination from which the vector will be stored.
+ /// The vector that will be stored.
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ private static void WriteVector128(ref char destination, nint offset, Vector128 value) =>
+ Unsafe.WriteUnaligned(
+ ref Unsafe.As(ref Unsafe.Add(ref destination, offset)),
+ value);
+
+ #endregion
+
+ #region Inner type: PathSegmentIterator
+
+ ///
+ /// Provides functionality to iterate over segments of a path.
+ ///
+ private struct PathSegmentIterator
+ {
+ private int _last;
+ private nint _position;
+ private uint _mask;
+
+ ///
+ /// Initializes a new instance of the structure.
+ ///
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public PathSegmentIterator() =>
+ _last = -1;
+
+ ///
+ /// Retrieves the next segment of the path.
+ ///
+ /// A reference to the starting character of the path.
+ /// The total number of characters in the input path starting from .
+ /// The flags indicating the type of path separators to match.
+ ///
+ /// A tuple containing the start and end indices of the next path segment.
+ /// start indicates the beginning of the segment, and final satisfies
+ /// the condition that final - start equals the length of the segment.
+ /// The end of the iteration is indicated by final being equal to the length of the path.
+ ///
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public (int start, int final) GetNext(ref char source, int length, MatchFlags flags)
+ {
+ var start = _last + 1;
+
+ while ((int)_position < length)
+ {
+ if ((Avx2.IsSupported || Sse2.IsSupported || AdvSimd.Arm64.IsSupported) && _mask != 0)
+ {
+ var offset = BitOperations.TrailingZeroCount(_mask);
+ if (AdvSimd.IsSupported)
+ {
+ //
+ // On ARM, ExtractMostSignificantBits returns a mask where each bit
+ // represents one vector element (1 bit per ushort), so offset
+ // directly corresponds to the element index
+ //
+ _last = (int)(_position + (nint)(uint)offset);
+
+ //
+ // Clear the bits for the current separator
+ //
+ _mask &= ~(1u << offset);
+ }
+ else
+ {
+ //
+ // On x86, MoveMask (and ExtractMostSignificantBits on byte-based vectors)
+ // returns a mask where each bit represents one byte (2 bits per ushort),
+ // so we need to divide offset by 2 to get the actual element index
+ //
+ _last = (int)(_position + (nint)((uint)offset >> 1));
+
+ //
+ // Clear the bits for the current separator
+ //
+ _mask &= ~(0b_11u << offset);
+ }
+
+ //
+ // Advance position to the next chunk when no separators remain in the mask
+ //
+ if (_mask == 0)
+ {
+ //
+ // https://github.com/dotnet/runtime/issues/117416
+ //
+ // Precompute the stride size instead of calculating it inline
+ // to avoid stack spilling. For some unknown reason, the JIT
+ // fails to optimize properly when this is written inline, like so:
+ // _position += Avx2.IsSupported
+ // ? Vector256.Count
+ // : Vector128.Count;
+ //
+
+ var stride = Avx2.IsSupported
+ ? Vector256.Count
+ : Vector128.Count;
+
+ _position += stride;
+ }
+
+ return (start, _last);
+ }
+
+ if (Avx2.IsSupported && (int)_position + Vector256.Count <= length)
+ {
+ var chunk = LoadVector256(ref source, _position);
+ var backslashMask = CreateBackslash256Bitmask(flags);
+ var slash = Vector256.Create((ushort)'/');
+ var backslash = Vector256.Create((ushort)'\\');
+
+ var comparison = Avx2.Or(
+ Avx2.CompareEqual(chunk, slash),
+ Avx2.And(
+ backslashMask,
+ Avx2.CompareEqual(chunk, backslash)));
+
+ //
+ // Store the comparison bitmask and reuse it across iterations
+ // as long as it contains non-zero bits.
+ // This avoids reloading SIMD registers and repeating comparisons
+ // on the same chunk of data.
+ //
+ _mask = (uint)Avx2.MoveMask(comparison.AsByte());
+
+ //
+ // Advance position to the next chunk when no separators found
+ //
+ if (_mask == 0)
+ _position += Vector256.Count;
+ }
+ else if (Sse2.IsSupported && !Avx2.IsSupported && (int)_position + Vector128.Count <= length)
+ {
+ var chunk = LoadVector128(ref source, _position);
+ var backslashMask = CreateBackslash128Bitmask(flags);
+ var slash = Vector128.Create((ushort)'/');
+ var backslash = Vector128.Create((ushort)'\\');
+
+ var comparison = Sse2.Or(
+ Sse2.CompareEqual(chunk, slash),
+ Sse2.And(
+ backslashMask,
+ Sse2.CompareEqual(chunk, backslash)));
+
+ //
+ // Store the comparison bitmask and reuse it across iterations
+ // as long as it contains non-zero bits.
+ // This avoids reloading SIMD registers and repeating comparisons
+ // on the same chunk of data.
+ //
+ _mask = (uint)Sse2.MoveMask(comparison.AsByte());
+
+ //
+ // Advance position to the next chunk when no separators found
+ //
+ if (_mask == 0)
+ _position += Vector128.Count;
+ }
+ else if (AdvSimd.Arm64.IsSupported && (int)_position + Vector128.Count <= length)
+ {
+ var chunk = LoadVector128(ref source, _position);
+ var backslashMask = CreateBackslash128Bitmask(flags);
+ var slash = Vector128.Create((ushort)'/');
+ var backslash = Vector128.Create((ushort)'\\');
+
+ var comparison = AdvSimd.Or(
+ AdvSimd.CompareEqual(chunk, slash),
+ AdvSimd.And(
+ backslashMask,
+ AdvSimd.CompareEqual(chunk, backslash)));
+
+ //
+ // Store the comparison bitmask and reuse it across iterations
+ // as long as it contains non-zero bits.
+ // This avoids reloading SIMD registers and repeating comparisons
+ // on the same chunk of data.
+ //
+ _mask = ExtractMostSignificantBits(comparison);
+
+ //
+ // Advance position to the next chunk when no separators found
+ //
+ if (_mask == 0)
+ _position += Vector128.Count;
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ static uint ExtractMostSignificantBits(Vector128 v)
+ {
+ var sum = AdvSimd.Arm64.AddAcross(
+ AdvSimd.ShiftLogical(
+ AdvSimd.And(v, Vector128.Create((ushort)0x8000)),
+ Vector128.Create((short)-15, -14, -13, -12, -11, -10, -9, -8)));
+ return sum.ToScalar();
+ }
+ }
+ else
+ {
+ for (; (int)_position < length; _position++)
+ {
+ var ch = Unsafe.Add(ref source, _position);
+ if (ch == '/' || (ch == '\\' && flags == MatchFlags.Windows))
+ {
+ _last = (int)_position;
+ _position++;
+
+ return (start, _last);
+ }
+ }
+ }
+ }
+
+ return (start, length);
+ }
+ }
+
+ #endregion
+}
diff --git a/Ramstack.Globbing/MatchFlags.cs b/Ramstack.Globbing/MatchFlags.cs
index 9189baa..6335bcd 100644
--- a/Ramstack.Globbing/MatchFlags.cs
+++ b/Ramstack.Globbing/MatchFlags.cs
@@ -1,26 +1,30 @@
-namespace Ramstack.Globbing;
-
-///
-/// Defines flags that control the behavior of the glob matching process.
-///
-public enum MatchFlags
-{
- ///
- /// Automatically determines whether to treat backslashes (\) as escape sequences
- /// or path separators based on the platform's separator convention.
- ///
- Auto,
-
- ///
- /// Treats backslashes (\) as path separators instead of escape sequences.
- /// This flag provides behavior consistent with Windows-style paths.
- /// Both backslashes (\) and forward (/) slashes are considered as path separators in this mode.
- ///
- Windows = 2,
-
- ///
- /// Treats backslashes \ as escape sequences, allowing for special character escaping.
- /// This flag provides behavior consistent with Unix-style paths.
- ///
- Unix = 4
-}
+using System.Diagnostics.CodeAnalysis;
+
+namespace Ramstack.Globbing;
+
+///
+/// Defines flags that control the behavior of the glob matching process.
+///
+[SuppressMessage("Naming", "CA1711:Identifiers should not have incorrect suffix",
+ Justification = "Renaming the public enum would break the public API.")]
+public enum MatchFlags
+{
+ ///
+ /// Automatically determines whether to treat backslashes (\) as escape sequences
+ /// or path separators based on the platform's separator convention.
+ ///
+ Auto,
+
+ ///
+ /// Treats backslashes (\) as path separators instead of escape sequences.
+ /// This flag provides behavior consistent with Windows-style paths.
+ /// Both backslashes (\) and forward (/) slashes are considered as path separators in this mode.
+ ///
+ Windows = 2,
+
+ ///
+ /// Treats backslashes \ as escape sequences, allowing for special character escaping.
+ /// This flag provides behavior consistent with Unix-style paths.
+ ///
+ Unix = 4
+}
diff --git a/Ramstack.Globbing/Matcher.cs b/Ramstack.Globbing/Matcher.cs
index ac6a6a8..8cb8939 100644
--- a/Ramstack.Globbing/Matcher.cs
+++ b/Ramstack.Globbing/Matcher.cs
@@ -1,571 +1,571 @@
-using System.Diagnostics;
-using System.Runtime.CompilerServices;
-using System.Runtime.InteropServices;
-
-using Ramstack.Globbing.Internal;
-
-namespace Ramstack.Globbing;
-
-///
-/// Provides functionality for shell-style glob matching using the glob pattern syntax.
-///
-///
-///
-/// -
-///
-/// Supported meta-characters include '*', '?', '\' and '[', ']'.
-/// And inside character classes '-', '!' and ']'.
-///
-///
-/// -
-///
-/// The '.' and '..' symbols do not have any special treatment and are processed
-/// as regular characters for matching.
-///
-///
-/// -
-///
-/// Character classes can be negated by prefixing them with '!', such as [!0-9],
-/// which matches all characters except digits.
-///
-///
-/// -
-///
-/// Brace patterns are supported, including nested brace pattern:
-/// {file,dir,name}, {file-1.{c,cpp},file-2.{cs,f}}
-///
-///
-/// -
-///
-/// An empty pattern in brace expansion {} is allowed, as well as variations
-/// like {.cs,}, {name,,file}, or {,.cs}.
-///
-///
-/// -
-/// Leading and trailing separators are ignored.
-///
-/// -
-/// Consecutive separators are counted as one.
-///
-/// -
-///
-/// The '**' sequence in the glob pattern can be used to match zero or more directories and subdirectories.
-/// It can be used at the beginning, middle, or end of a pattern, for example,
-/// "**/file.txt", "dir/**/*.txt", "dir/**".
-///
-///
-///
-///
-public static unsafe class Matcher
-{
- ///
- /// Represents a marker structure used to indicate that the '\' character
- /// should be treated as an escape character in the context of glob pattern processing.
- /// This enables the JIT compiler to generate optimized versions of functions
- /// for different options, enhancing performance.
- ///
- private readonly struct Unix;
-
- ///
- /// Represents a marker structure used to indicate that the escape character '\'
- /// should not be treated as an escape character, but as a path separator instead,
- /// in the context of glob pattern processing.
- /// This enables the JIT compiler to generate optimized versions of functions
- /// for different options, enhancing performance.
- ///
- private readonly struct Windows;
-
- ///
- /// Determines whether the glob pattern matches the specified path, using the specified matching options.
- ///
- ///
- ///
- /// -
- /// Leading and trailing path separators are ignored.
- ///
- /// -
- /// Consecutive path separators are counted as one.
- ///
- /// -
- ///
- /// The '**' sequence in the can be used to match zero or more directories and subdirectories.
- /// It can be used at the beginning, middle, or end of a pattern, for example, "**/file.txt", "dir/**/*.txt", "dir/**".
- ///
- ///
- ///
- ///
- /// The path to test for a match.
- /// The glob pattern to match against the path.
- /// The matching options to use. Default is .
- ///
- /// if the pattern matches the path; otherwise, .
- ///
- [MethodImpl(MethodImplOptions.AggressiveInlining)]
- public static bool IsMatch(string path, string pattern, MatchFlags flags = MatchFlags.Auto)
- {
- _ = path.Length;
- _ = pattern.Length;
-
- return IsMatch(path.AsSpan(), pattern.AsSpan(), flags);
- }
-
- ///
- /// Determines whether the glob pattern matches the specified path, using the specified matching options.
- ///
- ///
- ///
- /// -
- /// Leading and trailing path separators are ignored.
- ///
- /// -
- /// Consecutive path separators are counted as one.
- ///
- /// -
- ///
- /// The '**' sequence in the can be used to match zero or more directories and subdirectories.
- /// It can be used at the beginning, middle, or end of a pattern, for example, "**/file.txt", "dir/**/*.txt", "dir/**".
- ///
- ///
- ///
- ///
- /// The path to test for a match.
- /// The glob pattern to match against the path.
- /// The matching options to use. Default is .
- ///
- /// if the pattern matches the path; otherwise, .
- ///
- [MethodImpl(MethodImplOptions.AggressiveInlining)]
- public static bool IsMatch(scoped ReadOnlySpan path, scoped ReadOnlySpan pattern, MatchFlags flags = MatchFlags.Auto)
- {
- Debug.Assert((int)MatchFlags.Auto == 0);
- Debug.Assert((int)MatchFlags.Windows == 2);
- Debug.Assert((int)MatchFlags.Unix == 4);
-
- if (Path.DirectorySeparatorChar == '\\' ? ((int)flags & (int)~MatchFlags.Windows) == 0 : flags == MatchFlags.Windows)
- {
- return IsMatchImpl(
- ref MemoryMarshal.GetReference(path),
- path.Length,
- ref MemoryMarshal.GetReference(pattern),
- pattern.Length);
- }
-
- return IsMatchImpl(
- ref MemoryMarshal.GetReference(path),
- path.Length,
- ref MemoryMarshal.GetReference(pattern),
- pattern.Length);
-
- [MethodImpl(MethodImplOptions.NoInlining)]
- static bool IsMatchImpl(ref char rv, int vlen, ref char rp, int plen)
- {
- // An empty span may be backed by a null reference (default, ReadOnlySpan.Empty).
- // Since null is used internally as the "no match" result, it must never be
- // the end-of-path pointer, so an empty path is redirected to a valid location.
- if (vlen == 0)
- rv = ref MemoryMarshal.GetReference(string.Empty.AsSpan());
-
- fixed (char* v = &rv, p = &rp)
- {
- var vend = v + (uint)vlen;
- var pend = p + (uint)plen;
-
- return DoMatch(p, pend, v, vend) == vend;
- }
- }
-
- // Advances the pointer past any slash characters
- [MethodImpl(MethodImplOptions.AggressiveInlining)]
- static char* SkipSlash(char* p, char* pend)
- {
- while (p < pend && (p[0] == '/' || typeof(TFlags) == typeof(Windows) && p[0] == '\\'))
- p++;
-
- return p;
- }
-
- [MethodImpl(MethodImplOptions.AggressiveInlining)]
- static char* FindNextSlash(char* p, char* pend)
- {
- var r = typeof(TFlags) == typeof(Windows)
- ? MemoryHelper.IndexOfAny(p, pend, '/', '\\')
- : MemoryHelper.IndexOf(p, pend, '/');
-
- if (r >= 0)
- return p + (uint)r;
-
- return pend;
- }
-
- [MethodImpl(MethodImplOptions.NoInlining)]
- static char* DoMatch(char* p, char* pend, char* v, char* vend)
- {
- var level = 0;
-
- p = SkipSlash(p, pend);
- v = SkipSlash(v, vend);
-
- while (p < pend && v <= vend)
- {
- var pe = FindNextSlash(p, pend);
-
- // In both systems (little-endian and big-endian), *(int*)"**" is 0x002A002A.
- //
- // 1. In UTF-16, the character '*' (asterisk) has the code 0x002A.
- // 2. In memory, "**" will be represented as a sequence of two 16-bit values: 0x002A and 0x002A.
- //
- // 3. * In little-endian systems: 2A 00 2A 00
- // * In big-endian systems: 00 2A 00 2A
- //
- // 4. When we interpret these 4 bytes as an `int`, we get:
- // * In little-endian: 0x002A002A (bytes are read from right to left)
- // * In big-endian: 0x002A002A (bytes are read from left to right)
- //
- // Thus, despite the different byte order in memory, the numeric value interpreted
- // as an `int` turns out to be the same in both cases.
- //
- // This occurs because:
- // - Each '*' character occupies exactly 2 bytes in UTF-16.
- // - The value of each character (0x002A) is symmetrical with respect to byte order.
- if (p + 2 == pe && Unsafe.ReadUnaligned(p) == ('*' << 16 | '*'))
- {
- p = SkipSlash(pe, pend);
-
- // short-circuit
- // match found if "**" is the last segment in the pattern
- if (p == pend)
- return vend;
-
- do
- {
- var r = DoMatch(p, pend, v, vend);
- if (r != null)
- return r;
-
- // try to match the next segment
- v = FindNextSlash(v, vend);
- v = SkipSlash(v, vend);
- }
- while (v < vend);
-
- // abort recursion
- return (char*)-1;
- }
-
- var ve = FindNextSlash(v, vend);
-
- // 1. At the root level (level == 0), an empty path segment is valid,
- // which can be represented by patterns like "*".
- // 2. At any deeper level (level > 0), an empty segment indicates that a required directory or file is missing,
- // making the path invalid for patterns expecting something at that level.
- //
- // For example
- // Pattern: "*/*" and path: "a" - This pattern requires at least one directory level, so "a" is not a match.
- // Pattern: "*/{,b}" and path: "a" - Similarly, this pattern requires a directory or a specific file ("b")
- // at the next level, so "a" doesn't match.
- //
- // This means that the patterns "*/{}" and "*/{,}" cannot match any path due to the rule:
- // an empty segment is not allowed beyond the root level.
- //
- // So, the check (v == ve && level != 0) ensures that empty segments are only acceptable at the root level.
- // If an empty segment is found at a deeper level, the function returns null to indicate no match.
- if (v == ve && level != 0)
- return null;
-
- if (DoMatchSegment(p, pe, v, ve, subpattern: 0) != ve)
- return null;
-
- p = SkipSlash(pe, pend);
- v = SkipSlash(ve, vend);
-
- level++;
- }
-
- if (p == pend && v == vend)
- return vend;
-
- return null;
- }
- }
-
- private static char* DoMatchSegment(char* p, char* pend, char* v, char* vend, int subpattern)
- {
- while (p < pend && v < vend)
- {
- switch (p[0])
- {
- case '[':
- {
- var inverse = false;
- var matched = false;
-
- // Malformed
- if (++p >= pend)
- return null;
-
- if (p[0] == '!')
- {
- inverse = true;
-
- // Malformed
- if (++p >= pend)
- return null;
- }
-
- var a = p[0];
-
- do
- {
- // Malformed
- if (++p >= pend)
- return null;
-
- var b = a;
-
- if (p[0] == '-' && p + 1 < pend && p[1] != ']')
- {
- b = p[1];
-
- // Malformed
- if ((p += 2) >= pend)
- return null;
- }
-
- matched |= a <= v[0] & v[0] <= b;
-
- a = p[0];
-
- } while (a != ']');
-
- if (matched == inverse)
- return null;
-
- p++;
- v++;
- break;
- }
-
- case '{':
- {
- var e = ExtractPattern(p, pend);
- if (e == null)
- return null;
-
- v = MatchSubpattern(p, e, v, vend);
- if (v == null)
- return null;
-
- p = e;
- break;
- }
-
- case '*':
- {
- // *** => *
- // Treats consecutive stars as one
- // ReSharper disable once RedundantJumpStatement
- while (++p < pend && p[0] == '*')
- continue;
-
- // Trailing '*' matches everything
- if (p == pend)
- return vend;
-
- // OPTIMIZATION:
- // Try to identify a fast-forward opportunity after '*' by inspecting the next pattern character.
- // If the next character is a plain literal (not a wildcard or special construct),
- // we can skip naive backtracking and jump directly to its next occurrence in the input.
- //
- // This reduces the number of recursive calls by skipping intermediate positions
- // that cannot possibly match, effectively replacing blind linear backtracking
- // with a guided search.
- //
- // For non-literal tokens ('?', '[', '{', '\'), we fall back to the original behavior
- // to preserve correctness.
-
- // Note: '*' is intentionally not included here, as consecutive '*' are collapsed above,
- // so the next pattern character is guaranteed not to be '*'.
- const long Mask =
- 1L << ('?' - 63) | // 63
- 1L << ('[' - 63) | // 91
- 1L << ('\\' - 63) | // 92
- 1L << ('{' - 63); // 123
-
- var lookup = p[0] - 63;
-
- while (true)
- {
- if ((uint)lookup > 60 || ((1L << lookup) & Mask) == 0)
- {
- var n = MemoryHelper.IndexOf(v, vend, p[0]);
- if (n < 0)
- {
- v = vend;
- break;
- }
-
- v += (uint)n;
- }
-
- var r = DoMatchSegment(p, pend, v, vend, subpattern);
- if (r != null)
- return r;
-
- if (++v >= vend)
- break;
- }
-
- // OPTIMIZATION:
- // Aborting recursion when failing
- //
- // To prevent quadratic behavior in scenarios like the pattern "a*a*a*a*c"
- // matching against the text "aaaaaaaaaaaaaaa", we use <-1> as a return
- // value instead of .
- //
- // This optimization prevents each star-loop from running to the end of the text.
- // Because only the last star-loop needs to iterate to the end of the text
- // since advancing the previous star-loops wouldn't yield positive results
- // upon the failure of the last star-loop.
- if (p >= pend || p[0] != '{')
- return (char*)-1;
-
- break;
- }
-
- case '\\':
- {
- // Invalid escape sequence
- if (++p >= pend)
- return null;
-
- // The escaped character is always compared literally,
- // so an escaped '?' must not act as a wildcard.
- if (p[0] != v[0])
- return null;
-
- p++;
- v++;
- break;
- }
-
- default:
- {
- if (p[0] != v[0] && p[0] != '?')
- return null;
-
- p++;
- v++;
- break;
- }
- }
- }
-
- if (v == vend)
- {
- // Check if the remaining pattern can match an empty string:
- // - Trailing stars (*) can match zero or more characters, including an empty string.
- // - Brace patterns ({},{a,}) can include alternatives that match an empty string.
- while (p < pend)
- {
- if (p[0] == '*')
- {
- p++;
- }
- else if (p[0] == '{')
- {
- var se = ExtractPattern(p, pend);
- if (MatchSubpattern(p, se, v, v) != v)
- return null;
-
- p = se;
- }
- else
- {
- return null;
- }
- }
-
- return v;
- }
-
- if (p == pend && subpattern != 0)
- return v;
-
- return null;
- }
-
- [MethodImpl(MethodImplOptions.AggressiveInlining)]
- private static char* MatchSubpattern(char* p, char* pend, char* v, char* vend)
- {
- var last = (char*)0;
-
- while (p < pend && p[0] != '}')
- {
- var e = ExtractSubpattern(p, pend);
- var r = DoMatchSegment(p + 1, e, v, vend, subpattern: 1);
-
- // (char*)-1 is the star-loop abort signal. For an alternative it only means
- // that this particular alternative doesn't match, so it must not win here:
- // as an unsigned address it is greater than any valid pointer.
- if (r > last && r != (char*)-1)
- last = r;
-
- p = e;
- }
-
- return last;
-
- [MethodImpl(MethodImplOptions.AggressiveInlining)]
- static char* ExtractSubpattern(char* p, char* pend)
- {
- Debug.Assert(p[0] is ',' or '{');
-
- var depth = 1;
-
- while (++p < pend)
- {
- var c = p[0];
- if (c == ',' && depth == 1 || c == '}' && --depth == 0)
- break;
-
- if (c == '{')
- {
- depth++;
- }
- else if (c == '\\')
- {
- p++;
- }
- }
-
- return p;
- }
- }
-
- [MethodImpl(MethodImplOptions.AggressiveInlining)]
- private static char* ExtractPattern(char* p, char* pend)
- {
- Debug.Assert(p[0] == '{');
-
- var depth = 1;
-
- while (++p < pend)
- {
- var c = p[0];
- if (c == '}' && --depth == 0)
- return p + 1;
-
- if (c == '{')
- {
- depth++;
- }
- else if (c == '\\')
- {
- p++;
- }
- }
-
- // Malformed
- return null;
- }
-}
+using System.Diagnostics;
+using System.Runtime.CompilerServices;
+using System.Runtime.InteropServices;
+
+using Ramstack.Globbing.Internal;
+
+namespace Ramstack.Globbing;
+
+///
+/// Provides functionality for shell-style glob matching using the glob pattern syntax.
+///
+///
+///
+/// -
+///
+/// Supported meta-characters include '*', '?', '\' and '[', ']'.
+/// And inside character classes '-', '!' and ']'.
+///
+///
+/// -
+///
+/// The '.' and '..' symbols do not have any special treatment and are processed
+/// as regular characters for matching.
+///
+///
+/// -
+///
+/// Character classes can be negated by prefixing them with '!', such as [!0-9],
+/// which matches all characters except digits.
+///
+///
+/// -
+///
+/// Brace patterns are supported, including nested brace pattern:
+/// {file,dir,name}, {file-1.{c,cpp},file-2.{cs,f}}
+///
+///
+/// -
+///
+/// An empty pattern in brace expansion {} is allowed, as well as variations
+/// like {.cs,}, {name,,file}, or {,.cs}.
+///
+///
+/// -
+/// Leading and trailing separators are ignored.
+///
+/// -
+/// Consecutive separators are counted as one.
+///
+/// -
+///
+/// The '**' sequence in the glob pattern can be used to match zero or more directories and subdirectories.
+/// It can be used at the beginning, middle, or end of a pattern, for example,
+/// "**/file.txt", "dir/**/*.txt", "dir/**".
+///
+///
+///
+///
+public static unsafe class Matcher
+{
+ ///
+ /// Represents a marker structure used to indicate that the '\' character
+ /// should be treated as an escape character in the context of glob pattern processing.
+ /// This enables the JIT compiler to generate optimized versions of functions
+ /// for different options, enhancing performance.
+ ///
+ private readonly struct Unix;
+
+ ///
+ /// Represents a marker structure used to indicate that the escape character '\'
+ /// should not be treated as an escape character, but as a path separator instead,
+ /// in the context of glob pattern processing.
+ /// This enables the JIT compiler to generate optimized versions of functions
+ /// for different options, enhancing performance.
+ ///
+ private readonly struct Windows;
+
+ ///
+ /// Determines whether the glob pattern matches the specified path, using the specified matching options.
+ ///
+ ///
+ ///
+ /// -
+ /// Leading and trailing path separators are ignored.
+ ///
+ /// -
+ /// Consecutive path separators are counted as one.
+ ///
+ /// -
+ ///
+ /// The '**' sequence in the can be used to match zero or more directories and subdirectories.
+ /// It can be used at the beginning, middle, or end of a pattern, for example, "**/file.txt", "dir/**/*.txt", "dir/**".
+ ///
+ ///
+ ///
+ ///
+ /// The path to test for a match.
+ /// The glob pattern to match against the path.
+ /// The matching options to use. Default is .
+ ///
+ /// if the pattern matches the path; otherwise, .
+ ///
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static bool IsMatch(string path, string pattern, MatchFlags flags = MatchFlags.Auto)
+ {
+ _ = path.Length;
+ _ = pattern.Length;
+
+ return IsMatch(path.AsSpan(), pattern.AsSpan(), flags);
+ }
+
+ ///
+ /// Determines whether the glob pattern matches the specified path, using the specified matching options.
+ ///
+ ///
+ ///
+ /// -
+ /// Leading and trailing path separators are ignored.
+ ///
+ /// -
+ /// Consecutive path separators are counted as one.
+ ///
+ /// -
+ ///
+ /// The '**' sequence in the can be used to match zero or more directories and subdirectories.
+ /// It can be used at the beginning, middle, or end of a pattern, for example, "**/file.txt", "dir/**/*.txt", "dir/**".
+ ///
+ ///
+ ///
+ ///
+ /// The path to test for a match.
+ /// The glob pattern to match against the path.
+ /// The matching options to use. Default is .
+ ///
+ /// if the pattern matches the path; otherwise, .
+ ///
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static bool IsMatch(scoped ReadOnlySpan path, scoped ReadOnlySpan pattern, MatchFlags flags = MatchFlags.Auto)
+ {
+ Debug.Assert((int)MatchFlags.Auto == 0);
+ Debug.Assert((int)MatchFlags.Windows == 2);
+ Debug.Assert((int)MatchFlags.Unix == 4);
+
+ if (Path.DirectorySeparatorChar == '\\' ? ((int)flags & (int)~MatchFlags.Windows) == 0 : flags == MatchFlags.Windows)
+ {
+ return IsMatchImpl(
+ ref MemoryMarshal.GetReference(path),
+ path.Length,
+ ref MemoryMarshal.GetReference(pattern),
+ pattern.Length);
+ }
+
+ return IsMatchImpl(
+ ref MemoryMarshal.GetReference(path),
+ path.Length,
+ ref MemoryMarshal.GetReference(pattern),
+ pattern.Length);
+
+ [MethodImpl(MethodImplOptions.NoInlining)]
+ static bool IsMatchImpl(ref char rv, int vlen, ref char rp, int plen)
+ {
+ // An empty span may be backed by a null reference (default, ReadOnlySpan.Empty).
+ // Since null is used internally as the "no match" result, it must never be
+ // the end-of-path pointer, so an empty path is redirected to a valid location.
+ if (vlen == 0)
+ rv = ref MemoryMarshal.GetReference(string.Empty.AsSpan());
+
+ fixed (char* v = &rv, p = &rp)
+ {
+ var vend = v + (uint)vlen;
+ var pend = p + (uint)plen;
+
+ return DoMatch(p, pend, v, vend) == vend;
+ }
+ }
+
+ // Advances the pointer past any slash characters
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ static char* SkipSlash(char* p, char* pend)
+ {
+ while (p < pend && (p[0] == '/' || typeof(TFlags) == typeof(Windows) && p[0] == '\\'))
+ p++;
+
+ return p;
+ }
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ static char* FindNextSlash(char* p, char* pend)
+ {
+ var r = typeof(TFlags) == typeof(Windows)
+ ? MemoryHelper.IndexOfAny(p, pend, '/', '\\')
+ : MemoryHelper.IndexOf(p, pend, '/');
+
+ if (r >= 0)
+ return p + (uint)r;
+
+ return pend;
+ }
+
+ [MethodImpl(MethodImplOptions.NoInlining)]
+ static char* DoMatch(char* p, char* pend, char* v, char* vend)
+ {
+ var level = 0;
+
+ p = SkipSlash(p, pend);
+ v = SkipSlash(v, vend);
+
+ while (p < pend && v <= vend)
+ {
+ var pe = FindNextSlash(p, pend);
+
+ // In both systems (little-endian and big-endian), *(int*)"**" is 0x002A002A.
+ //
+ // 1. In UTF-16, the character '*' (asterisk) has the code 0x002A.
+ // 2. In memory, "**" will be represented as a sequence of two 16-bit values: 0x002A and 0x002A.
+ //
+ // 3. * In little-endian systems: 2A 00 2A 00
+ // * In big-endian systems: 00 2A 00 2A
+ //
+ // 4. When we interpret these 4 bytes as an `int`, we get:
+ // * In little-endian: 0x002A002A (bytes are read from right to left)
+ // * In big-endian: 0x002A002A (bytes are read from left to right)
+ //
+ // Thus, despite the different byte order in memory, the numeric value interpreted
+ // as an `int` turns out to be the same in both cases.
+ //
+ // This occurs because:
+ // - Each '*' character occupies exactly 2 bytes in UTF-16.
+ // - The value of each character (0x002A) is symmetrical with respect to byte order.
+ if (p + 2 == pe && Unsafe.ReadUnaligned(p) == ('*' << 16 | '*'))
+ {
+ p = SkipSlash(pe, pend);
+
+ // short-circuit
+ // match found if "**" is the last segment in the pattern
+ if (p == pend)
+ return vend;
+
+ do
+ {
+ var r = DoMatch(p, pend, v, vend);
+ if (r != null)
+ return r;
+
+ // try to match the next segment
+ v = FindNextSlash(v, vend);
+ v = SkipSlash(v, vend);
+ }
+ while (v < vend);
+
+ // abort recursion
+ return (char*)-1;
+ }
+
+ var ve = FindNextSlash(v, vend);
+
+ // 1. At the root level (level == 0), an empty path segment is valid,
+ // which can be represented by patterns like "*".
+ // 2. At any deeper level (level > 0), an empty segment indicates that a required directory or file is missing,
+ // making the path invalid for patterns expecting something at that level.
+ //
+ // For example
+ // Pattern: "*/*" and path: "a" - This pattern requires at least one directory level, so "a" is not a match.
+ // Pattern: "*/{,b}" and path: "a" - Similarly, this pattern requires a directory or a specific file ("b")
+ // at the next level, so "a" doesn't match.
+ //
+ // This means that the patterns "*/{}" and "*/{,}" cannot match any path due to the rule:
+ // an empty segment is not allowed beyond the root level.
+ //
+ // So, the check (v == ve && level != 0) ensures that empty segments are only acceptable at the root level.
+ // If an empty segment is found at a deeper level, the function returns null to indicate no match.
+ if (v == ve && level != 0)
+ return null;
+
+ if (DoMatchSegment(p, pe, v, ve, subpattern: 0) != ve)
+ return null;
+
+ p = SkipSlash(pe, pend);
+ v = SkipSlash(ve, vend);
+
+ level++;
+ }
+
+ if (p == pend && v == vend)
+ return vend;
+
+ return null;
+ }
+ }
+
+ private static char* DoMatchSegment(char* p, char* pend, char* v, char* vend, int subpattern)
+ {
+ while (p < pend && v < vend)
+ {
+ switch (p[0])
+ {
+ case '[':
+ {
+ var inverse = false;
+ var matched = false;
+
+ // Malformed
+ if (++p >= pend)
+ return null;
+
+ if (p[0] == '!')
+ {
+ inverse = true;
+
+ // Malformed
+ if (++p >= pend)
+ return null;
+ }
+
+ var a = p[0];
+
+ do
+ {
+ // Malformed
+ if (++p >= pend)
+ return null;
+
+ var b = a;
+
+ if (p[0] == '-' && p + 1 < pend && p[1] != ']')
+ {
+ b = p[1];
+
+ // Malformed
+ if ((p += 2) >= pend)
+ return null;
+ }
+
+ matched |= a <= v[0] & v[0] <= b;
+
+ a = p[0];
+
+ } while (a != ']');
+
+ if (matched == inverse)
+ return null;
+
+ p++;
+ v++;
+ break;
+ }
+
+ case '{':
+ {
+ var e = ExtractPattern(p, pend);
+ if (e == null)
+ return null;
+
+ v = MatchSubpattern(p, e, v, vend);
+ if (v == null)
+ return null;
+
+ p = e;
+ break;
+ }
+
+ case '*':
+ {
+ // *** => *
+ // Treats consecutive stars as one
+ // ReSharper disable once RedundantJumpStatement
+ while (++p < pend && p[0] == '*')
+ continue;
+
+ // Trailing '*' matches everything
+ if (p == pend)
+ return vend;
+
+ // OPTIMIZATION:
+ // Try to identify a fast-forward opportunity after '*' by inspecting the next pattern character.
+ // If the next character is a plain literal (not a wildcard or special construct),
+ // we can skip naive backtracking and jump directly to its next occurrence in the input.
+ //
+ // This reduces the number of recursive calls by skipping intermediate positions
+ // that cannot possibly match, effectively replacing blind linear backtracking
+ // with a guided search.
+ //
+ // For non-literal tokens ('?', '[', '{', '\'), we fall back to the original behavior
+ // to preserve correctness.
+
+ // Note: '*' is intentionally not included here, as consecutive '*' are collapsed above,
+ // so the next pattern character is guaranteed not to be '*'.
+ const long Mask =
+ 1L << ('?' - 63) | // 63
+ 1L << ('[' - 63) | // 91
+ 1L << ('\\' - 63) | // 92
+ 1L << ('{' - 63); // 123
+
+ var lookup = p[0] - 63;
+
+ while (true)
+ {
+ if ((uint)lookup > 60 || ((1L << lookup) & Mask) == 0)
+ {
+ var n = MemoryHelper.IndexOf(v, vend, p[0]);
+ if (n < 0)
+ {
+ v = vend;
+ break;
+ }
+
+ v += (uint)n;
+ }
+
+ var r = DoMatchSegment(p, pend, v, vend, subpattern);
+ if (r != null)
+ return r;
+
+ if (++v >= vend)
+ break;
+ }
+
+ // OPTIMIZATION:
+ // Aborting recursion when failing
+ //
+ // To prevent quadratic behavior in scenarios like the pattern "a*a*a*a*c"
+ // matching against the text "aaaaaaaaaaaaaaa", we use <-1> as a return
+ // value instead of .
+ //
+ // This optimization prevents each star-loop from running to the end of the text.
+ // Because only the last star-loop needs to iterate to the end of the text
+ // since advancing the previous star-loops wouldn't yield positive results
+ // upon the failure of the last star-loop.
+ if (p >= pend || p[0] != '{')
+ return (char*)-1;
+
+ break;
+ }
+
+ case '\\':
+ {
+ // Invalid escape sequence
+ if (++p >= pend)
+ return null;
+
+ // The escaped character is always compared literally,
+ // so an escaped '?' must not act as a wildcard.
+ if (p[0] != v[0])
+ return null;
+
+ p++;
+ v++;
+ break;
+ }
+
+ default:
+ {
+ if (p[0] != v[0] && p[0] != '?')
+ return null;
+
+ p++;
+ v++;
+ break;
+ }
+ }
+ }
+
+ if (v == vend)
+ {
+ // Check if the remaining pattern can match an empty string:
+ // - Trailing stars (*) can match zero or more characters, including an empty string.
+ // - Brace patterns ({},{a,}) can include alternatives that match an empty string.
+ while (p < pend)
+ {
+ if (p[0] == '*')
+ {
+ p++;
+ }
+ else if (p[0] == '{')
+ {
+ var se = ExtractPattern(p, pend);
+ if (MatchSubpattern(p, se, v, v) != v)
+ return null;
+
+ p = se;
+ }
+ else
+ {
+ return null;
+ }
+ }
+
+ return v;
+ }
+
+ if (p == pend && subpattern != 0)
+ return v;
+
+ return null;
+ }
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ private static char* MatchSubpattern(char* p, char* pend, char* v, char* vend)
+ {
+ var last = (char*)0;
+
+ while (p < pend && p[0] != '}')
+ {
+ var e = ExtractSubpattern(p, pend);
+ var r = DoMatchSegment(p + 1, e, v, vend, subpattern: 1);
+
+ // (char*)-1 is the star-loop abort signal. For an alternative it only means
+ // that this particular alternative doesn't match, so it must not win here:
+ // as an unsigned address it is greater than any valid pointer.
+ if (r > last && r != (char*)-1)
+ last = r;
+
+ p = e;
+ }
+
+ return last;
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ static char* ExtractSubpattern(char* p, char* pend)
+ {
+ Debug.Assert(p[0] is ',' or '{');
+
+ var depth = 1;
+
+ while (++p < pend)
+ {
+ var c = p[0];
+ if (c == ',' && depth == 1 || c == '}' && --depth == 0)
+ break;
+
+ if (c == '{')
+ {
+ depth++;
+ }
+ else if (c == '\\')
+ {
+ p++;
+ }
+ }
+
+ return p;
+ }
+ }
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ private static char* ExtractPattern(char* p, char* pend)
+ {
+ Debug.Assert(p[0] == '{');
+
+ var depth = 1;
+
+ while (++p < pend)
+ {
+ var c = p[0];
+ if (c == '}' && --depth == 0)
+ return p + 1;
+
+ if (c == '{')
+ {
+ depth++;
+ }
+ else if (c == '\\')
+ {
+ p++;
+ }
+ }
+
+ // Malformed
+ return null;
+ }
+}
diff --git a/Ramstack.Globbing/Properties/AssemblyInfo.cs b/Ramstack.Globbing/Properties/AssemblyInfo.cs
index 01c2569..241c51d 100644
--- a/Ramstack.Globbing/Properties/AssemblyInfo.cs
+++ b/Ramstack.Globbing/Properties/AssemblyInfo.cs
@@ -1,26 +1,26 @@
-[module: System.Runtime.CompilerServices.SkipLocalsInit]
-
-// ReSharper disable CheckNamespace
-// ReSharper disable UnusedType.Global
-
-namespace System.Runtime.CompilerServices;
-
-///
-/// Specifies that a type has required members or that a member is required.
-///
-[AttributeUsage(
- AttributeTargets.Class
- | AttributeTargets.Struct
- | AttributeTargets.Field
- | AttributeTargets.Property,
- Inherited = false)]
-internal sealed class RequiredMemberAttribute : Attribute;
-
-///
-/// Indicates that compiler support for a particular feature is required for the location where this attribute is applied.
-///
-/// The name of the required compiler feature.
-[AttributeUsage(AttributeTargets.All, AllowMultiple = true, Inherited = false)]
-#pragma warning disable CS9113 // Parameter is unread.
-internal sealed class CompilerFeatureRequiredAttribute(string featureName) : Attribute;
-#pragma warning restore CS9113 // Parameter is unread.
+[module: System.Runtime.CompilerServices.SkipLocalsInit]
+
+// ReSharper disable CheckNamespace
+// ReSharper disable UnusedType.Global
+
+namespace System.Runtime.CompilerServices;
+
+///
+/// Specifies that a type has required members or that a member is required.
+///
+[AttributeUsage(
+ AttributeTargets.Class
+ | AttributeTargets.Struct
+ | AttributeTargets.Field
+ | AttributeTargets.Property,
+ Inherited = false)]
+internal sealed class RequiredMemberAttribute : Attribute;
+
+///
+/// Indicates that compiler support for a particular feature is required for the location where this attribute is applied.
+///
+/// The name of the required compiler feature.
+[AttributeUsage(AttributeTargets.All, AllowMultiple = true, Inherited = false)]
+#pragma warning disable CS9113 // Parameter is unread.
+internal sealed class CompilerFeatureRequiredAttribute(string featureName) : Attribute;
+#pragma warning restore CS9113 // Parameter is unread.
diff --git a/Ramstack.Globbing/Ramstack.Globbing.csproj b/Ramstack.Globbing/Ramstack.Globbing.csproj
index 65755cd..53c1282 100644
--- a/Ramstack.Globbing/Ramstack.Globbing.csproj
+++ b/Ramstack.Globbing/Ramstack.Globbing.csproj
@@ -1,54 +1,49 @@
-
-
- net6.0
- Fast and zero-allocation .NET globbing library for matching file paths using glob patterns.
- enable
- enable
- preview
- true
- true
-
-
-
- 649;1591
- CS8600;CS8601;CS8602;CS8603;CS8604;CS8610;CS8613;CS8614;CS8618;CS8619;CS8620;CS8625;CS8643;CS8653;CS8714
-
-
-
- https://github.com/rameel/ramstack.globbing
- Rameel
- globbing;glob
- https://github.com/rameel/ramstack.globbing#readme
- README.md
- MIT
- true
- snupkg
- true
- true
- true
- true
-
-
-
- true
-
-
-
-
- all
- runtime; build; native; contentfiles; analyzers; buildtransitive
-
-
- all
- runtime; build; native; contentfiles; analyzers; buildtransitive
-
-
-
-
-
- True
- \
-
-
-
-
+
+
+ net6.0
+ Fast and zero-allocation .NET globbing library for matching file paths using glob patterns.
+ enable
+ enable
+ preview
+ true
+ true
+
+
+
+ https://github.com/rameel/ramstack.globbing
+ Rameel
+ globbing;glob
+ https://github.com/rameel/ramstack.globbing#readme
+ README.md
+ MIT
+ true
+ snupkg
+ true
+ true
+ true
+ true
+
+
+
+ true
+
+
+
+
+ all
+ runtime; build; native; contentfiles; analyzers; buildtransitive
+
+
+ all
+ runtime; build; native; contentfiles; analyzers; buildtransitive
+
+
+
+
+
+ True
+ \
+
+
+
+
diff --git a/Ramstack.Globbing/Traversal/DirectoryInfoExtensions.cs b/Ramstack.Globbing/Traversal/DirectoryInfoExtensions.cs
index d2a8b87..3a8a8e6 100644
--- a/Ramstack.Globbing/Traversal/DirectoryInfoExtensions.cs
+++ b/Ramstack.Globbing/Traversal/DirectoryInfoExtensions.cs
@@ -1,786 +1,786 @@
-using System.IO.Enumeration;
-
-namespace Ramstack.Globbing.Traversal;
-
-///
-/// Provides extension methods for class.
-///
-public static class DirectoryInfoExtensions
-{
- ///
- /// Enumerates files in a directory that match the specified glob pattern.
- ///
- /// The instance representing the directory to search.
- /// The glob pattern to match against the names of files.
- /// Optional glob pattern to exclude files.
- /// The matching options to use. Default is .
- ///
- /// An enumerable collection of files in the directory specified by
- /// that match the specified glob pattern.
- ///
- ///
- /// Glob pattern:
- ///
- /// -
- ///
- /// Supported meta-characters include "*", "?", "\" and "[", "]".
- /// And inside character classes "-", "!" and "]".
- ///
- ///
- /// -
- ///
- /// The "." and ".." symbols do not have any special treatment and are processed
- /// as regular characters for matching.
- ///
- ///
- /// -
- ///
- /// Character classes can be negated by prefixing them with "!", such as [!0-9],
- /// which matches all characters except digits.
- ///
- ///
- /// -
- ///
- /// Brace patterns are supported, including nested brace pattern:
- /// {file,dir,name}, {file-1.{c,cpp},file-2.{cs,f}}
- ///
- ///
- /// -
- ///
- /// An empty pattern in brace expansion {} is allowed, as well as variations
- /// like {.cs,}, {name,,file}, or {,.cs}.
- ///
- ///
- /// -
- /// Leading and trailing separators are ignored.
- ///
- /// -
- /// Consecutive separators are counted as one.
- ///
- /// -
- ///
- /// The "**" sequence in the glob pattern can be used to match zero or more directories and subdirectories.
- /// It can be used at the beginning, middle, or end of a pattern, for example,
- /// "**/file.txt", "dir/**/*.txt", "dir/**".
- ///
- ///
- ///
- ///
- public static IEnumerable EnumerateFiles(this DirectoryInfo directory, string pattern, string? exclude = null, MatchFlags flags = MatchFlags.Auto) =>
- EnumerateFiles(directory.FullName, [pattern], Files.ToExcludes(exclude), flags, SearchTarget.Files, TraversalOptions.DefaultEnumerationOptions);
-
- ///
- /// Enumerates files in a directory that match any of the specified glob patterns.
- ///
- /// The instance representing the directory to search.
- /// An array of glob patterns to match against the names of files.
- /// Optional array of glob patterns to exclude files.
- /// The matching options to use. Default is .
- ///
- /// An enumerable collection of files in the directory specified by
- /// that match the specified glob patterns.
- ///
- ///
- /// Glob pattern:
- ///
- /// -
- ///
- /// Supported meta-characters include "*", "?", "\" and "[", "]".
- /// And inside character classes "-", "!" and "]".
- ///
- ///
- /// -
- ///
- /// The "." and ".." symbols do not have any special treatment and are processed
- /// as regular characters for matching.
- ///
- ///
- /// -
- ///
- /// Character classes can be negated by prefixing them with "!", such as [!0-9],
- /// which matches all characters except digits.
- ///
- ///
- /// -
- ///
- /// Brace patterns are supported, including nested brace pattern:
- /// {file,dir,name}, {file-1.{c,cpp},file-2.{cs,f}}
- ///
- ///
- /// -
- ///
- /// An empty pattern in brace expansion {} is allowed, as well as variations
- /// like {.cs,}, {name,,file}, or {,.cs}.
- ///
- ///
- /// -
- /// Leading and trailing separators are ignored.
- ///
- /// -
- /// Consecutive separators are counted as one.
- ///
- /// -
- ///
- /// The "**" sequence in the glob pattern can be used to match zero or more directories and subdirectories.
- /// It can be used at the beginning, middle, or end of a pattern, for example,
- /// "**/file.txt", "dir/**/*.txt", "dir/**".
- ///
- ///
- ///
- ///
- public static IEnumerable EnumerateFiles(this DirectoryInfo directory, string[] patterns, string[]? excludes = null, MatchFlags flags = MatchFlags.Auto) =>
- EnumerateFiles(directory.FullName, patterns, excludes ?? [], flags, SearchTarget.Files, TraversalOptions.DefaultEnumerationOptions);
-
- ///
- /// Enumerates files in a directory that match the specified glob pattern.
- ///
- /// The instance representing the directory to search.
- /// The glob pattern to match against the names of files.
- /// The glob pattern to exclude files.
- /// An object describing the traversal options.
- ///
- /// An enumerable collection of files in the directory specified by
- /// that match the specified glob pattern.
- ///
- ///
- /// Glob pattern:
- ///
- /// -
- ///
- /// Supported meta-characters include "*", "?", "\" and "[", "]".
- /// And inside character classes "-", "!" and "]".
- ///
- ///
- /// -
- ///
- /// The "." and ".." symbols do not have any special treatment and are processed
- /// as regular characters for matching.
- ///
- ///
- /// -
- ///
- /// Character classes can be negated by prefixing them with "!", such as [!0-9],
- /// which matches all characters except digits.
- ///
- ///
- /// -
- ///
- /// Brace patterns are supported, including nested brace pattern:
- /// {file,dir,name}, {file-1.{c,cpp},file-2.{cs,f}}
- ///
- ///
- /// -
- ///
- /// An empty pattern in brace expansion {} is allowed, as well as variations
- /// like {.cs,}, {name,,file}, or {,.cs}.
- ///
- ///
- /// -
- /// Leading and trailing separators are ignored.
- ///
- /// -
- /// Consecutive separators are counted as one.
- ///
- /// -
- ///
- /// The "**" sequence in the glob pattern can be used to match zero or more directories and subdirectories.
- /// It can be used at the beginning, middle, or end of a pattern, for example,
- /// "**/file.txt", "dir/**/*.txt", "dir/**".
- ///
- ///
- ///
- ///
- public static IEnumerable EnumerateFiles(this DirectoryInfo directory, string pattern, string? exclude, TraversalOptions? options) =>
- EnumerateFiles(directory.FullName, [pattern], Files.ToExcludes(exclude), options?.MatchFlags ?? MatchFlags.Auto, SearchTarget.Files, options.ToEnumerationOptions());
-
- ///
- /// Enumerates files in a directory that match any of the specified glob patterns.
- ///
- /// The instance representing the directory to search.
- /// An array of glob patterns to match against the names of files.
- /// Optional array of glob patterns to exclude files.
- /// An object describing the traversal options.
- ///
- /// An enumerable collection of files in the directory specified by
- /// that match the specified glob patterns.
- ///
- ///
- /// Glob pattern:
- ///
- /// -
- ///
- /// Supported meta-characters include "*", "?", "\" and "[", "]".
- /// And inside character classes "-", "!" and "]".
- ///
- ///
- /// -
- ///
- /// The "." and ".." symbols do not have any special treatment and are processed
- /// as regular characters for matching.
- ///
- ///
- /// -
- ///
- /// Character classes can be negated by prefixing them with "!", such as [!0-9],
- /// which matches all characters except digits.
- ///
- ///
- /// -
- ///
- /// Brace patterns are supported, including nested brace pattern:
- /// {file,dir,name}, {file-1.{c,cpp},file-2.{cs,f}}
- ///
- ///
- /// -
- ///
- /// An empty pattern in brace expansion {} is allowed, as well as variations
- /// like {.cs,}, {name,,file}, or {,.cs}.
- ///
- ///
- /// -
- /// Leading and trailing separators are ignored.
- ///
- /// -
- /// Consecutive separators are counted as one.
- ///
- /// -
- ///
- /// The "**" sequence in the glob pattern can be used to match zero or more directories and subdirectories.
- /// It can be used at the beginning, middle, or end of a pattern, for example,
- /// "**/file.txt", "dir/**/*.txt", "dir/**".
- ///
- ///
- ///
- ///
- public static IEnumerable EnumerateFiles(this DirectoryInfo directory, string[] patterns, string[]? excludes, TraversalOptions? options) =>
- EnumerateFiles(directory.FullName, patterns, excludes ?? [], options?.MatchFlags ?? MatchFlags.Auto, SearchTarget.Files, options.ToEnumerationOptions());
-
- ///
- /// Enumerates directories in a directory that match the specified glob pattern.
- ///
- /// The instance representing the directory to search.
- /// The glob pattern to match against the names of directories.
- /// Optional glob pattern to exclude directories.
- /// The matching options to use. Default is .
- ///
- /// An enumerable collection of directories in the directory specified by
- /// that match the specified glob pattern.
- ///
- ///
- /// Glob pattern:
- ///
- /// -
- ///
- /// Supported meta-characters include "*", "?", "\" and "[", "]".
- /// And inside character classes "-", "!" and "]".
- ///
- ///
- /// -
- ///
- /// The "." and ".." symbols do not have any special treatment and are processed
- /// as regular characters for matching.
- ///
- ///
- /// -
- ///
- /// Character classes can be negated by prefixing them with "!", such as [!0-9],
- /// which matches all characters except digits.
- ///
- ///
- /// -
- ///
- /// Brace patterns are supported, including nested brace pattern:
- /// {file,dir,name}, {file-1.{c,cpp},file-2.{cs,f}}
- ///
- ///
- /// -
- ///
- /// An empty pattern in brace expansion {} is allowed, as well as variations
- /// like {.cs,}, {name,,file}, or {,.cs}.
- ///
- ///
- /// -
- /// Leading and trailing separators are ignored.
- ///
- /// -
- /// Consecutive separators are counted as one.
- ///
- /// -
- ///
- /// The "**" sequence in the glob pattern can be used to match zero or more directories and subdirectories.
- /// It can be used at the beginning, middle, or end of a pattern, for example,
- /// "**/file.txt", "dir/**/*.txt", "dir/**".
- ///
- ///
- ///
- ///
- public static IEnumerable EnumerateDirectories(this DirectoryInfo directory, string pattern, string? exclude = null, MatchFlags flags = MatchFlags.Auto) =>
- EnumerateDirectories(directory.FullName, [pattern], Files.ToExcludes(exclude), flags, SearchTarget.Directories, TraversalOptions.DefaultEnumerationOptions);
-
- ///
- /// Enumerates directories in a directory that match any of the specified glob patterns.
- ///
- /// The instance representing the directory to search.
- /// An array of glob patterns to match against the names of directories.
- /// Optional array of glob patterns to exclude directories.
- /// The matching options to use. Default is .
- ///
- /// An enumerable collection of directories in the directory specified by
- /// that match the specified glob patterns.
- ///
- ///
- /// Glob pattern:
- ///
- /// -
- ///
- /// Supported meta-characters include "*", "?", "\" and "[", "]".
- /// And inside character classes "-", "!" and "]".
- ///
- ///
- /// -
- ///
- /// The "." and ".." symbols do not have any special treatment and are processed
- /// as regular characters for matching.
- ///
- ///
- /// -
- ///
- /// Character classes can be negated by prefixing them with "!", such as [!0-9],
- /// which matches all characters except digits.
- ///
- ///
- /// -
- ///
- /// Brace patterns are supported, including nested brace pattern:
- /// {file,dir,name}, {file-1.{c,cpp},file-2.{cs,f}}
- ///
- ///
- /// -
- ///
- /// An empty pattern in brace expansion {} is allowed, as well as variations
- /// like {.cs,}, {name,,file}, or {,.cs}.
- ///
- ///
- /// -
- /// Leading and trailing separators are ignored.
- ///
- /// -
- /// Consecutive separators are counted as one.
- ///
- /// -
- ///
- /// The "**" sequence in the glob pattern can be used to match zero or more directories and subdirectories.
- /// It can be used at the beginning, middle, or end of a pattern, for example,
- /// "**/file.txt", "dir/**/*.txt", "dir/**".
- ///
- ///
- ///
- ///
- public static IEnumerable EnumerateDirectories(this DirectoryInfo directory, string[] patterns, string[]? excludes = null, MatchFlags flags = MatchFlags.Auto) =>
- EnumerateDirectories(directory.FullName, patterns, excludes ?? [], flags, SearchTarget.Directories, TraversalOptions.DefaultEnumerationOptions);
-
- ///
- /// Enumerates directories in a directory that match the specified glob pattern.
- ///
- /// The instance representing the directory to search.
- /// The glob pattern to match against the names of directories.
- /// Optional glob pattern to exclude directories.
- /// An object describing the traversal options.
- ///
- /// An enumerable collection of directories in the directory specified by
- /// that match the specified glob pattern.
- ///
- ///
- /// Glob pattern:
- ///
- /// -
- ///
- /// Supported meta-characters include "*", "?", "\" and "[", "]".
- /// And inside character classes "-", "!" and "]".
- ///
- ///
- /// -
- ///
- /// The "." and ".." symbols do not have any special treatment and are processed
- /// as regular characters for matching.
- ///
- ///
- /// -
- ///
- /// Character classes can be negated by prefixing them with "!", such as [!0-9],
- /// which matches all characters except digits.
- ///
- ///
- /// -
- ///
- /// Brace patterns are supported, including nested brace pattern:
- /// {file,dir,name}, {file-1.{c,cpp},file-2.{cs,f}}
- ///
- ///
- /// -
- ///
- /// An empty pattern in brace expansion {} is allowed, as well as variations
- /// like {.cs,}, {name,,file}, or {,.cs}.
- ///
- ///
- /// -
- /// Leading and trailing separators are ignored.
- ///
- /// -
- /// Consecutive separators are counted as one.
- ///
- /// -
- ///
- /// The "**" sequence in the glob pattern can be used to match zero or more directories and subdirectories.
- /// It can be used at the beginning, middle, or end of a pattern, for example,
- /// "**/file.txt", "dir/**/*.txt", "dir/**".
- ///
- ///
- ///
- ///
- public static IEnumerable EnumerateDirectories(this DirectoryInfo directory, string pattern, string? exclude, TraversalOptions? options) =>
- EnumerateDirectories(directory.FullName, [pattern], Files.ToExcludes(exclude), options?.MatchFlags ?? MatchFlags.Auto, SearchTarget.Directories, options.ToEnumerationOptions());
-
- ///
- /// Enumerates directories in a directory that match any of the specified glob patterns.
- ///
- /// The instance representing the directory to search.
- /// An array of glob patterns to match against the names of directories.
- /// Optional array of glob patterns to exclude directories.
- /// An object describing the traversal options.
- ///
- /// An enumerable collection of directories in the directory specified by
- /// that match the specified glob patterns.
- ///
- ///
- /// Glob pattern:
- ///
- /// -
- ///
- /// Supported meta-characters include "*", "?", "\" and "[", "]".
- /// And inside character classes "-", "!" and "]".
- ///
- ///
- /// -
- ///
- /// The "." and ".." symbols do not have any special treatment and are processed
- /// as regular characters for matching.
- ///
- ///
- /// -
- ///
- /// Character classes can be negated by prefixing them with "!", such as [!0-9],
- /// which matches all characters except digits.
- ///
- ///
- /// -
- ///
- /// Brace patterns are supported, including nested brace pattern:
- /// {file,dir,name}, {file-1.{c,cpp},file-2.{cs,f}}
- ///
- ///
- /// -
- ///
- /// An empty pattern in brace expansion {} is allowed, as well as variations
- /// like {.cs,}, {name,,file}, or {,.cs}.
- ///
- ///
- /// -
- /// Leading and trailing separators are ignored.
- ///
- /// -
- /// Consecutive separators are counted as one.
- ///
- /// -
- ///
- /// The "**" sequence in the glob pattern can be used to match zero or more directories and subdirectories.
- /// It can be used at the beginning, middle, or end of a pattern, for example,
- /// "**/file.txt", "dir/**/*.txt", "dir/**".
- ///
- ///
- ///
- ///
- public static IEnumerable EnumerateDirectories(this DirectoryInfo directory, string[] patterns, string[]? excludes, TraversalOptions? options) =>
- EnumerateDirectories(directory.FullName, patterns, excludes ?? [], options?.MatchFlags ?? MatchFlags.Auto, SearchTarget.Directories, options.ToEnumerationOptions());
-
- ///
- /// Enumerates file system information objects in a directory that match any of the specified glob pattern.
- ///
- /// The instance representing the directory to search.
- /// The glob pattern to match against the names of file-system entries in path.
- /// Optional glob pattern to exclude file-system entries.
- /// The matching options to use. Default is .
- ///
- /// An enumerable collection of file system information objects in the directory specified by
- /// that match the specified glob pattern.
- ///
- ///
- /// Glob pattern:
- ///
- /// -
- ///
- /// Supported meta-characters include "*", "?", "\" and "[", "]".
- /// And inside character classes "-", "!" and "]".
- ///
- ///
- /// -
- ///
- /// The "." and ".." symbols do not have any special treatment and are processed
- /// as regular characters for matching.
- ///
- ///
- /// -
- ///
- /// Character classes can be negated by prefixing them with "!", such as [!0-9],
- /// which matches all characters except digits.
- ///
- ///
- /// -
- ///
- /// Brace patterns are supported, including nested brace pattern:
- /// {file,dir,name}, {file-1.{c,cpp},file-2.{cs,f}}
- ///
- ///
- /// -
- ///
- /// An empty pattern in brace expansion {} is allowed, as well as variations
- /// like {.cs,}, {name,,file}, or {,.cs}.
- ///
- ///
- /// -
- /// Leading and trailing separators are ignored.
- ///
- /// -
- /// Consecutive separators are counted as one.
- ///
- /// -
- ///
- /// The "**" sequence in the glob pattern can be used to match zero or more directories and subdirectories.
- /// It can be used at the beginning, middle, or end of a pattern, for example,
- /// "**/file.txt", "dir/**/*.txt", "dir/**".
- ///
- ///
- ///
- ///
- public static IEnumerable EnumerateFileSystemInfos(this DirectoryInfo directory, string pattern, string? exclude = null, MatchFlags flags = MatchFlags.Auto) =>
- EnumerateInfos(directory.FullName, [pattern], Files.ToExcludes(exclude), flags, SearchTarget.Both, TraversalOptions.DefaultEnumerationOptions);
-
- ///
- /// Enumerates file system information objects in a directory that match any of the specified glob patterns.
- ///
- /// The instance representing the directory to search.
- /// An array of glob patterns to match against the names of file-system entries.
- /// Optional array of glob patterns to exclude file-system entries.
- /// The matching options to use. Default is .
- ///
- /// An enumerable collection of file system information objects in the directory specified by
- /// that match the specified glob patterns.
- ///
- ///
- /// Glob pattern:
- ///
- /// -
- ///
- /// Supported meta-characters include "*", "?", "\" and "[", "]".
- /// And inside character classes "-", "!" and "]".
- ///
- ///
- /// -
- ///
- /// The "." and ".." symbols do not have any special treatment and are processed
- /// as regular characters for matching.
- ///
- ///
- /// -
- ///
- /// Character classes can be negated by prefixing them with "!", such as [!0-9],
- /// which matches all characters except digits.
- ///
- ///
- /// -
- ///
- /// Brace patterns are supported, including nested brace pattern:
- /// {file,dir,name}, {file-1.{c,cpp},file-2.{cs,f}}
- ///
- ///
- /// -
- ///
- /// An empty pattern in brace expansion {} is allowed, as well as variations
- /// like {.cs,}, {name,,file}, or {,.cs}.
- ///
- ///
- /// -
- /// Leading and trailing separators are ignored.
- ///
- /// -
- /// Consecutive separators are counted as one.
- ///
- /// -
- ///
- /// The "**" sequence in the glob pattern can be used to match zero or more directories and subdirectories.
- /// It can be used at the beginning, middle, or end of a pattern, for example,
- /// "**/file.txt", "dir/**/*.txt", "dir/**".
- ///
- ///
- ///
- ///
- public static IEnumerable EnumerateFileSystemInfos(this DirectoryInfo directory, string[] patterns, string[]? excludes = null, MatchFlags flags = MatchFlags.Auto) =>
- EnumerateInfos(directory.FullName, patterns, excludes ?? [], flags, SearchTarget.Both, TraversalOptions.DefaultEnumerationOptions);
-
- ///
- /// Enumerates file system information objects in a directory that match any of the specified glob pattern.
- ///
- /// The instance representing the directory to search.
- /// The glob pattern to match against the names of file-system entries in path.
- /// Optional glob pattern to exclude file-system entries.
- /// An object describing the traversal options.
- ///
- /// An enumerable collection of file system information objects in the directory specified by
- /// that match the specified glob pattern.
- ///
- ///
- /// Glob pattern:
- ///
- /// -
- ///
- /// Supported meta-characters include "*", "?", "\" and "[", "]".
- /// And inside character classes "-", "!" and "]".
- ///
- ///
- /// -
- ///
- /// The "." and ".." symbols do not have any special treatment and are processed
- /// as regular characters for matching.
- ///
- ///
- /// -
- ///
- /// Character classes can be negated by prefixing them with "!", such as [!0-9],
- /// which matches all characters except digits.
- ///
- ///
- /// -
- ///
- /// Brace patterns are supported, including nested brace pattern:
- /// {file,dir,name}, {file-1.{c,cpp},file-2.{cs,f}}
- ///
- ///
- /// -
- ///
- /// An empty pattern in brace expansion {} is allowed, as well as variations
- /// like {.cs,}, {name,,file}, or {,.cs}.
- ///
- ///
- /// -
- /// Leading and trailing separators are ignored.
- ///
- /// -
- /// Consecutive separators are counted as one.
- ///
- /// -
- ///
- /// The "**" sequence in the glob pattern can be used to match zero or more directories and subdirectories.
- /// It can be used at the beginning, middle, or end of a pattern, for example,
- /// "**/file.txt", "dir/**/*.txt", "dir/**".
- ///
- ///
- ///
- ///
- public static IEnumerable EnumerateFileSystemInfos(this DirectoryInfo directory, string pattern, string? exclude, TraversalOptions? options) =>
- EnumerateInfos(directory.FullName, [pattern], Files.ToExcludes(exclude), options?.MatchFlags ?? MatchFlags.Auto, SearchTarget.Both, options.ToEnumerationOptions());
-
- ///
- /// Enumerates file system information objects in a directory that match any of the specified glob patterns.
- ///
- /// The instance representing the directory to search.
- /// An array of glob patterns to match against the names of file-system entries.
- /// Optional array of glob patterns to exclude file-system entries.
- /// An object describing the traversal options.
- ///
- /// An enumerable collection of file system information objects in the directory specified by
- /// that match the specified glob patterns.
- ///
- ///
- /// Glob pattern:
- ///
- /// -
- ///
- /// Supported meta-characters include "*", "?", "\" and "[", "]".
- /// And inside character classes "-", "!" and "]".
- ///
- ///
- /// -
- ///
- /// The "." and ".." symbols do not have any special treatment and are processed
- /// as regular characters for matching.
- ///
- ///
- /// -
- ///
- /// Character classes can be negated by prefixing them with "!", such as [!0-9],
- /// which matches all characters except digits.
- ///
- ///
- /// -
- ///
- /// Brace patterns are supported, including nested brace pattern:
- /// {file,dir,name}, {file-1.{c,cpp},file-2.{cs,f}}
- ///
- ///
- /// -
- ///
- /// An empty pattern in brace expansion {} is allowed, as well as variations
- /// like {.cs,}, {name,,file}, or {,.cs}.
- ///
- ///
- /// -
- /// Leading and trailing separators are ignored.
- ///
- /// -
- /// Consecutive separators are counted as one.
- ///
- /// -
- ///
- /// The "**" sequence in the glob pattern can be used to match zero or more directories and subdirectories.
- /// It can be used at the beginning, middle, or end of a pattern, for example,
- /// "**/file.txt", "dir/**/*.txt", "dir/**".
- ///
- ///
- ///
- ///
- public static IEnumerable EnumerateFileSystemInfos(this DirectoryInfo directory, string[] patterns, string[]? excludes, TraversalOptions? options) =>
- EnumerateInfos(directory.FullName, patterns, excludes ?? [], options?.MatchFlags ?? MatchFlags.Auto, SearchTarget.Both, options.ToEnumerationOptions());
-
- private static IEnumerable EnumerateFiles(string path, string[] patterns, string[] excludes, MatchFlags flags, SearchTarget target, EnumerationOptions options)
- {
- flags = Files.ResolveMatchFlags(flags);
-
- return new FileSystemEnumerable(path, (ref entry) => (FileInfo)entry.ToFileSystemInfo(), options)
- {
- ShouldIncludePredicate = (ref entry) => Files.ShouldInclude(ref entry, patterns, excludes, flags, target),
- ShouldRecursePredicate = (ref entry) => Files.ShouldRecurse(ref entry, patterns, excludes, flags)
- };
- }
-
- private static IEnumerable EnumerateDirectories(string path, string[] patterns, string[] excludes, MatchFlags flags, SearchTarget target, EnumerationOptions options)
- {
- flags = Files.ResolveMatchFlags(flags);
-
- return new FileSystemEnumerable(path, (ref entry) => (DirectoryInfo)entry.ToFileSystemInfo(), options)
- {
- ShouldIncludePredicate = (ref entry) => Files.ShouldInclude(ref entry, patterns, excludes, flags, target),
- ShouldRecursePredicate = (ref entry) => Files.ShouldRecurse(ref entry, patterns, excludes, flags)
- };
- }
-
- private static IEnumerable EnumerateInfos(string path, string[] patterns, string[] excludes, MatchFlags flags, SearchTarget target, EnumerationOptions options)
- {
- flags = Files.ResolveMatchFlags(flags);
-
- return new FileSystemEnumerable(path, (ref entry) => entry.ToFileSystemInfo(), options)
- {
- ShouldIncludePredicate = (ref entry) => Files.ShouldInclude(ref entry, patterns, excludes, flags, target),
- ShouldRecursePredicate = (ref entry) => Files.ShouldRecurse(ref entry, patterns, excludes, flags)
- };
- }
-}
+using System.IO.Enumeration;
+
+namespace Ramstack.Globbing.Traversal;
+
+///
+/// Provides extension methods for class.
+///
+public static class DirectoryInfoExtensions
+{
+ ///
+ /// Enumerates files in a directory that match the specified glob pattern.
+ ///
+ /// The instance representing the directory to search.
+ /// The glob pattern to match against the names of files.
+ /// Optional glob pattern to exclude files.
+ /// The matching options to use. Default is .
+ ///
+ /// An enumerable collection of files in the directory specified by
+ /// that match the specified glob pattern.
+ ///
+ ///
+ /// Glob pattern:
+ ///
+ /// -
+ ///
+ /// Supported meta-characters include "*", "?", "\" and "[", "]".
+ /// And inside character classes "-", "!" and "]".
+ ///
+ ///
+ /// -
+ ///
+ /// The "." and ".." symbols do not have any special treatment and are processed
+ /// as regular characters for matching.
+ ///
+ ///
+ /// -
+ ///
+ /// Character classes can be negated by prefixing them with "!", such as [!0-9],
+ /// which matches all characters except digits.
+ ///
+ ///
+ /// -
+ ///
+ /// Brace patterns are supported, including nested brace pattern:
+ /// {file,dir,name}, {file-1.{c,cpp},file-2.{cs,f}}
+ ///
+ ///
+ /// -
+ ///
+ /// An empty pattern in brace expansion {} is allowed, as well as variations
+ /// like {.cs,}, {name,,file}, or {,.cs}.
+ ///
+ ///
+ /// -
+ /// Leading and trailing separators are ignored.
+ ///
+ /// -
+ /// Consecutive separators are counted as one.
+ ///
+ /// -
+ ///
+ /// The "**" sequence in the glob pattern can be used to match zero or more directories and subdirectories.
+ /// It can be used at the beginning, middle, or end of a pattern, for example,
+ /// "**/file.txt", "dir/**/*.txt", "dir/**".
+ ///
+ ///
+ ///
+ ///
+ public static IEnumerable EnumerateFiles(this DirectoryInfo directory, string pattern, string? exclude = null, MatchFlags flags = MatchFlags.Auto) =>
+ EnumerateFiles(directory.FullName, [pattern], Files.ToExcludes(exclude), flags, SearchTarget.Files, TraversalOptions.DefaultEnumerationOptions);
+
+ ///
+ /// Enumerates files in a directory that match any of the specified glob patterns.
+ ///
+ /// The instance representing the directory to search.
+ /// An array of glob patterns to match against the names of files.
+ /// Optional array of glob patterns to exclude files.
+ /// The matching options to use. Default is .
+ ///
+ /// An enumerable collection of files in the directory specified by
+ /// that match the specified glob patterns.
+ ///
+ ///
+ /// Glob pattern:
+ ///
+ /// -
+ ///
+ /// Supported meta-characters include "*", "?", "\" and "[", "]".
+ /// And inside character classes "-", "!" and "]".
+ ///
+ ///
+ /// -
+ ///
+ /// The "." and ".." symbols do not have any special treatment and are processed
+ /// as regular characters for matching.
+ ///
+ ///
+ /// -
+ ///
+ /// Character classes can be negated by prefixing them with "!", such as [!0-9],
+ /// which matches all characters except digits.
+ ///
+ ///
+ /// -
+ ///
+ /// Brace patterns are supported, including nested brace pattern:
+ /// {file,dir,name}, {file-1.{c,cpp},file-2.{cs,f}}
+ ///
+ ///
+ /// -
+ ///
+ /// An empty pattern in brace expansion {} is allowed, as well as variations
+ /// like {.cs,}, {name,,file}, or {,.cs}.
+ ///
+ ///
+ /// -
+ /// Leading and trailing separators are ignored.
+ ///
+ /// -
+ /// Consecutive separators are counted as one.
+ ///
+ /// -
+ ///
+ /// The "**" sequence in the glob pattern can be used to match zero or more directories and subdirectories.
+ /// It can be used at the beginning, middle, or end of a pattern, for example,
+ /// "**/file.txt", "dir/**/*.txt", "dir/**".
+ ///
+ ///
+ ///
+ ///
+ public static IEnumerable EnumerateFiles(this DirectoryInfo directory, string[] patterns, string[]? excludes = null, MatchFlags flags = MatchFlags.Auto) =>
+ EnumerateFiles(directory.FullName, patterns, excludes ?? [], flags, SearchTarget.Files, TraversalOptions.DefaultEnumerationOptions);
+
+ ///
+ /// Enumerates files in a directory that match the specified glob pattern.
+ ///
+ /// The instance representing the directory to search.
+ /// The glob pattern to match against the names of files.
+ /// The glob pattern to exclude files.
+ /// An object describing the traversal options.
+ ///
+ /// An enumerable collection of files in the directory specified by
+ /// that match the specified glob pattern.
+ ///
+ ///
+ /// Glob pattern:
+ ///
+ /// -
+ ///
+ /// Supported meta-characters include "*", "?", "\" and "[", "]".
+ /// And inside character classes "-", "!" and "]".
+ ///
+ ///
+ /// -
+ ///
+ /// The "." and ".." symbols do not have any special treatment and are processed
+ /// as regular characters for matching.
+ ///
+ ///
+ /// -
+ ///
+ /// Character classes can be negated by prefixing them with "!", such as [!0-9],
+ /// which matches all characters except digits.
+ ///
+ ///
+ /// -
+ ///
+ /// Brace patterns are supported, including nested brace pattern:
+ /// {file,dir,name}, {file-1.{c,cpp},file-2.{cs,f}}
+ ///
+ ///
+ /// -
+ ///
+ /// An empty pattern in brace expansion {} is allowed, as well as variations
+ /// like {.cs,}, {name,,file}, or {,.cs}.
+ ///
+ ///
+ /// -
+ /// Leading and trailing separators are ignored.
+ ///
+ /// -
+ /// Consecutive separators are counted as one.
+ ///
+ /// -
+ ///
+ /// The "**" sequence in the glob pattern can be used to match zero or more directories and subdirectories.
+ /// It can be used at the beginning, middle, or end of a pattern, for example,
+ /// "**/file.txt", "dir/**/*.txt", "dir/**".
+ ///
+ ///
+ ///
+ ///
+ public static IEnumerable EnumerateFiles(this DirectoryInfo directory, string pattern, string? exclude, TraversalOptions? options) =>
+ EnumerateFiles(directory.FullName, [pattern], Files.ToExcludes(exclude), options?.MatchFlags ?? MatchFlags.Auto, SearchTarget.Files, options.ToEnumerationOptions());
+
+ ///
+ /// Enumerates files in a directory that match any of the specified glob patterns.
+ ///
+ /// The instance representing the directory to search.
+ /// An array of glob patterns to match against the names of files.
+ /// Optional array of glob patterns to exclude files.
+ /// An object describing the traversal options.
+ ///
+ /// An enumerable collection of files in the directory specified by
+ /// that match the specified glob patterns.
+ ///
+ ///
+ /// Glob pattern:
+ ///
+ /// -
+ ///
+ /// Supported meta-characters include "*", "?", "\" and "[", "]".
+ /// And inside character classes "-", "!" and "]".
+ ///
+ ///
+ /// -
+ ///
+ /// The "." and ".." symbols do not have any special treatment and are processed
+ /// as regular characters for matching.
+ ///
+ ///
+ /// -
+ ///
+ /// Character classes can be negated by prefixing them with "!", such as [!0-9],
+ /// which matches all characters except digits.
+ ///
+ ///
+ /// -
+ ///
+ /// Brace patterns are supported, including nested brace pattern:
+ /// {file,dir,name}, {file-1.{c,cpp},file-2.{cs,f}}
+ ///
+ ///
+ /// -
+ ///
+ /// An empty pattern in brace expansion {} is allowed, as well as variations
+ /// like {.cs,}, {name,,file}, or {,.cs}.
+ ///
+ ///
+ /// -
+ /// Leading and trailing separators are ignored.
+ ///
+ /// -
+ /// Consecutive separators are counted as one.
+ ///
+ /// -
+ ///
+ /// The "**" sequence in the glob pattern can be used to match zero or more directories and subdirectories.
+ /// It can be used at the beginning, middle, or end of a pattern, for example,
+ /// "**/file.txt", "dir/**/*.txt", "dir/**".
+ ///
+ ///
+ ///
+ ///
+ public static IEnumerable EnumerateFiles(this DirectoryInfo directory, string[] patterns, string[]? excludes, TraversalOptions? options) =>
+ EnumerateFiles(directory.FullName, patterns, excludes ?? [], options?.MatchFlags ?? MatchFlags.Auto, SearchTarget.Files, options.ToEnumerationOptions());
+
+ ///
+ /// Enumerates directories in a directory that match the specified glob pattern.
+ ///
+ /// The instance representing the directory to search.
+ /// The glob pattern to match against the names of directories.
+ /// Optional glob pattern to exclude directories.
+ /// The matching options to use. Default is .
+ ///
+ /// An enumerable collection of directories in the directory specified by
+ /// that match the specified glob pattern.
+ ///
+ ///
+ /// Glob pattern:
+ ///
+ /// -
+ ///
+ /// Supported meta-characters include "*", "?", "\" and "[", "]".
+ /// And inside character classes "-", "!" and "]".
+ ///
+ ///
+ /// -
+ ///
+ /// The "." and ".." symbols do not have any special treatment and are processed
+ /// as regular characters for matching.
+ ///
+ ///
+ /// -
+ ///
+ /// Character classes can be negated by prefixing them with "!", such as [!0-9],
+ /// which matches all characters except digits.
+ ///
+ ///
+ /// -
+ ///
+ /// Brace patterns are supported, including nested brace pattern:
+ /// {file,dir,name}, {file-1.{c,cpp},file-2.{cs,f}}
+ ///
+ ///
+ /// -
+ ///
+ /// An empty pattern in brace expansion {} is allowed, as well as variations
+ /// like {.cs,}, {name,,file}, or {,.cs}.
+ ///
+ ///
+ /// -
+ /// Leading and trailing separators are ignored.
+ ///
+ /// -
+ /// Consecutive separators are counted as one.
+ ///
+ /// -
+ ///
+ /// The "**" sequence in the glob pattern can be used to match zero or more directories and subdirectories.
+ /// It can be used at the beginning, middle, or end of a pattern, for example,
+ /// "**/file.txt", "dir/**/*.txt", "dir/**".
+ ///
+ ///
+ ///
+ ///
+ public static IEnumerable EnumerateDirectories(this DirectoryInfo directory, string pattern, string? exclude = null, MatchFlags flags = MatchFlags.Auto) =>
+ EnumerateDirectories(directory.FullName, [pattern], Files.ToExcludes(exclude), flags, SearchTarget.Directories, TraversalOptions.DefaultEnumerationOptions);
+
+ ///
+ /// Enumerates directories in a directory that match any of the specified glob patterns.
+ ///
+ /// The instance representing the directory to search.
+ /// An array of glob patterns to match against the names of directories.
+ /// Optional array of glob patterns to exclude directories.
+ /// The matching options to use. Default is .
+ ///
+ /// An enumerable collection of directories in the directory specified by
+ /// that match the specified glob patterns.
+ ///
+ ///
+ /// Glob pattern:
+ ///
+ /// -
+ ///
+ /// Supported meta-characters include "*", "?", "\" and "[", "]".
+ /// And inside character classes "-", "!" and "]".
+ ///
+ ///
+ /// -
+ ///
+ /// The "." and ".." symbols do not have any special treatment and are processed
+ /// as regular characters for matching.
+ ///
+ ///
+ /// -
+ ///
+ /// Character classes can be negated by prefixing them with "!", such as [!0-9],
+ /// which matches all characters except digits.
+ ///
+ ///
+ /// -
+ ///
+ /// Brace patterns are supported, including nested brace pattern:
+ /// {file,dir,name}, {file-1.{c,cpp},file-2.{cs,f}}
+ ///
+ ///
+ /// -
+ ///
+ /// An empty pattern in brace expansion {} is allowed, as well as variations
+ /// like {.cs,}, {name,,file}, or {,.cs}.
+ ///
+ ///
+ /// -
+ /// Leading and trailing separators are ignored.
+ ///
+ /// -
+ /// Consecutive separators are counted as one.
+ ///
+ /// -
+ ///
+ /// The "**" sequence in the glob pattern can be used to match zero or more directories and subdirectories.
+ /// It can be used at the beginning, middle, or end of a pattern, for example,
+ /// "**/file.txt", "dir/**/*.txt", "dir/**".
+ ///
+ ///
+ ///
+ ///
+ public static IEnumerable EnumerateDirectories(this DirectoryInfo directory, string[] patterns, string[]? excludes = null, MatchFlags flags = MatchFlags.Auto) =>
+ EnumerateDirectories(directory.FullName, patterns, excludes ?? [], flags, SearchTarget.Directories, TraversalOptions.DefaultEnumerationOptions);
+
+ ///
+ /// Enumerates directories in a directory that match the specified glob pattern.
+ ///
+ /// The instance representing the directory to search.
+ /// The glob pattern to match against the names of directories.
+ /// Optional glob pattern to exclude directories.
+ /// An object describing the traversal options.
+ ///
+ /// An enumerable collection of directories in the directory specified by
+ /// that match the specified glob pattern.
+ ///
+ ///
+ /// Glob pattern:
+ ///
+ /// -
+ ///
+ /// Supported meta-characters include "*", "?", "\" and "[", "]".
+ /// And inside character classes "-", "!" and "]".
+ ///
+ ///
+ /// -
+ ///
+ /// The "." and ".." symbols do not have any special treatment and are processed
+ /// as regular characters for matching.
+ ///
+ ///
+ /// -
+ ///
+ /// Character classes can be negated by prefixing them with "!", such as [!0-9],
+ /// which matches all characters except digits.
+ ///
+ ///
+ /// -
+ ///
+ /// Brace patterns are supported, including nested brace pattern:
+ /// {file,dir,name}, {file-1.{c,cpp},file-2.{cs,f}}
+ ///
+ ///
+ /// -
+ ///
+ /// An empty pattern in brace expansion {} is allowed, as well as variations
+ /// like {.cs,}, {name,,file}, or {,.cs}.
+ ///
+ ///
+ /// -
+ /// Leading and trailing separators are ignored.
+ ///
+ /// -
+ /// Consecutive separators are counted as one.
+ ///
+ /// -
+ ///
+ /// The "**" sequence in the glob pattern can be used to match zero or more directories and subdirectories.
+ /// It can be used at the beginning, middle, or end of a pattern, for example,
+ /// "**/file.txt", "dir/**/*.txt", "dir/**".
+ ///
+ ///
+ ///
+ ///
+ public static IEnumerable EnumerateDirectories(this DirectoryInfo directory, string pattern, string? exclude, TraversalOptions? options) =>
+ EnumerateDirectories(directory.FullName, [pattern], Files.ToExcludes(exclude), options?.MatchFlags ?? MatchFlags.Auto, SearchTarget.Directories, options.ToEnumerationOptions());
+
+ ///
+ /// Enumerates directories in a directory that match any of the specified glob patterns.
+ ///
+ /// The instance representing the directory to search.
+ /// An array of glob patterns to match against the names of directories.
+ /// Optional array of glob patterns to exclude directories.
+ /// An object describing the traversal options.
+ ///
+ /// An enumerable collection of directories in the directory specified by
+ /// that match the specified glob patterns.
+ ///
+ ///
+ /// Glob pattern:
+ ///
+ /// -
+ ///
+ /// Supported meta-characters include "*", "?", "\" and "[", "]".
+ /// And inside character classes "-", "!" and "]".
+ ///
+ ///
+ /// -
+ ///
+ /// The "." and ".." symbols do not have any special treatment and are processed
+ /// as regular characters for matching.
+ ///
+ ///
+ /// -
+ ///
+ /// Character classes can be negated by prefixing them with "!", such as [!0-9],
+ /// which matches all characters except digits.
+ ///
+ ///
+ /// -
+ ///
+ /// Brace patterns are supported, including nested brace pattern:
+ /// {file,dir,name}, {file-1.{c,cpp},file-2.{cs,f}}
+ ///
+ ///
+ /// -
+ ///
+ /// An empty pattern in brace expansion {} is allowed, as well as variations
+ /// like {.cs,}, {name,,file}, or {,.cs}.
+ ///
+ ///
+ /// -
+ /// Leading and trailing separators are ignored.
+ ///
+ /// -
+ /// Consecutive separators are counted as one.
+ ///
+ /// -
+ ///
+ /// The "**" sequence in the glob pattern can be used to match zero or more directories and subdirectories.
+ /// It can be used at the beginning, middle, or end of a pattern, for example,
+ /// "**/file.txt", "dir/**/*.txt", "dir/**".
+ ///
+ ///
+ ///
+ ///
+ public static IEnumerable EnumerateDirectories(this DirectoryInfo directory, string[] patterns, string[]? excludes, TraversalOptions? options) =>
+ EnumerateDirectories(directory.FullName, patterns, excludes ?? [], options?.MatchFlags ?? MatchFlags.Auto, SearchTarget.Directories, options.ToEnumerationOptions());
+
+ ///
+ /// Enumerates file system information objects in a directory that match any of the specified glob pattern.
+ ///
+ /// The instance representing the directory to search.
+ /// The glob pattern to match against the names of file-system entries in path.
+ /// Optional glob pattern to exclude file-system entries.
+ /// The matching options to use. Default is .
+ ///
+ /// An enumerable collection of file system information objects in the directory specified by
+ /// that match the specified glob pattern.
+ ///
+ ///
+ /// Glob pattern:
+ ///
+ /// -
+ ///
+ /// Supported meta-characters include "*", "?", "\" and "[", "]".
+ /// And inside character classes "-", "!" and "]".
+ ///
+ ///
+ /// -
+ ///
+ /// The "." and ".." symbols do not have any special treatment and are processed
+ /// as regular characters for matching.
+ ///
+ ///
+ /// -
+ ///
+ /// Character classes can be negated by prefixing them with "!", such as [!0-9],
+ /// which matches all characters except digits.
+ ///
+ ///
+ /// -
+ ///
+ /// Brace patterns are supported, including nested brace pattern:
+ /// {file,dir,name}, {file-1.{c,cpp},file-2.{cs,f}}
+ ///
+ ///
+ /// -
+ ///
+ /// An empty pattern in brace expansion {} is allowed, as well as variations
+ /// like {.cs,}, {name,,file}, or {,.cs}.
+ ///
+ ///
+ /// -
+ /// Leading and trailing separators are ignored.
+ ///
+ /// -
+ /// Consecutive separators are counted as one.
+ ///
+ /// -
+ ///
+ /// The "**" sequence in the glob pattern can be used to match zero or more directories and subdirectories.
+ /// It can be used at the beginning, middle, or end of a pattern, for example,
+ /// "**/file.txt", "dir/**/*.txt", "dir/**".
+ ///
+ ///
+ ///
+ ///
+ public static IEnumerable EnumerateFileSystemInfos(this DirectoryInfo directory, string pattern, string? exclude = null, MatchFlags flags = MatchFlags.Auto) =>
+ EnumerateInfos(directory.FullName, [pattern], Files.ToExcludes(exclude), flags, SearchTarget.Both, TraversalOptions.DefaultEnumerationOptions);
+
+ ///
+ /// Enumerates file system information objects in a directory that match any of the specified glob patterns.
+ ///
+ /// The instance representing the directory to search.
+ /// An array of glob patterns to match against the names of file-system entries.
+ /// Optional array of glob patterns to exclude file-system entries.
+ /// The matching options to use. Default is .
+ ///
+ /// An enumerable collection of file system information objects in the directory specified by
+ /// that match the specified glob patterns.
+ ///
+ ///
+ /// Glob pattern:
+ ///
+ /// -
+ ///
+ /// Supported meta-characters include "*", "?", "\" and "[", "]".
+ /// And inside character classes "-", "!" and "]".
+ ///
+ ///
+ /// -
+ ///
+ /// The "." and ".." symbols do not have any special treatment and are processed
+ /// as regular characters for matching.
+ ///
+ ///
+ /// -
+ ///
+ /// Character classes can be negated by prefixing them with "!", such as [!0-9],
+ /// which matches all characters except digits.
+ ///
+ ///
+ /// -
+ ///
+ /// Brace patterns are supported, including nested brace pattern:
+ /// {file,dir,name}, {file-1.{c,cpp},file-2.{cs,f}}
+ ///
+ ///
+ /// -
+ ///
+ /// An empty pattern in brace expansion {} is allowed, as well as variations
+ /// like {.cs,}, {name,,file}, or {,.cs}.
+ ///
+ ///
+ /// -
+ /// Leading and trailing separators are ignored.
+ ///
+ /// -
+ /// Consecutive separators are counted as one.
+ ///
+ /// -
+ ///
+ /// The "**" sequence in the glob pattern can be used to match zero or more directories and subdirectories.
+ /// It can be used at the beginning, middle, or end of a pattern, for example,
+ /// "**/file.txt", "dir/**/*.txt", "dir/**".
+ ///
+ ///
+ ///
+ ///
+ public static IEnumerable EnumerateFileSystemInfos(this DirectoryInfo directory, string[] patterns, string[]? excludes = null, MatchFlags flags = MatchFlags.Auto) =>
+ EnumerateInfos(directory.FullName, patterns, excludes ?? [], flags, SearchTarget.Both, TraversalOptions.DefaultEnumerationOptions);
+
+ ///
+ /// Enumerates file system information objects in a directory that match any of the specified glob pattern.
+ ///
+ /// The instance representing the directory to search.
+ /// The glob pattern to match against the names of file-system entries in path.
+ /// Optional glob pattern to exclude file-system entries.
+ /// An object describing the traversal options.
+ ///
+ /// An enumerable collection of file system information objects in the directory specified by
+ /// that match the specified glob pattern.
+ ///
+ ///
+ /// Glob pattern:
+ ///
+ /// -
+ ///
+ /// Supported meta-characters include "*", "?", "\" and "[", "]".
+ /// And inside character classes "-", "!" and "]".
+ ///
+ ///
+ /// -
+ ///
+ /// The "." and ".." symbols do not have any special treatment and are processed
+ /// as regular characters for matching.
+ ///
+ ///
+ /// -
+ ///
+ /// Character classes can be negated by prefixing them with "!", such as [!0-9],
+ /// which matches all characters except digits.
+ ///
+ ///
+ /// -
+ ///
+ /// Brace patterns are supported, including nested brace pattern:
+ /// {file,dir,name}, {file-1.{c,cpp},file-2.{cs,f}}
+ ///
+ ///
+ /// -
+ ///
+ /// An empty pattern in brace expansion {} is allowed, as well as variations
+ /// like {.cs,}, {name,,file}, or {,.cs}.
+ ///
+ ///
+ /// -
+ /// Leading and trailing separators are ignored.
+ ///
+ /// -
+ /// Consecutive separators are counted as one.
+ ///
+ /// -
+ ///
+ /// The "**" sequence in the glob pattern can be used to match zero or more directories and subdirectories.
+ /// It can be used at the beginning, middle, or end of a pattern, for example,
+ /// "**/file.txt", "dir/**/*.txt", "dir/**".
+ ///
+ ///
+ ///
+ ///
+ public static IEnumerable EnumerateFileSystemInfos(this DirectoryInfo directory, string pattern, string? exclude, TraversalOptions? options) =>
+ EnumerateInfos(directory.FullName, [pattern], Files.ToExcludes(exclude), options?.MatchFlags ?? MatchFlags.Auto, SearchTarget.Both, options.ToEnumerationOptions());
+
+ ///
+ /// Enumerates file system information objects in a directory that match any of the specified glob patterns.
+ ///
+ /// The instance representing the directory to search.
+ /// An array of glob patterns to match against the names of file-system entries.
+ /// Optional array of glob patterns to exclude file-system entries.
+ /// An object describing the traversal options.
+ ///
+ /// An enumerable collection of file system information objects in the directory specified by
+ /// that match the specified glob patterns.
+ ///
+ ///
+ /// Glob pattern:
+ ///
+ /// -
+ ///
+ /// Supported meta-characters include "*", "?", "\" and "[", "]".
+ /// And inside character classes "-", "!" and "]".
+ ///
+ ///
+ /// -
+ ///
+ /// The "." and ".." symbols do not have any special treatment and are processed
+ /// as regular characters for matching.
+ ///
+ ///
+ /// -
+ ///
+ /// Character classes can be negated by prefixing them with "!", such as [!0-9],
+ /// which matches all characters except digits.
+ ///
+ ///
+ /// -
+ ///
+ /// Brace patterns are supported, including nested brace pattern:
+ /// {file,dir,name}, {file-1.{c,cpp},file-2.{cs,f}}
+ ///
+ ///
+ /// -
+ ///
+ /// An empty pattern in brace expansion {} is allowed, as well as variations
+ /// like {.cs,}, {name,,file}, or {,.cs}.
+ ///
+ ///
+ /// -
+ /// Leading and trailing separators are ignored.
+ ///
+ /// -
+ /// Consecutive separators are counted as one.
+ ///
+ /// -
+ ///
+ /// The "**" sequence in the glob pattern can be used to match zero or more directories and subdirectories.
+ /// It can be used at the beginning, middle, or end of a pattern, for example,
+ /// "**/file.txt", "dir/**/*.txt", "dir/**".
+ ///
+ ///
+ ///
+ ///
+ public static IEnumerable EnumerateFileSystemInfos(this DirectoryInfo directory, string[] patterns, string[]? excludes, TraversalOptions? options) =>
+ EnumerateInfos(directory.FullName, patterns, excludes ?? [], options?.MatchFlags ?? MatchFlags.Auto, SearchTarget.Both, options.ToEnumerationOptions());
+
+ private static FileSystemEnumerable EnumerateFiles(string path, string[] patterns, string[] excludes, MatchFlags flags, SearchTarget target, EnumerationOptions options)
+ {
+ flags = Files.ResolveMatchFlags(flags);
+
+ return new FileSystemEnumerable(path, (ref entry) => (FileInfo)entry.ToFileSystemInfo(), options)
+ {
+ ShouldIncludePredicate = (ref entry) => Files.ShouldInclude(ref entry, patterns, excludes, flags, target),
+ ShouldRecursePredicate = (ref entry) => Files.ShouldRecurse(ref entry, patterns, excludes, flags)
+ };
+ }
+
+ private static FileSystemEnumerable EnumerateDirectories(string path, string[] patterns, string[] excludes, MatchFlags flags, SearchTarget target, EnumerationOptions options)
+ {
+ flags = Files.ResolveMatchFlags(flags);
+
+ return new FileSystemEnumerable(path, (ref entry) => (DirectoryInfo)entry.ToFileSystemInfo(), options)
+ {
+ ShouldIncludePredicate = (ref entry) => Files.ShouldInclude(ref entry, patterns, excludes, flags, target),
+ ShouldRecursePredicate = (ref entry) => Files.ShouldRecurse(ref entry, patterns, excludes, flags)
+ };
+ }
+
+ private static FileSystemEnumerable EnumerateInfos(string path, string[] patterns, string[] excludes, MatchFlags flags, SearchTarget target, EnumerationOptions options)
+ {
+ flags = Files.ResolveMatchFlags(flags);
+
+ return new FileSystemEnumerable(path, (ref entry) => entry.ToFileSystemInfo(), options)
+ {
+ ShouldIncludePredicate = (ref entry) => Files.ShouldInclude(ref entry, patterns, excludes, flags, target),
+ ShouldRecursePredicate = (ref entry) => Files.ShouldRecurse(ref entry, patterns, excludes, flags)
+ };
+ }
+}
diff --git a/Ramstack.Globbing/Traversal/FileTreeAsyncEnumerable.cs b/Ramstack.Globbing/Traversal/FileTreeAsyncEnumerable.cs
index d026261..1afadd6 100644
--- a/Ramstack.Globbing/Traversal/FileTreeAsyncEnumerable.cs
+++ b/Ramstack.Globbing/Traversal/FileTreeAsyncEnumerable.cs
@@ -1,122 +1,122 @@
-using System.Buffers;
-using System.Runtime.CompilerServices;
-
-using Ramstack.Globbing.Internal;
-
-namespace Ramstack.Globbing.Traversal;
-
-///
-/// Represents an asynchronously enumerable file tree structure with customizable filtering and selection options.
-///
-/// The type of the entry in the file tree.
-/// The type of the result.
-public sealed class FileTreeAsyncEnumerable : IAsyncEnumerable
-{
- private readonly TEntry _directory;
- private readonly CancellationToken _cancellationToken;
-
- ///
- /// Gets or sets the glob patterns to include in the enumeration.
- ///
- public required string[] Patterns { get; init; }
-
- ///
- /// Gets or sets the patterns to exclude from the enumeration.
- /// Defaults to an empty array.
- ///
- public string[] Excludes { get; init; } = [];
-
- ///
- /// Gets or sets the matching options to use. Defaults to .
- ///
- public MatchFlags Flags { get; init; } = MatchFlags.Auto;
-
- ///
- /// Gets or sets the predicate that determines whether to recurse into a directory.
- ///
- public Func? ShouldRecursePredicate { get; init; }
-
- ///
- /// Gets or sets the predicate that determines whether to include a file entry in the result set.
- ///
- public Func? ShouldIncludePredicate { get; init; }
-
- ///
- /// Gets or sets a function to extract the name for a file entry.
- ///
- public required Func FileNameSelector { get; init; }
-
- ///
- /// Gets or sets a function that retrieves the child entries of an entry.
- ///
- public required Func> ChildrenSelector { get; init; }
-
- ///
- /// Gets or sets a function that transforms a file entry into a result.
- ///
- public required Func ResultSelector { get; init; }
-
- ///
- /// Initializes a new instance of the class.
- ///
- /// The root directory to start the enumeration from.
- /// An optional cancellation token that may be used to cancel the asynchronous iteration.
- public FileTreeAsyncEnumerable(TEntry directory, CancellationToken cancellationToken = default)
- {
- _directory = directory;
- _cancellationToken = cancellationToken;
- }
-
- ///
- IAsyncEnumerator IAsyncEnumerable.GetAsyncEnumerator(CancellationToken cancellationToken)
- {
- CancellationTokenSource? source = null;
-
- if (_cancellationToken != CancellationToken.None)
- cancellationToken = cancellationToken != CancellationToken.None
- ? (source = CancellationTokenSource.CreateLinkedTokenSource(_cancellationToken, cancellationToken)).Token
- : _cancellationToken;
-
- // ReSharper disable PossiblyMistakenUseOfCancellationToken
- return EnumerateAsync(source, cancellationToken).GetAsyncEnumerator(cancellationToken);
- // ReSharper restore PossiblyMistakenUseOfCancellationToken
- }
-
- private async IAsyncEnumerable EnumerateAsync(CancellationTokenSource? source, [EnumeratorCancellation] CancellationToken cancellationToken)
- {
- try
- {
- var flags = Files.ResolveMatchFlags(Flags);
- var chars = ArrayPool.Shared.Rent(FileTreeEnumerable.DefaultBufferCapacity);
-
- var queue = new Queue<(TEntry Directory, string Path)>();
- queue.Enqueue((_directory, ""));
-
- while (queue.TryDequeue(out var e))
- {
- await foreach (var entry in ChildrenSelector(e.Directory, cancellationToken).ConfigureAwait(false))
- {
- var name = FileNameSelector(entry);
- var fullName = FileTreeHelper.GetFullName(ref chars, e.Path, name);
-
- if (PathHelper.IsMatch(fullName, Excludes, flags))
- continue;
-
- if (ShouldRecursePredicate == null || ShouldRecursePredicate(entry))
- if (PathHelper.IsPartialMatch(fullName, Patterns, flags))
- queue.Enqueue((entry, fullName.ToString()));
-
- if (ShouldIncludePredicate == null || ShouldIncludePredicate(entry))
- if (PathHelper.IsMatch(fullName, Patterns, flags))
- yield return ResultSelector(entry);
- }
- }
-
- ArrayPool.Shared.Return(chars);
- }
- finally
- {
- source?.Dispose();
- }
- }
-}
+using System.Buffers;
+using System.Runtime.CompilerServices;
+
+using Ramstack.Globbing.Internal;
+
+namespace Ramstack.Globbing.Traversal;
+
+///
+/// Represents an asynchronously enumerable file tree structure with customizable filtering and selection options.
+///
+/// The type of the entry in the file tree.
+/// The type of the result.
+public sealed class FileTreeAsyncEnumerable : IAsyncEnumerable
+{
+ private readonly TEntry _directory;
+ private readonly CancellationToken _cancellationToken;
+
+ ///
+ /// Gets or sets the glob patterns to include in the enumeration.
+ ///
+ public required string[] Patterns { get; init; }
+
+ ///
+ /// Gets or sets the patterns to exclude from the enumeration.
+ /// Defaults to an empty array.
+ ///
+ public string[] Excludes { get; init; } = [];
+
+ ///
+ /// Gets or sets the matching options to use. Defaults to .
+ ///
+ public MatchFlags Flags { get; init; } = MatchFlags.Auto;
+
+ ///
+ /// Gets or sets the predicate that determines whether to recurse into a directory.
+ ///
+ public Func? ShouldRecursePredicate { get; init; }
+
+ ///
+ /// Gets or sets the predicate that determines whether to include a file entry in the result set.
+ ///
+ public Func? ShouldIncludePredicate { get; init; }
+
+ ///
+ /// Gets or sets a function to extract the name for a file entry.
+ ///
+ public required Func FileNameSelector { get; init; }
+
+ ///
+ /// Gets or sets a function that retrieves the child entries of an entry.
+ ///
+ public required Func> ChildrenSelector { get; init; }
+
+ ///
+ /// Gets or sets a function that transforms a file entry into a result.
+ ///
+ public required Func ResultSelector { get; init; }
+
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// The root directory to start the enumeration from.
+ /// An optional cancellation token that may be used to cancel the asynchronous iteration.
+ public FileTreeAsyncEnumerable(TEntry directory, CancellationToken cancellationToken = default)
+ {
+ _directory = directory;
+ _cancellationToken = cancellationToken;
+ }
+
+ ///
+ IAsyncEnumerator IAsyncEnumerable.GetAsyncEnumerator(CancellationToken cancellationToken)
+ {
+ CancellationTokenSource? source = null;
+
+ if (_cancellationToken != CancellationToken.None)
+ cancellationToken = cancellationToken != CancellationToken.None
+ ? (source = CancellationTokenSource.CreateLinkedTokenSource(_cancellationToken, cancellationToken)).Token
+ : _cancellationToken;
+
+ // ReSharper disable PossiblyMistakenUseOfCancellationToken
+ return EnumerateAsync(source, cancellationToken).GetAsyncEnumerator(cancellationToken);
+ // ReSharper restore PossiblyMistakenUseOfCancellationToken
+ }
+
+ private async IAsyncEnumerable EnumerateAsync(CancellationTokenSource? source, [EnumeratorCancellation] CancellationToken cancellationToken)
+ {
+ try
+ {
+ var flags = Files.ResolveMatchFlags(Flags);
+ var chars = ArrayPool.Shared.Rent(FileTreeEnumerable.DefaultBufferCapacity);
+
+ var queue = new Queue<(TEntry Directory, string Path)>();
+ queue.Enqueue((_directory, ""));
+
+ while (queue.TryDequeue(out var e))
+ {
+ await foreach (var entry in ChildrenSelector(e.Directory, cancellationToken).ConfigureAwait(false))
+ {
+ var name = FileNameSelector(entry);
+ var fullName = FileTreeHelper.GetFullName(ref chars, e.Path, name);
+
+ if (PathHelper.IsMatch(fullName, Excludes, flags))
+ continue;
+
+ if (ShouldRecursePredicate == null || ShouldRecursePredicate(entry))
+ if (PathHelper.IsPartialMatch(fullName, Patterns, flags))
+ queue.Enqueue((entry, fullName.ToString()));
+
+ if (ShouldIncludePredicate == null || ShouldIncludePredicate(entry))
+ if (PathHelper.IsMatch(fullName, Patterns, flags))
+ yield return ResultSelector(entry);
+ }
+ }
+
+ ArrayPool.Shared.Return(chars);
+ }
+ finally
+ {
+ source?.Dispose();
+ }
+ }
+}
diff --git a/Ramstack.Globbing/Traversal/FileTreeEnumerable.cs b/Ramstack.Globbing/Traversal/FileTreeEnumerable.cs
index 41f5643..6bfd867 100644
--- a/Ramstack.Globbing/Traversal/FileTreeEnumerable.cs
+++ b/Ramstack.Globbing/Traversal/FileTreeEnumerable.cs
@@ -1,107 +1,107 @@
-using System.Buffers;
-using System.Collections;
-
-using Ramstack.Globbing.Internal;
-
-namespace Ramstack.Globbing.Traversal;
-
-///
-/// Represents an enumerable file tree structure with customizable filtering and selection options.
-///
-/// The type of the entry in the file tree.
-/// The type of the result.
-public sealed class FileTreeEnumerable : IEnumerable
-{
- private readonly TEntry _directory;
-
- ///
- /// The default capacity of the character buffer for paths rented from the shared array pool.
- ///
- internal const int DefaultBufferCapacity = 512;
-
- ///
- /// Gets or sets the glob patterns to include in the enumeration.
- ///
- public required string[] Patterns { get; init; }
-
- ///
- /// Gets or sets the patterns to exclude from the enumeration.
- /// Defaults to an empty array.
- ///
- public string[] Excludes { get; init; } = [];
-
- ///
- /// Gets or sets the matching options to use. Defaults to .
- ///
- public MatchFlags Flags { get; init; } = MatchFlags.Auto;
-
- ///
- /// Gets or sets the predicate that determines whether to recurse into a directory.
- ///
- public Func? ShouldRecursePredicate { get; init; }
-
- ///
- /// Gets or sets the predicate that determines whether to include a file entry in the result set.
- ///
- public Func? ShouldIncludePredicate { get; init; }
-
- ///
- /// Gets or sets a function to extract the name for a file entry.
- ///
- public required Func FileNameSelector { get; init; }
-
- ///
- /// Gets or sets a function that retrieves the child entries of an entry.
- ///
- public required Func> ChildrenSelector { get; init; }
-
- ///
- /// Gets or sets a function that transforms a file entry into a result.
- ///
- public required Func ResultSelector { get; init; }
-
- ///
- /// Initializes a new instance of the class.
- ///
- /// The root directory to start the enumeration from.
- public FileTreeEnumerable(TEntry directory) =>
- _directory = directory;
-
- ///
- IEnumerator IEnumerable.GetEnumerator() =>
- Enumerate().GetEnumerator();
-
- ///
- IEnumerator IEnumerable.GetEnumerator() =>
- Enumerate().GetEnumerator();
-
- private IEnumerable Enumerate()
- {
- var flags = Files.ResolveMatchFlags(Flags);
- var chars = ArrayPool.Shared.Rent(DefaultBufferCapacity);
- var queue = new Queue<(TEntry Directory, string Path)>();
- queue.Enqueue((_directory, ""));
-
- while (queue.TryDequeue(out var e))
- {
- foreach (var entry in ChildrenSelector(e.Directory))
- {
- var name = FileNameSelector(entry);
- var fullName = FileTreeHelper.GetFullName(ref chars, e.Path, name);
-
- if (PathHelper.IsMatch(fullName, Excludes, flags))
- continue;
-
- if (ShouldRecursePredicate == null || ShouldRecursePredicate(entry))
- if (PathHelper.IsPartialMatch(fullName, Patterns, flags))
- queue.Enqueue((entry, fullName.ToString()));
-
- if (ShouldIncludePredicate == null || ShouldIncludePredicate(entry))
- if (PathHelper.IsMatch(fullName, Patterns, flags))
- yield return ResultSelector(entry);
- }
- }
-
- ArrayPool.Shared.Return(chars);
- }
-}
+using System.Buffers;
+using System.Collections;
+
+using Ramstack.Globbing.Internal;
+
+namespace Ramstack.Globbing.Traversal;
+
+///
+/// Represents an enumerable file tree structure with customizable filtering and selection options.
+///
+/// The type of the entry in the file tree.
+/// The type of the result.
+public sealed class FileTreeEnumerable : IEnumerable
+{
+ private readonly TEntry _directory;
+
+ ///
+ /// The default capacity of the character buffer for paths rented from the shared array pool.
+ ///
+ internal const int DefaultBufferCapacity = 512;
+
+ ///
+ /// Gets or sets the glob patterns to include in the enumeration.
+ ///
+ public required string[] Patterns { get; init; }
+
+ ///
+ /// Gets or sets the patterns to exclude from the enumeration.
+ /// Defaults to an empty array.
+ ///
+ public string[] Excludes { get; init; } = [];
+
+ ///
+ /// Gets or sets the matching options to use. Defaults to .
+ ///
+ public MatchFlags Flags { get; init; } = MatchFlags.Auto;
+
+ ///
+ /// Gets or sets the predicate that determines whether to recurse into a directory.
+ ///
+ public Func? ShouldRecursePredicate { get; init; }
+
+ ///
+ /// Gets or sets the predicate that determines whether to include a file entry in the result set.
+ ///
+ public Func? ShouldIncludePredicate { get; init; }
+
+ ///
+ /// Gets or sets a function to extract the name for a file entry.
+ ///
+ public required Func FileNameSelector { get; init; }
+
+ ///
+ /// Gets or sets a function that retrieves the child entries of an entry.
+ ///
+ public required Func> ChildrenSelector { get; init; }
+
+ ///
+ /// Gets or sets a function that transforms a file entry into a result.
+ ///
+ public required Func ResultSelector { get; init; }
+
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// The root directory to start the enumeration from.
+ public FileTreeEnumerable(TEntry directory) =>
+ _directory = directory;
+
+ ///
+ IEnumerator IEnumerable.GetEnumerator() =>
+ Enumerate().GetEnumerator();
+
+ ///
+ IEnumerator IEnumerable.GetEnumerator() =>
+ Enumerate().GetEnumerator();
+
+ private IEnumerable Enumerate()
+ {
+ var flags = Files.ResolveMatchFlags(Flags);
+ var chars = ArrayPool.Shared.Rent(DefaultBufferCapacity);
+ var queue = new Queue<(TEntry Directory, string Path)>();
+ queue.Enqueue((_directory, ""));
+
+ while (queue.TryDequeue(out var e))
+ {
+ foreach (var entry in ChildrenSelector(e.Directory))
+ {
+ var name = FileNameSelector(entry);
+ var fullName = FileTreeHelper.GetFullName(ref chars, e.Path, name);
+
+ if (PathHelper.IsMatch(fullName, Excludes, flags))
+ continue;
+
+ if (ShouldRecursePredicate == null || ShouldRecursePredicate(entry))
+ if (PathHelper.IsPartialMatch(fullName, Patterns, flags))
+ queue.Enqueue((entry, fullName.ToString()));
+
+ if (ShouldIncludePredicate == null || ShouldIncludePredicate(entry))
+ if (PathHelper.IsMatch(fullName, Patterns, flags))
+ yield return ResultSelector(entry);
+ }
+ }
+
+ ArrayPool.Shared.Return(chars);
+ }
+}
diff --git a/Ramstack.Globbing/Traversal/Files.Utilities.cs b/Ramstack.Globbing/Traversal/Files.Utilities.cs
index f2da1f5..f8b0387 100644
--- a/Ramstack.Globbing/Traversal/Files.Utilities.cs
+++ b/Ramstack.Globbing/Traversal/Files.Utilities.cs
@@ -1,165 +1,165 @@
-using System.Buffers;
-using System.Diagnostics;
-using System.IO.Enumeration;
-using System.Runtime.CompilerServices;
-
-using Ramstack.Globbing.Internal;
-
-namespace Ramstack.Globbing.Traversal;
-
-partial class Files
-{
- ///
- /// The threshold size in characters for using stack allocation.
- /// This value corresponds to the MAX_PATH constant for paths in Windows.
- ///
- private const int StackallocThreshold = 260;
-
- ///
- /// Determines whether the specified file system entry should be included in the results.
- ///
- /// A file system entry reference.
- /// An array of glob patterns to match against the names of files.
- /// Optional array of glob patterns to exclude files.
- /// The matching options to use.
- /// This parameter must be explicitly set to either or .
- /// is not allowed and will result in an assertion failure.
- /// The search target.
- ///
- /// if the specified file system entry should be included in the results;
- /// otherwise, .
- ///
- internal static bool ShouldInclude(ref FileSystemEntry entry, string[] patterns, string[] excludes, MatchFlags flags, SearchTarget target)
- {
- Debug.Assert(flags != MatchFlags.Auto);
-
- char[]? rented = null;
-
- var current = entry.IsDirectory
- ? SearchTarget.Directories
- : SearchTarget.Files;
-
- var length = GetRelativePathLength(ref entry);
- var relativePath = (uint)length <= StackallocThreshold
- ? stackalloc char[StackallocThreshold]
- : rented = ArrayPool.Shared.Rent(length);
-
- relativePath = relativePath[..length];
- WriteRelativePath(ref entry, relativePath);
- UpdatePathSeparators(relativePath, flags);
-
- var matched = (target & current) != 0
- && PathHelper.IsMatch(relativePath, excludes, flags) == false
- && PathHelper.IsMatch(relativePath, patterns, flags);
-
- if (rented is not null)
- ArrayPool.Shared.Return(rented);
-
- return matched;
- }
-
- ///