/
GlobFilter.cs
375 lines (312 loc) · 11.9 KB
/
GlobFilter.cs
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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
#nullable enable
namespace Serenity.IO;
/// <summary>
/// A fast glob implementation, compatible with .gitignore patterns of GIT
/// </summary>
public class GlobFilter
{
private readonly GlobFilter? excludeFilter;
private readonly HashSet<string>? extensions;
private readonly List<string>? startsWith;
private readonly List<string>? endsWith;
private readonly List<string>? contains;
private readonly HashSet<string>? exactMatch;
private readonly List<Tuple<string?, bool, string>>? startsWithAndEndsWith;
private readonly List<Tuple<string, bool, string>>? containsAndEndsWith;
private readonly bool isActive;
private readonly List<Func<string, bool>> matchers;
private readonly char[] DotAsteriskSlashBackQue = ['.', '*', '/', '\\', '?'];
private readonly char[] AsteriskSlashBackQue = ['*', '/', '\\', '?'];
private readonly char[] AsteriskQue = ['*', '?'];
private readonly char[] FolderSeps = ['\\', '/'];
/// <summary>
/// Creates a new GlobFilter, containing both include and exclude patterns.
/// When "include" is null / empty, all files are included by default, unless
/// they match a pattern in "exclude" list.
/// When "exclude" is null, it is ignored.
/// </summary>
/// <param name="include">List of include patterns</param>
/// <param name="exclude">List of exclude patterns</param>
public GlobFilter(IEnumerable<string> include, IEnumerable<string> exclude)
: this(include)
{
if (exclude != null)
{
var excludes = exclude.Where(x => !string.IsNullOrEmpty(x));
if (excludes.Any())
excludeFilter = new GlobFilter(excludes);
}
}
/// <summary>
/// Creates a new GlobFilter, with just "include" globs.
/// </summary>
/// <param name="globs">List of patterns</param>
public GlobFilter(IEnumerable<string> globs)
{
matchers = [];
if (globs == null)
return;
foreach (var glob in globs)
{
if (string.IsNullOrEmpty(glob))
continue;
isActive = true;
var s = glob.Replace('\\', '/');
var starDotIndex = s.IndexOf("*.");
// exact match
if (s[0] == '/' &&
s[^1] != '/' &&
s.IndexOfAny(AsteriskQue, 1) < 0)
{
exactMatch ??= new HashSet<string>(StringComparer.OrdinalIgnoreCase);
exactMatch.Add(s[1..]);
continue;
}
// simple extension filter (*.txt)
if (starDotIndex == 0 &&
s.IndexOfAny(DotAsteriskSlashBackQue, 2) < 0)
{
extensions ??= [];
extensions.Add(s[1..]);
continue;
}
// simple extension filter with extra dot (*.csproj.user)
if (starDotIndex == 0 &&
s.IndexOfAny(AsteriskSlashBackQue, 2) < 0)
{
endsWith ??= [];
endsWith.Add(s[1..]);
continue;
}
// subdirectory under root and extension (/bin/some/*.txt)
if (starDotIndex > 1 &&
s[starDotIndex - 1] == '/' &&
s[0] == '/' &&
s.IndexOfAny(AsteriskSlashBackQue, starDotIndex + 2) < 0 &&
s.LastIndexOfAny(AsteriskQue, starDotIndex - 1) < 0)
{
startsWithAndEndsWith ??= [];
startsWithAndEndsWith.Add(new(s[1..starDotIndex], false, s[(starDotIndex + 1)..]));
continue;
}
// extension under root (/*.txt)
if (starDotIndex == 1 &&
s[0] == '/' &&
s.IndexOfAny(AsteriskSlashBackQue, starDotIndex + 2) < 0)
{
startsWithAndEndsWith ??= [];
startsWithAndEndsWith.Add(new(null, false, s[(starDotIndex + 1)..]));
continue;
}
// directory filter at any depth (.git/)
if (s[^1] == '/' &&
s[0] != '/' &&
s.IndexOfAny(AsteriskQue, 1) < 0)
{
contains ??= [];
startsWith ??= [];
contains.Add('/'.ToString() + s);
startsWith.Add(s);
continue;
}
// directory filter at root (/Imports/)
if (s[^1] == '/' &&
s[0] == '/' &&
s.IndexOfAny(AsteriskQue) < 0)
{
startsWith ??= [];
startsWith.Add(s[1..]);
continue;
}
// folder than any then extension (App_Data/**/*.log) or (/App_Code/**/*.xyz)
if (starDotIndex > 4 &&
s[starDotIndex - 1] == '/' &&
s[starDotIndex - 2] == '*' &&
s[starDotIndex - 3] == '*' &&
s[starDotIndex - 4] == '/' &&
s.LastIndexOfAny(AsteriskQue, starDotIndex - 5) < 0 &&
s.IndexOfAny(AsteriskSlashBackQue, starDotIndex + 2) < 0)
{
startsWithAndEndsWith ??= [];
if (s[0] == '/')
{
startsWithAndEndsWith.Add(new(s.Substring(1, starDotIndex - 4), true, s[(starDotIndex + 1)..]));
}
else
{
containsAndEndsWith ??= [];
startsWithAndEndsWith.Add(new(s[..(starDotIndex - 3)], true, s[(starDotIndex + 1)..]));
containsAndEndsWith.Add(new('/'.ToString() + s[..(starDotIndex - 3)], true, s[(starDotIndex + 1)..]));
}
continue;
}
if (s.IndexOfAny(AsteriskQue) < 0)
{
exactMatch ??= new HashSet<string>(StringComparer.OrdinalIgnoreCase);
if (s[0] == '/')
{
exactMatch.Add(s[..]);
}
else
{
exactMatch.Add(s[..]);
endsWith ??= [];
endsWith.Add('/' + s[..]);
}
continue;
}
if (s[0] == '*' && s.IndexOfAny(AsteriskSlashBackQue, 1) < 0)
{
endsWith ??= [];
endsWith.Add(s[1..]);
continue;
}
if (s[0] == '/' &&
s.Length > 2 &&
s[1] == '*' &&
s.IndexOfAny(AsteriskSlashBackQue, 2) < 0)
{
startsWithAndEndsWith ??= [];
startsWithAndEndsWith.Add(new(null, false, s[2..]));
continue;
}
matchers.Add(ToMatcher(s));
}
}
private static Func<string, bool> ToMatcher(string glob)
{
return ToMatcherRegex(glob);
}
private static Func<string, bool> ToMatcherRegex(string glob)
{
var regex = WildcardToRegex(NormalizeGlob(glob)!);
return regex.IsMatch;
}
/// <summary>
/// Determines whether the specified path is matching this filter.
/// </summary>
/// <param name="path">The path.</param>
/// <returns>
/// <c>true</c> if the specified path is match; otherwise, <c>false</c>.
/// </returns>
public bool IsMatch(string? path)
{
if (string.IsNullOrEmpty(path))
return false;
path = path?.Replace('\\', '/');
if (excludeFilter != null &&
excludeFilter.IsMatch(path))
return false;
if (!isActive)
return true;
if (extensions != null)
{
var extension = System.IO.Path.GetExtension(path);
if (extension != null &&
extensions.Contains(extension))
return true;
}
if (contains != null &&
contains.Any(x => path!.IndexOf(x, StringComparison.OrdinalIgnoreCase) >= 0))
return true;
if (exactMatch != null &&
exactMatch.Contains(path!))
return true;
if (startsWith != null &&
startsWith.Any(x => path!.StartsWith(x, StringComparison.OrdinalIgnoreCase)))
return true;
if (endsWith != null &&
endsWith.Any(x => path!.EndsWith(x, StringComparison.OrdinalIgnoreCase)))
return true;
if (startsWithAndEndsWith != null &&
startsWithAndEndsWith.Any(x =>
{
if (!path!.EndsWith(x.Item3, StringComparison.OrdinalIgnoreCase))
return false;
if (x.Item1 == null)
{
if (path.Length > x.Item3.Length &&
path.LastIndexOfAny(FolderSeps, path.Length - x.Item3.Length - 1) >= 0)
return false;
}
else
{
if (!path.StartsWith(x.Item1, StringComparison.OrdinalIgnoreCase))
return false;
if (!x.Item2 &&
path.IndexOfAny(FolderSeps, x.Item1.Length) >= 0)
{
return false;
}
}
return true;
}))
{
return true;
}
if (containsAndEndsWith != null &&
containsAndEndsWith.Any(x =>
{
if (!path!.EndsWith(x.Item3, StringComparison.OrdinalIgnoreCase))
return false;
if (x.Item1 == null)
{
if (path.Length > x.Item3.Length &&
path.LastIndexOfAny(FolderSeps, path.Length - x.Item3.Length - 1) >= 0)
return false;
}
else
{
var idx = path.IndexOf(x.Item1, StringComparison.OrdinalIgnoreCase);
if (idx < 0)
return false;
if (!x.Item2 &&
path.IndexOfAny(FolderSeps, idx + x.Item1.Length) >= 0)
{
return false;
}
}
return true;
}))
{
return true;
}
if (matchers != null && matchers.Any(x => x(path!)))
return true;
return false;
}
/// <summary>
/// Wildcards to regex conversion. Inspired from NuGet source code.
/// </summary>
/// <param name="wildcard">The wildcard.</param>
private static Regex WildcardToRegex(string wildcard)
{
var pattern = Regex.Escape(wildcard);
pattern = pattern
.Replace(@"\.\*\*", @"\.[^/.]*") // .** should not match on ../file or ./file but will match .file
.Replace(@"\*\*/", "(.+/)*") //For recursive wildcards /**/, include the current directory.
.Replace(@"\*\*", ".*") // For recursive wildcards that don't end in a slash e.g. **.txt would be treated as a .txt file at any depth
.Replace(@"\*", @"[^/]*(/)?") // For non recursive searches, limit it any character that is not a directory separator
.Replace(@"\?", "."); // ? translates to a single any character
return new Regex('^' + pattern + '$', RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.ExplicitCapture | RegexOptions.CultureInvariant);
}
/// <summary>
/// Normalizes the glob by replacing back slashes etc.
/// </summary>
/// <param name="glob">The glob.</param>
/// <returns></returns>
private static string? NormalizeGlob(string? glob)
{
if (string.IsNullOrEmpty(glob))
return glob;
if (glob!.StartsWith("/") ||
glob.StartsWith("\\"))
glob = glob[1..];
else if (!glob.StartsWith("**", StringComparison.Ordinal))
glob = "**/" + glob;
if (glob.EndsWith("/") ||
glob.EndsWith("\\"))
glob += "**/*";
return glob;
}
}