1use std::path::Path;
2
3#[cfg(any(windows, unix))]
4use anyhow::Context;
5use anyhow::Result;
6use globset::GlobBuilder;
7#[cfg(not(any(windows, unix)))]
8use globset::{GlobSet, GlobSetBuilder};
9#[cfg(any(windows, unix))]
10use regex_automata::{meta::Regex, util::syntax};
11
12use crate::error::{invalid, invalid_with_source};
13use crate::path::{
14 is_absolute_pattern, is_drive_relative_path, normalize_absolute_for_match, path_matches_prefix,
15 paths_equal,
16};
17
18#[cfg(windows)]
19fn windows_glob_regex(glob: &globset::Glob) -> Result<String> {
20 Ok(format!("(?i:{})", unicode_glob_regex(glob)?))
21}
22
23#[cfg(any(windows, unix))]
24fn unicode_glob_regex(glob: &globset::Glob) -> Result<String> {
25 let byte_regex = glob
26 .regex()
27 .strip_prefix("(?-u)")
28 .context("Glob regex did not use the expected byte mode prefix")?;
29 decode_utf8_regex_literals(byte_regex)
30}
31
32#[cfg(any(windows, unix))]
33fn decode_utf8_regex_literals(regex: &str) -> Result<String> {
34 let bytes = regex.as_bytes();
35 let mut decoded = String::with_capacity(regex.len());
36 let mut offset = 0;
37
38 while offset < bytes.len() {
39 if bytes.get(offset..offset + 2) == Some(br"\\") {
40 decoded.push_str(r"\\");
41 offset += 2;
42 continue;
43 }
44 if let Some((byte, next_offset)) = regex_hex_escape(bytes, offset)
45 && byte >= 0x80
46 {
47 let mut utf8 = vec![byte];
48 offset = next_offset;
49 while let Some((next_byte, after_escape)) = regex_hex_escape(bytes, offset) {
50 if next_byte < 0x80 {
51 break;
52 }
53 utf8.push(next_byte);
54 offset = after_escape;
55 }
56 let literal = std::str::from_utf8(&utf8)
57 .context("Glob regex contained an invalid UTF-8 literal")?;
58 decoded.push_str(literal);
59 continue;
60 }
61
62 let character = regex[offset..]
63 .chars()
64 .next()
65 .context("Glob regex ended unexpectedly")?;
66 decoded.push(character);
67 offset += character.len_utf8();
68 }
69
70 Ok(decoded)
71}
72
73#[cfg(any(windows, unix))]
74fn regex_hex_escape(bytes: &[u8], offset: usize) -> Option<(u8, usize)> {
75 let escape = bytes.get(offset..offset + 4)?;
76 if escape[0] != b'\\' || escape[1] != b'x' {
77 return None;
78 }
79 let high = hex_digit(escape[2])?;
80 let low = hex_digit(escape[3])?;
81 Some(((high << 4) | low, offset + 4))
82}
83
84#[cfg(any(windows, unix))]
85fn hex_digit(byte: u8) -> Option<u8> {
86 match byte {
87 b'0'..=b'9' => Some(byte - b'0'),
88 b'a'..=b'f' => Some(byte - b'a' + 10),
89 b'A'..=b'F' => Some(byte - b'A' + 10),
90 _ => None,
91 }
92}
93
94pub(super) fn compile_patterns(root: &Path, patterns: &[String]) -> Result<CompiledPatterns> {
96 let root_text = normalize_absolute_for_match(&root.to_string_lossy());
97 #[cfg(not(any(windows, unix)))]
98 let mut builder = GlobSetBuilder::new();
99 let mut prefixes = Vec::with_capacity(patterns.len());
100 #[cfg(any(windows, unix))]
101 let mut regexes = Vec::with_capacity(patterns.len());
102
103 for raw in patterns {
104 if raw.is_empty() {
105 return Err(invalid("Pattern must not be empty"));
106 }
107 if raw.split(['/', '\\']).any(|component| component == "..") {
108 return Err(invalid(format!(
109 "Parent directory traversal is not allowed in pattern: {raw}"
110 )));
111 }
112
113 let pattern = normalize_pattern(&root_text, raw)?;
114 let glob = GlobBuilder::new(&pattern)
115 .literal_separator(true)
116 .build()
117 .map_err(|error| invalid_with_source(error, format!("Invalid glob pattern: {raw}")))?;
118 #[cfg(windows)]
119 regexes.push(windows_glob_regex(&glob)?);
120 #[cfg(unix)]
121 regexes.push(unicode_glob_regex(&glob)?);
122 #[cfg(not(any(windows, unix)))]
123 builder.add(glob);
124
125 if !has_glob_syntax(&pattern) {
126 prefixes.push(pattern.trim_end_matches('/').to_owned());
127 }
128 }
129
130 #[cfg(any(windows, unix))]
131 let matcher = Regex::builder()
132 .syntax(syntax::Config::new().dot_matches_new_line(true))
133 .build_many(®exes)
134 .context("Failed to compile keep patterns")?;
135 #[cfg(not(any(windows, unix)))]
136 let matcher = builder.build()?;
137
138 Ok(CompiledPatterns { matcher, prefixes })
139}
140
141fn has_glob_syntax(pattern: &str) -> bool {
147 #[cfg(windows)]
148 const GLOB_SYNTAX: [char; 5] = ['*', '?', '[', '{', '}'];
149 #[cfg(not(windows))]
150 const GLOB_SYNTAX: [char; 6] = ['*', '?', '[', '{', '}', '\\'];
151 pattern.contains(GLOB_SYNTAX)
152}
153
154pub(super) struct CompiledPatterns {
155 #[cfg(any(windows, unix))]
156 matcher: Regex,
157 #[cfg(not(any(windows, unix)))]
158 matcher: GlobSet,
159 prefixes: Vec<String>,
160}
161
162impl CompiledPatterns {
163 pub(super) fn matches(&self, path: &str) -> bool {
164 #[cfg(any(windows, unix))]
165 if self.matcher.is_match(path.as_bytes()) {
166 return true;
167 }
168 #[cfg(not(any(windows, unix)))]
169 if self.matcher.is_match(path) {
170 return true;
171 }
172
173 self.prefixes
174 .iter()
175 .any(|prefix| path_matches_prefix(path, prefix))
176 }
177}
178
179pub(super) fn normalize_pattern(root_text: &str, pattern: &str) -> Result<String> {
181 if is_drive_relative_path(pattern) {
182 return Err(invalid(format!(
183 "Drive-relative patterns are not supported: {pattern}"
184 )));
185 }
186
187 let normalized = normalize_absolute_for_match(pattern);
188 let root_text = normalize_absolute_for_match(root_text);
189
190 if is_absolute_pattern(pattern) {
191 let boundary_root = root_text.trim_end_matches('/');
192 let Some(relative) = strip_case_insensitive_prefix(&normalized, boundary_root) else {
193 return Err(invalid(format!(
194 "Absolute pattern is outside the processing root: {pattern}"
195 )));
196 };
197 Ok(normalize_relative_pattern(relative))
198 } else {
199 Ok(normalize_relative_pattern(&normalized))
200 }
201}
202
203fn normalize_relative_pattern(pattern: &str) -> String {
204 pattern
205 .split('/')
206 .filter(|component| !component.is_empty() && *component != ".")
207 .collect::<Vec<_>>()
208 .join("/")
209}
210
211fn strip_case_insensitive_prefix<'a>(path: &'a str, prefix: &str) -> Option<&'a str> {
212 let mut path_chars = path.char_indices();
213 let mut prefix_bytes = 0;
214 for _ in prefix.chars() {
215 let (index, character) = path_chars.next()?;
216 prefix_bytes = index + character.len_utf8();
217 }
218 if !paths_equal(&path[..prefix_bytes], prefix) {
219 return None;
220 }
221 let suffix = &path[prefix_bytes..];
222 if suffix.is_empty() {
223 Some(suffix)
224 } else {
225 suffix.strip_prefix('/')
226 }
227}
228
229#[cfg(all(test, unix))]
230mod unix_tests {
231 use globset::GlobBuilder;
232 use regex_automata::meta::Regex;
233
234 use super::unicode_glob_regex;
235
236 fn compile_unix_glob(pattern: &str) -> Regex {
237 let glob = GlobBuilder::new(pattern)
238 .literal_separator(true)
239 .build()
240 .unwrap();
241 Regex::new(&unicode_glob_regex(&glob).unwrap()).unwrap()
242 }
243
244 #[test]
245 fn question_mark_matches_one_unicode_scalar_without_crossing_separators() {
246 let matcher = compile_unix_glob("?.txt");
247 assert!(matcher.is_match("é.txt".as_bytes()));
248 assert!(matcher.is_match("あ.txt".as_bytes()));
249 assert!(!matcher.is_match("e\u{301}.txt".as_bytes()));
250 assert!(!matcher.is_match("ee.txt".as_bytes()));
251 assert!(!matcher.is_match("nested/é.txt".as_bytes()));
252 }
253
254 #[test]
255 fn question_marks_match_each_scalar_in_a_combining_sequence() {
256 let matcher = compile_unix_glob("??.txt");
257 assert!(matcher.is_match("e\u{301}.txt".as_bytes()));
258 assert!(!matcher.is_match("é.txt".as_bytes()));
259 }
260
261 #[test]
262 fn character_classes_match_unicode_scalars_and_ranges() {
263 let listed = compile_unix_glob("[éあ].txt");
264 assert!(listed.is_match("é.txt".as_bytes()));
265 assert!(listed.is_match("あ.txt".as_bytes()));
266 assert!(!listed.is_match("è.txt".as_bytes()));
267 assert!(!listed.is_match("e\u{301}.txt".as_bytes()));
268
269 let range = compile_unix_glob("[è-ê].txt");
270 assert!(range.is_match("è.txt".as_bytes()));
271 assert!(range.is_match("é.txt".as_bytes()));
272 assert!(range.is_match("ê.txt".as_bytes()));
273 assert!(!range.is_match("ë.txt".as_bytes()));
274
275 let negated = compile_unix_glob("[!é].txt");
276 assert!(!negated.is_match("é.txt".as_bytes()));
277 assert!(negated.is_match("è.txt".as_bytes()));
278 assert!(!negated.is_match("e\u{301}.txt".as_bytes()));
279 }
280
281 #[test]
282 fn unicode_matching_preserves_case_and_glob_separator_rules() {
283 let case_sensitive = compile_unix_glob("é.txt");
284 assert!(case_sensitive.is_match("é.txt".as_bytes()));
285 assert!(!case_sensitive.is_match("É.txt".as_bytes()));
286
287 let single_level = compile_unix_glob("*.txt");
288 assert!(single_level.is_match("é.txt".as_bytes()));
289 assert!(!single_level.is_match("nested/é.txt".as_bytes()));
290
291 let recursive = compile_unix_glob("**/*.txt");
292 assert!(recursive.is_match("é.txt".as_bytes()));
293 assert!(recursive.is_match("nested/é.txt".as_bytes()));
294 }
295
296 #[test]
297 fn escaped_glob_characters_remain_literal() {
298 let matcher = compile_unix_glob(r"\*.txt");
299 assert!(matcher.is_match("*.txt".as_bytes()));
300 assert!(!matcher.is_match("x.txt".as_bytes()));
301 }
302}
303
304#[cfg(test)]
305mod normalization_tests {
306 use super::normalize_pattern;
307
308 #[cfg(any(windows, unix))]
309 #[test]
310 fn recursive_globs_preserve_newline_matching() {
311 for (pattern, path) in [
312 ("**", "a\nb"),
313 ("dir/**", "dir/a\nb"),
314 ("**/x", "a\nb/x"),
315 ("dir/**/x", "dir/a\nb/x"),
316 ("**/*.txt", "a\nb/nested/file.txt"),
317 ] {
318 let compiled =
319 super::compile_patterns(std::path::Path::new("/work"), &[pattern.to_owned()])
320 .unwrap();
321 assert!(compiled.matches(path), "{pattern:?} should keep {path:?}");
322 }
323 }
324
325 #[cfg(any(windows, unix))]
326 #[test]
327 fn regex_literal_decoding_preserves_escaped_backslashes() {
328 for regex in [
329 r"^\\x80\.txt$",
330 r"^\\xC3\.txt$",
331 r"^\\xc3\\xa9\.txt$",
332 r"^[\\x80]\.txt$",
333 ] {
334 assert_eq!(super::decode_utf8_regex_literals(regex).unwrap(), regex);
335 }
336 assert_eq!(
337 super::decode_utf8_regex_literals(r"^\\x80\xc3\xa9\.txt$").unwrap(),
338 "^\\\\x80é\\.txt$"
339 );
340 }
341
342 #[test]
343 fn root_patterns_normalize_to_an_empty_relative_pattern() {
344 assert_eq!(normalize_pattern("/work", ".").unwrap(), "");
345 assert_eq!(normalize_pattern("/work", "./").unwrap(), "");
346 assert_eq!(normalize_pattern("/work", "./.").unwrap(), "");
347 }
348
349 #[test]
350 fn normalizes_dot_components_and_repeated_separators() {
351 assert_eq!(
352 normalize_pattern("/work", "nested/./keep//file.txt").unwrap(),
353 "nested/keep/file.txt"
354 );
355 assert_eq!(
356 normalize_pattern("/work", "/work/nested//./keep.txt").unwrap(),
357 "nested/keep.txt"
358 );
359 }
360
361 #[cfg(windows)]
362 #[test]
363 fn normalizes_windows_separators_in_absolute_patterns() {
364 assert_eq!(
365 normalize_pattern("C:/work", r"C:\work\nested\.\keep.txt").unwrap(),
366 "nested/keep.txt"
367 );
368 assert_eq!(
369 normalize_pattern("C:/work", r"C:\work\nested\\keep.txt").unwrap(),
370 "nested/keep.txt"
371 );
372 }
373
374 #[test]
375 fn preserves_whitespace_in_patterns() {
376 assert_eq!(
377 normalize_pattern("/work", " keep.txt ").unwrap(),
378 " keep.txt "
379 );
380 }
381
382 #[test]
383 fn absolute_sibling_with_shared_text_prefix_is_outside_root() {
384 let temp = assert_fs::TempDir::new().unwrap();
385 let root = temp.path().join("work");
386 let sibling_pattern = temp.path().join("work-sibling").join("*");
387
388 let error = normalize_pattern(&root.to_string_lossy(), &sibling_pattern.to_string_lossy())
389 .unwrap_err();
390
391 assert!(error.to_string().contains("outside the processing root"));
392 }
393}
394
395#[cfg(all(test, windows))]
396mod tests {
397 use anyhow::Context;
398 use globset::GlobBuilder;
399 use regex_automata::meta::Regex;
400
401 use super::{decode_utf8_regex_literals, normalize_pattern, windows_glob_regex};
402
403 fn compile_windows_glob(pattern: &str) -> Regex {
404 let glob = GlobBuilder::new(pattern)
405 .literal_separator(true)
406 .build()
407 .unwrap();
408 Regex::new(&windows_glob_regex(&glob).unwrap()).unwrap()
409 }
410
411 #[test]
412 fn windows_glob_uses_unicode_simple_case_folding() {
413 let umlaut = compile_windows_glob("ä.txt");
414 assert!(umlaut.is_match("Ä.txt".as_bytes()));
415
416 let sharp_s = compile_windows_glob("ß.txt");
417 assert!(sharp_s.is_match("ẞ.txt".as_bytes()));
418 assert!(!sharp_s.is_match("SS.txt".as_bytes()));
419 }
420
421 #[test]
422 fn windows_question_mark_matches_one_unicode_scalar() {
423 let matcher = compile_windows_glob("?.txt");
424 assert!(matcher.is_match("é.txt".as_bytes()));
425 assert!(!matcher.is_match("ee.txt".as_bytes()));
426 }
427
428 #[test]
429 fn windows_character_classes_keep_glob_syntax_under_case_folding() {
430 let matcher = compile_windows_glob("[Ä].txt");
431 assert!(matcher.is_match("ä.txt".as_bytes()));
432 assert!(!matcher.is_match("b.txt".as_bytes()));
433 }
434
435 #[test]
436 fn windows_globs_preserve_recursive_and_single_level_separators() {
437 let recursive = compile_windows_glob("root/**/*.txt");
438 assert!(recursive.is_match("ROOT/Ä.txt".as_bytes()));
439 assert!(recursive.is_match("root/nested/ä.txt".as_bytes()));
440
441 let single_level = compile_windows_glob("root/*.txt");
442 assert!(single_level.is_match("ROOT/Ä.txt".as_bytes()));
443 assert!(!single_level.is_match("root/nested/ä.txt".as_bytes()));
444 }
445
446 #[test]
447 fn absolute_pattern_boundary_uses_simple_fold_without_byte_length_assumptions() {
448 assert_eq!(
449 normalize_pattern("C:/Keep", "c:/Keep/file.txt").unwrap(),
450 "file.txt"
451 );
452 assert!(normalize_pattern("C:/keep", "c:/keeping/file.txt").is_err());
453 }
454
455 #[test]
456 fn decodes_non_ascii_literals_without_rewriting_regex_syntax() {
457 let glob = GlobBuilder::new("[Ä]?.txt")
458 .literal_separator(true)
459 .build()
460 .unwrap();
461 let decoded = decode_utf8_regex_literals(
462 glob.regex()
463 .strip_prefix("(?-u)")
464 .context("expected byte regex mode")
465 .unwrap(),
466 )
467 .unwrap();
468 assert!(decoded.contains("[Ä]"));
469 assert!(decoded.contains("[^/]"));
470 }
471}