|
| 1 | +/* |
| 2 | + * ThreadPilot - path pattern matcher with wildcard support. |
| 3 | + */ |
| 4 | +namespace ThreadPilot.Helpers |
| 5 | +{ |
| 6 | + using System; |
| 7 | + using System.IO; |
| 8 | + |
| 9 | + public static class PathPatternMatcher |
| 10 | + { |
| 11 | + public static bool HasWildcard(string? pattern) => |
| 12 | + !string.IsNullOrEmpty(pattern) && (pattern.Contains('*') || pattern.Contains('?')); |
| 13 | + |
| 14 | + public static bool IsPathMatch(string? pattern, string? path) |
| 15 | + { |
| 16 | + if (string.IsNullOrWhiteSpace(pattern) || string.IsNullOrWhiteSpace(path)) |
| 17 | + { |
| 18 | + return false; |
| 19 | + } |
| 20 | + |
| 21 | + var normalizedPattern = Normalize(pattern); |
| 22 | + var normalizedPath = Normalize(path); |
| 23 | + |
| 24 | + return HasWildcard(normalizedPattern) |
| 25 | + ? MatchesWildcard(normalizedPattern, normalizedPath) |
| 26 | + : string.Equals(normalizedPattern, normalizedPath, StringComparison.OrdinalIgnoreCase); |
| 27 | + } |
| 28 | + |
| 29 | + private static bool MatchesWildcard(string pattern, string path) |
| 30 | + { |
| 31 | + var patternIndex = 0; |
| 32 | + var pathIndex = 0; |
| 33 | + var starIndex = -1; |
| 34 | + var retryPathIndex = -1; |
| 35 | + |
| 36 | + while (pathIndex < path.Length) |
| 37 | + { |
| 38 | + if (patternIndex < pattern.Length && |
| 39 | + (pattern[patternIndex] == '?' || |
| 40 | + pattern.AsSpan(patternIndex, 1).Equals( |
| 41 | + path.AsSpan(pathIndex, 1), |
| 42 | + StringComparison.OrdinalIgnoreCase))) |
| 43 | + { |
| 44 | + patternIndex++; |
| 45 | + pathIndex++; |
| 46 | + } |
| 47 | + else if (patternIndex < pattern.Length && pattern[patternIndex] == '*') |
| 48 | + { |
| 49 | + starIndex = patternIndex++; |
| 50 | + retryPathIndex = pathIndex; |
| 51 | + } |
| 52 | + else if (starIndex >= 0) |
| 53 | + { |
| 54 | + patternIndex = starIndex + 1; |
| 55 | + pathIndex = ++retryPathIndex; |
| 56 | + } |
| 57 | + else |
| 58 | + { |
| 59 | + return false; |
| 60 | + } |
| 61 | + } |
| 62 | + |
| 63 | + while (patternIndex < pattern.Length && pattern[patternIndex] == '*') |
| 64 | + { |
| 65 | + patternIndex++; |
| 66 | + } |
| 67 | + |
| 68 | + return patternIndex == pattern.Length; |
| 69 | + } |
| 70 | + |
| 71 | + private static string Normalize(string path) => |
| 72 | + path.Trim() |
| 73 | + .TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar) |
| 74 | + .Replace(Path.AltDirectorySeparatorChar, Path.DirectorySeparatorChar); |
| 75 | + } |
| 76 | +} |
0 commit comments