1use std::collections::HashSet;
22use std::ffi::OsStr;
23use std::path::Path;
24
25pub const DEFAULT_EXTENSIONS: &[&str] = &[
27 "c", "cc", "cpp", "cxx", "c++", "h", "hh", "hpp", "hxx", "h++", "inl", "ipp", "tpp", "ixx", "m",
29 "mm", "cs", "csx", "java", "kt", "kts", "rs", "go", "py", "pyi", "rb", "php", "pl", "pm", "lua", "js", "jsx", "ts", "tsx", "mjs",
32 "cjs", "sh", "bash", "zsh", "ps1", "bat", "cmd", "json", "jsonc", "yaml", "yml", "toml", "ini", "cfg", "conf", "xml", "csv", "tsv", "sql",
35 "md", "markdown", "txt", "rst", "proto",
37];
38
39pub const RC_EXTENSIONS: &[&str] = &["rc", "rc2", "dlg"];
42
43pub const MSBUILD_EXTENSIONS: &[&str] = &[
46 "sln", "vcxproj", "vcproj", "props", "targets", "filters", "user",
47];
48
49pub const DEFAULT_EXCLUDE_DIRS: &[&str] = &[
52 "dep",
53 "deps",
54 "third_party",
55 "third-party",
56 "3rdparty",
57 "vendor",
58 "external",
59 "extern",
60 "_tools",
61 "tools_bin",
62 ".svn",
63 ".git",
64 ".hg",
65 ".vs",
66 ".idea",
67 ".vscode",
68 "build",
69 "out",
70 "bin",
71 "obj",
72 "debug",
73 "release",
74 "target",
75 "node_modules",
76 "__pycache__",
77 ".venv",
78 "venv",
79 "temp",
80 "tmp",
81 "cache",
82];
83
84pub const DEFAULT_EXCLUDE_PREFIXES: &[&str] = &["outputfile"];
87
88#[derive(Debug, Clone, Default)]
90pub struct FilterOptions {
91 pub ext_override: Vec<String>,
93 pub exclude_ext: Vec<String>,
95 pub exclude_dirs: Vec<String>,
97 pub exclude_dirs_override: Option<Vec<String>>,
101 pub exclude_globs: Vec<String>,
103 pub include_rc: bool,
105 pub include_msbuild: bool,
107 pub include_hidden: bool,
109}
110
111#[derive(Debug, Clone)]
116pub struct FilterConfig {
117 pub extensions: HashSet<String>,
119 pub exclude_dirs: HashSet<String>,
121 pub exclude_prefixes: Vec<String>,
123 pub exclude_globs: Vec<Glob>,
125 pub include_hidden: bool,
127}
128
129impl FilterConfig {
130 pub fn build(opts: &FilterOptions, ext_source: &str) -> Result<FilterConfig, String> {
133 let exclude_ext: HashSet<String> = normalize_ext_list(&opts.exclude_ext, "--exclude-ext")?;
134
135 if opts.include_rc && RC_EXTENSIONS.iter().any(|e| exclude_ext.contains(*e)) {
138 return Err("--include-rc conflicts with --exclude-ext (rc/rc2/dlg)".to_string());
139 }
140 if opts.include_msbuild && MSBUILD_EXTENSIONS.iter().any(|e| exclude_ext.contains(*e)) {
141 return Err(concat!(
142 "--include-msbuild conflicts with --exclude-ext ",
143 "(sln/vcxproj/vcproj/props/targets/filters/user)"
144 )
145 .to_string());
146 }
147
148 let mut extensions: HashSet<String> = if !opts.ext_override.is_empty() {
152 let normalized = normalize_ext_list(&opts.ext_override, ext_source)?;
153 if normalized.is_empty() {
154 return Err("empty --ext list: no usable extensions".to_string());
155 }
156 normalized
157 } else {
158 let mut base: HashSet<String> = DEFAULT_EXTENSIONS
159 .iter()
160 .map(|s| (*s).to_string())
161 .collect();
162 if opts.include_rc {
163 base.extend(RC_EXTENSIONS.iter().map(|s| (*s).to_string()));
164 }
165 if opts.include_msbuild {
166 base.extend(MSBUILD_EXTENSIONS.iter().map(|s| (*s).to_string()));
167 }
168 base
169 };
170 for e in &exclude_ext {
171 extensions.remove(e);
172 }
173
174 let mut exclude_dirs: HashSet<String> = match &opts.exclude_dirs_override {
175 Some(list) => list
178 .iter()
179 .map(|s| s.trim().to_ascii_lowercase())
180 .filter(|s| !s.is_empty())
181 .collect(),
182 None => DEFAULT_EXCLUDE_DIRS
183 .iter()
184 .map(|s| (*s).to_string())
185 .collect(),
186 };
187 exclude_dirs.extend(normalize_dir_list(&opts.exclude_dirs));
188
189 let exclude_prefixes: Vec<String> = DEFAULT_EXCLUDE_PREFIXES
190 .iter()
191 .map(|s| (*s).to_string())
192 .collect();
193
194 let mut exclude_globs = Vec::new();
195 for pattern in &opts.exclude_globs {
196 match Glob::compile(pattern) {
197 Ok(g) => exclude_globs.push(g),
198 Err(e) => return Err(format!("invalid --exclude-glob `{pattern}`: {e}")),
199 }
200 }
201
202 Ok(FilterConfig {
203 extensions,
204 exclude_dirs,
205 exclude_prefixes,
206 exclude_globs,
207 include_hidden: opts.include_hidden,
208 })
209 }
210
211 pub fn is_excluded_dir_name(&self, name: &OsStr) -> bool {
213 let n = name.to_string_lossy().to_ascii_lowercase();
214 self.exclude_dirs.contains(&n) || self.exclude_prefixes.iter().any(|p| n.starts_with(p))
215 }
216
217 pub fn is_hidden_name(&self, name: &OsStr) -> bool {
219 !self.include_hidden && name.to_string_lossy().starts_with('.')
220 }
221
222 pub fn is_excluded_by_glob(&self, rel_components: &[&str]) -> bool {
224 self.exclude_globs.iter().any(|g| g.matches(rel_components))
225 }
226}
227
228fn normalize_ext_list(values: &[String], source: &str) -> Result<HashSet<String>, String> {
236 let mut out = HashSet::new();
237 for raw in values {
238 let v = raw.trim();
239 let v = v.strip_prefix('.').unwrap_or(v).to_ascii_lowercase();
240 if v.starts_with('.') {
241 return Err(format!(
242 "invalid {source} value `{raw}`: too many leading dots"
243 ));
244 }
245 if v.contains('/') {
246 return Err(format!("invalid {source} value `{raw}`: contains `/`"));
247 }
248 if !v.is_empty() {
249 out.insert(v);
250 }
251 }
252 Ok(out)
253}
254
255fn normalize_dir_list(values: &[String]) -> HashSet<String> {
259 values
260 .iter()
261 .map(|s| s.trim().to_ascii_lowercase())
262 .filter(|s| !s.is_empty())
263 .collect()
264}
265
266pub fn extension_of(path: &Path) -> Option<String> {
269 path.extension()
270 .map(|e| e.to_string_lossy().to_ascii_lowercase())
271}
272
273#[derive(Debug, Clone, PartialEq, Eq)]
284pub struct Glob {
285 parts: Vec<String>,
286}
287
288impl Glob {
289 pub fn compile(pattern: &str) -> Result<Glob, String> {
292 Glob::compile_inner(pattern, true)
293 }
294
295 pub fn compile_raw(pattern: &str) -> Result<Glob, String> {
299 Glob::compile_inner(pattern, false)
300 }
301
302 fn compile_inner(pattern: &str, normalize_backslash: bool) -> Result<Glob, String> {
303 let normalized = if normalize_backslash {
304 pattern.replace('\\', "/")
305 } else {
306 pattern.to_string()
307 };
308 if normalized.contains('[') || normalized.contains('{') {
313 return Err(String::from(
314 "this grammar supports only `*`, `?` and `**`; `[` and `{` are not glob \
315 constructs and would match literally",
316 ));
317 }
318 let parts: Vec<String> = normalized
319 .split('/')
320 .filter(|s| !s.is_empty())
321 .map(|s| collapse_stars(&s.to_ascii_lowercase()))
322 .collect();
323 if parts.is_empty() {
324 return Err("empty pattern".to_string());
325 }
326 Ok(Glob { parts })
327 }
328
329 pub fn matches(&self, components: &[&str]) -> bool {
331 let lowered: Vec<String> = components.iter().map(|c| c.to_ascii_lowercase()).collect();
332 let refs: Vec<&str> = lowered.iter().map(String::as_str).collect();
333 match_parts(&self.parts, &refs)
334 }
335}
336
337fn collapse_stars(component: &str) -> String {
341 if component.chars().all(|c| c == '*') && component.len() >= 2 {
342 return "**".to_string();
343 }
344 let mut out = String::with_capacity(component.len());
345 let mut last_was_star = false;
346 for c in component.chars() {
347 if c == '*' {
348 if !last_was_star {
349 out.push(c);
350 }
351 } else {
352 out.push(c);
353 }
354 last_was_star = c == '*';
355 }
356 out
357}
358
359fn match_parts(pattern: &[String], path: &[&str]) -> bool {
363 let mut pattern_index = 0;
364 let mut path_index = 0;
365 let mut last_star = None;
366
367 while path_index < path.len() {
368 let part = pattern.get(pattern_index);
369 if part.is_some_and(|part| part == "**") {
370 last_star = Some((pattern_index, path_index));
371 pattern_index += 1;
372 } else if part.is_some_and(|part| match_component(part, path[path_index])) {
373 pattern_index += 1;
374 path_index += 1;
375 } else if let Some((star_index, matched_until)) = &mut last_star {
376 *matched_until += 1;
377 path_index = *matched_until;
378 pattern_index = *star_index + 1;
379 } else {
380 return false;
381 }
382 }
383
384 pattern[pattern_index..].iter().all(|part| part == "**")
385}
386
387fn match_component(pattern: &str, text: &str) -> bool {
390 let pattern: Vec<char> = pattern.chars().collect();
391 let text: Vec<char> = text.chars().collect();
392 let mut pattern_index = 0;
393 let mut text_index = 0;
394 let mut last_star = None;
395
396 while text_index < text.len() {
397 let token = pattern.get(pattern_index);
398 if token == Some(&'*') {
399 last_star = Some((pattern_index, text_index));
400 pattern_index += 1;
401 } else if token.is_some_and(|&token| token == '?' || token == text[text_index]) {
402 pattern_index += 1;
403 text_index += 1;
404 } else if let Some((star_index, matched_until)) = &mut last_star {
405 *matched_until += 1;
406 text_index = *matched_until;
407 pattern_index = *star_index + 1;
408 } else {
409 return false;
410 }
411 }
412
413 pattern[pattern_index..].iter().all(|&token| token == '*')
414}
415
416#[cfg(test)]
417mod tests {
418 use super::*;
419
420 #[test]
421 fn glob_double_star_matches_nested_and_root() {
422 let g = Glob::compile("**/Generated/**").unwrap();
423 assert!(g.matches(&["GameServer", "Generated", "a.cpp"]));
424 assert!(g.matches(&["Generated", "b.h"]));
425 assert!(!g.matches(&["GameServer", "a.cpp"]));
426 assert!(!g.matches(&["Generated.cpp"]));
427 }
428
429 #[test]
430 fn glob_is_case_insensitive_and_normalizes_slashes() {
431 let g = Glob::compile("**\\generated\\**").unwrap();
432 assert!(g.matches(&["GameServer", "GENERATED", "x.cpp"]));
433 }
434
435 #[test]
436 fn glob_component_wildcards() {
437 let g = Glob::compile("**/*.tmp.*").unwrap();
438 assert!(g.matches(&["a", "x.tmp.cpp"]));
439 assert!(!g.matches(&["a", "y.cpp"]));
440 let q = Glob::compile("??-gen").unwrap();
441 assert!(q.matches(&["ab-gen"]));
442 assert!(!q.matches(&["abc-gen"]));
443 }
444
445 #[test]
446 fn glob_empty_pattern_rejected() {
447 assert!(Glob::compile("").is_err());
448 assert!(Glob::compile("///").is_err());
449 }
450
451 #[test]
452 fn glob_retries_after_expensive_nonmatching_component() {
453 let pattern = format!("**/{}b.cpp", "*a".repeat(8));
454 let directory = "a".repeat(40);
455 let glob = Glob::compile(&pattern).unwrap();
456 assert!(glob.matches(&[&directory, "aaaaaaaab.cpp"]));
459 assert!(!glob.matches(&[&directory, "aaaaaaaac.cpp"]));
460 }
461
462 #[test]
463 fn glob_handles_long_literals_and_deep_paths_without_recursion() {
464 let literal = "a".repeat(20_000);
465 assert!(Glob::compile(&literal).unwrap().matches(&[&literal]));
466 let components = vec!["a"; 10_000];
467 let pattern = components.join("/");
468 assert!(Glob::compile(&pattern).unwrap().matches(&components));
469 }
470
471 #[test]
472 fn glob_preserves_unicode_and_raw_backslash_semantics() {
473 let glob = Glob::compile("**/?文*.CPP").unwrap();
474 assert!(glob.matches(&["目录", "中文本.cpp"]));
475 assert!(!glob.matches(&["目录", "文.cpp"]));
476 assert!(Glob::compile_raw("a\\?文").unwrap().matches(&["A\\中文"]));
477 assert!(!Glob::compile_raw("a\\?文").unwrap().matches(&["a", "中文"]));
478 }
479
480 fn short_sequences<T: Clone>(alphabet: &[T], max_len: usize) -> Vec<Vec<T>> {
482 let mut all = vec![Vec::new()];
483 let mut level = vec![Vec::new()];
484 for _ in 0..max_len {
485 let mut next = Vec::new();
486 for prefix in &level {
487 for token in alphabet {
488 let mut sequence = prefix.clone();
489 sequence.push(token.clone());
490 next.push(sequence);
491 }
492 }
493 all.extend(next.iter().cloned());
494 level = next;
495 }
496 all
497 }
498
499 fn reference_chars(pattern: &[char], text: &[char]) -> bool {
501 match pattern.first() {
502 None => text.is_empty(),
503 Some('*') => {
504 (0..=text.len()).any(|length| reference_chars(&pattern[1..], &text[length..]))
505 }
506 Some(token) => {
507 text.first()
508 .is_some_and(|first| *token == '?' || token == first)
509 && reference_chars(&pattern[1..], &text[1..])
510 }
511 }
512 }
513
514 fn reference_parts(pattern: &[&str], path: &[&str]) -> bool {
516 match pattern.first() {
517 None => path.is_empty(),
518 Some(&"**") => {
519 (0..=path.len()).any(|length| reference_parts(&pattern[1..], &path[length..]))
520 }
521 Some(part) => {
522 path.first().is_some_and(|component| {
523 reference_chars(
524 &part.chars().collect::<Vec<_>>(),
525 &component.chars().collect::<Vec<_>>(),
526 )
527 }) && reference_parts(&pattern[1..], &path[1..])
528 }
529 }
530 }
531
532 #[test]
533 fn component_matcher_agrees_with_exhaustive_short_input_oracle() {
534 let patterns = short_sequences(&['a', 'b', '?', '*'], 5);
535 let texts = short_sequences(&['a', 'b', '你'], 4);
536 for pattern in &patterns {
537 let pattern_string: String = pattern.iter().collect();
538 for text in &texts {
539 let text_string: String = text.iter().collect();
540 assert_eq!(
541 match_component(&pattern_string, &text_string),
542 reference_chars(pattern, text),
543 "pattern={pattern_string:?}, text={text_string:?}"
544 );
545 }
546 }
547 }
548
549 #[test]
550 fn path_matcher_agrees_with_exhaustive_short_input_oracle() {
551 let patterns = short_sequences(&["a", "b", "?", "a*", "**"], 3);
552 let paths = short_sequences(&["a", "b", "aa", "你"], 3);
553 for pattern in &patterns {
554 let parts: Vec<String> = pattern.iter().map(|part| part.to_string()).collect();
555 for path in &paths {
556 assert_eq!(
557 match_parts(&parts, path),
558 reference_parts(pattern, path),
559 "pattern={pattern:?}, path={path:?}"
560 );
561 }
562 }
563 }
564
565 #[test]
566 fn build_default_whitelist_contains_cpp_not_rc() {
567 let cfg = FilterConfig::build(&FilterOptions::default(), "--ext").unwrap();
568 assert!(cfg.extensions.contains("cpp"));
569 assert!(cfg.extensions.contains("proto"));
570 assert!(!cfg.extensions.contains("rc"));
571 assert!(!cfg.extensions.contains("vcxproj"));
572 }
573
574 #[test]
575 fn build_opt_in_flags_add_their_sets() {
576 let cfg = FilterConfig::build(
577 &FilterOptions {
578 include_rc: true,
579 include_msbuild: true,
580 ..Default::default()
581 },
582 "--ext",
583 )
584 .unwrap();
585 assert!(cfg.extensions.contains("rc"));
586 assert!(cfg.extensions.contains("rc2"));
587 assert!(cfg.extensions.contains("dlg"));
588 assert!(cfg.extensions.contains("vcxproj"));
589 assert!(cfg.extensions.contains("sln"));
590 }
591
592 #[test]
593 fn build_ext_override_replaces_default_set() {
594 let cfg = FilterConfig::build(
595 &FilterOptions {
596 ext_override: vec!["H".into(), "cpp".into()],
597 include_rc: true,
598 ..Default::default()
599 },
600 "--ext",
601 )
602 .unwrap();
603 assert!(cfg.extensions.contains("h"));
604 assert!(cfg.extensions.contains("cpp"));
605 assert!(!cfg.extensions.contains("md"));
606 assert!(!cfg.extensions.contains("rc"));
608 }
609
610 #[test]
611 fn build_exclude_ext_removes_from_whitelist() {
612 let cfg = FilterConfig::build(
613 &FilterOptions {
614 exclude_ext: vec!["CPP".into(), "".into()],
615 ..Default::default()
616 },
617 "--ext",
618 )
619 .unwrap();
620 assert!(!cfg.extensions.contains("cpp"));
621 assert!(cfg.extensions.contains("h"));
622 }
623
624 #[test]
625 fn build_detects_documented_conflicts() {
626 let err = FilterConfig::build(
627 &FilterOptions {
628 include_rc: true,
629 exclude_ext: vec!["rc".into()],
630 ..Default::default()
631 },
632 "--ext",
633 )
634 .unwrap_err();
635 assert!(err.contains("--include-rc"));
636
637 let err = FilterConfig::build(
638 &FilterOptions {
639 include_msbuild: true,
640 exclude_ext: vec!["vcxproj".into()],
641 ..Default::default()
642 },
643 "--ext",
644 )
645 .unwrap_err();
646 assert!(err.contains("--include-msbuild"));
647 }
648
649 #[test]
650 fn build_rejects_bad_glob() {
651 let res = FilterConfig::build(
654 &FilterOptions {
655 exclude_globs: vec!["".into()],
656 ..Default::default()
657 },
658 "--ext",
659 );
660 assert!(res.is_err());
661 }
662
663 #[test]
664 fn excluded_dir_name_is_case_insensitive_with_prefix_rule() {
665 let cfg = FilterConfig::build(
666 &FilterOptions {
667 exclude_dirs: vec!["GameServer201".into()],
668 ..Default::default()
669 },
670 "--ext",
671 )
672 .unwrap();
673 assert!(cfg.is_excluded_dir_name(OsStr::new("dep")));
674 assert!(cfg.is_excluded_dir_name(OsStr::new("DEP")));
675 assert!(cfg.is_excluded_dir_name(OsStr::new(".svn")));
676 assert!(cfg.is_excluded_dir_name(OsStr::new("OutputFile1")));
677 assert!(cfg.is_excluded_dir_name(OsStr::new("OutputFiles")));
678 assert!(cfg.is_excluded_dir_name(OsStr::new("gameserver201")));
679 assert!(!cfg.is_excluded_dir_name(OsStr::new("src")));
680 assert!(!cfg.is_excluded_dir_name(OsStr::new("temp.md")));
681 }
682
683 #[test]
684 fn hidden_respects_include_flag() {
685 let cfg = FilterConfig::build(&FilterOptions::default(), "--ext").unwrap();
686 assert!(cfg.is_hidden_name(OsStr::new(".hidden.cpp")));
687 assert!(!cfg.is_hidden_name(OsStr::new("a.cpp")));
688 let cfg = FilterConfig::build(
689 &FilterOptions {
690 include_hidden: true,
691 ..Default::default()
692 },
693 "--ext",
694 )
695 .unwrap();
696 assert!(!cfg.is_hidden_name(OsStr::new(".hidden.cpp")));
697 }
698
699 #[test]
700 fn extension_of_lowercases() {
701 assert_eq!(extension_of(Path::new("a.CPP")), Some("cpp".to_string()));
702 assert_eq!(extension_of(Path::new("a.tar.gz")), Some("gz".to_string()));
703 assert_eq!(extension_of(Path::new("Makefile")), None);
704 }
705}