-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFilePatternMatcher.cs
More file actions
90 lines (75 loc) · 2.38 KB
/
Copy pathFilePatternMatcher.cs
File metadata and controls
90 lines (75 loc) · 2.38 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
using System.Text.RegularExpressions;
namespace LineEndingNormalizer;
/// <summary>
/// Matches wildcard filenames and relative paths.
/// Patterns without a separator match filenames; patterns with a separator
/// match paths relative to the scan root. '\' is treated as '/'.
/// </summary>
internal static partial class FilePatternMatcher
{
[GeneratedRegex(
"^.*$",
RegexOptions.CultureInvariant)]
private static partial Regex MatchAllRegex();
/// <summary>
/// Returns true when any pattern matches the filename/path.
/// Supports '*' and '?' using a case-insensitive comparison.
/// </summary>
public static bool IsMatch(
string fileName,
IEnumerable<Regex> patterns)
{
foreach (Regex pattern in patterns)
{
if (pattern.IsMatch(fileName))
{
return true;
}
}
return false;
}
/// <summary>
/// Converts wildcard patterns to compiled regexes.
/// </summary>
public static List<Regex> Compile(
List<string> patterns)
{
ArgumentNullException.ThrowIfNull(patterns);
var result =
new List<Regex>(patterns.Count);
foreach (string pattern in patterns)
{
string fileMask =
pattern.Trim();
if (fileMask.Length == 0)
{
continue;
}
// A separator-free mask must match the filename at any depth, not
// just at the scan root, so it needs an optional directory prefix.
bool hasSeparator =
fileMask.Contains('/') ||
fileMask.Contains('\\');
string body =
Regex.Escape(fileMask.Replace('\\', '/'))
.Replace(@"\*", ".*")
.Replace(@"\?", ".");
string anchored =
hasSeparator
? "^" + body + "$"
: "^(?:.*/)?" + body + "$";
result.Add(
new Regex(
anchored,
RegexOptions.IgnoreCase |
RegexOptions.CultureInvariant |
RegexOptions.Compiled));
}
// Empty input means match everything.
if (result.Count == 0)
{
result.Add(MatchAllRegex());
}
return result;
}
}