|
1 | 1 | // Copyright (c) Microsoft. All rights reserved. |
2 | 2 | // Licensed under the MIT license. See LICENSE file in the project root for full license information. |
3 | 3 |
|
| 4 | +using System; |
4 | 5 | using System.IO; |
5 | 6 | using System.Text.RegularExpressions; |
6 | 7 |
|
@@ -29,20 +30,33 @@ public static bool IsMatch(string filePath, string pattern, string basePath = nu |
29 | 30 | // Normalize the file path |
30 | 31 | var normalizedFilePath = Path.GetFullPath(filePath); |
31 | 32 |
|
32 | | - // If basePath is provided and pattern is relative, create the full pattern |
33 | | - string normalizedPattern; |
| 33 | + // If basePath is provided and pattern is relative, we need to check if the file |
| 34 | + // is within the base path and then match against the relative portion |
| 35 | + string patternToMatch; |
34 | 36 | if (!string.IsNullOrEmpty(basePath) && !Path.IsPathRooted(pattern)) |
35 | 37 | { |
36 | | - var combinedPath = Path.Combine(basePath, pattern); |
37 | | - normalizedPattern = Path.GetFullPath(combinedPath); |
| 38 | + var normalizedBasePath = Path.GetFullPath(basePath); |
| 39 | + |
| 40 | + // Check if the file is within the base path |
| 41 | + if (!normalizedFilePath.StartsWith(normalizedBasePath, StringComparison.OrdinalIgnoreCase)) |
| 42 | + { |
| 43 | + return false; |
| 44 | + } |
| 45 | + |
| 46 | + // Get the relative path from the base path |
| 47 | + var relativePath = Path.GetRelativePath(normalizedBasePath, normalizedFilePath); |
| 48 | + |
| 49 | + // Match the relative path against the pattern |
| 50 | + patternToMatch = pattern; |
| 51 | + normalizedFilePath = relativePath; |
38 | 52 | } |
39 | 53 | else |
40 | 54 | { |
41 | | - normalizedPattern = pattern; |
| 55 | + patternToMatch = pattern; |
42 | 56 | } |
43 | 57 |
|
44 | 58 | // Convert glob pattern to regex |
45 | | - var regexPattern = ConvertGlobToRegex(normalizedPattern); |
| 59 | + var regexPattern = ConvertGlobToRegex(patternToMatch); |
46 | 60 |
|
47 | 61 | // Perform case-insensitive matching for cross-platform compatibility |
48 | 62 | var regex = new Regex(regexPattern, RegexOptions.IgnoreCase); |
@@ -101,7 +115,7 @@ private static string ConvertGlobToRegex(string globPattern) |
101 | 115 | } |
102 | 116 | } |
103 | 117 |
|
104 | | - // Anchor the pattern to match from the beginning |
105 | | - return "^" + regexPattern.ToString() + ".*$"; |
| 118 | + // Don't anchor to end with .* since we want exact path matching |
| 119 | + return "^" + regexPattern.ToString() + "$"; |
106 | 120 | } |
107 | 121 | } |
0 commit comments