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_globs: Vec<String>,
99 pub include_rc: bool,
101 pub include_msbuild: bool,
103 pub include_hidden: bool,
105}
106
107#[derive(Debug, Clone)]
112pub struct FilterConfig {
113 pub extensions: HashSet<String>,
115 pub exclude_dirs: HashSet<String>,
117 pub exclude_prefixes: Vec<String>,
119 pub exclude_globs: Vec<Glob>,
121 pub include_hidden: bool,
123}
124
125impl FilterConfig {
126 pub fn build(opts: &FilterOptions) -> Result<FilterConfig, String> {
129 let exclude_ext: HashSet<String> = normalize_ext_list(&opts.exclude_ext)?;
130
131 if opts.include_rc && RC_EXTENSIONS.iter().any(|e| exclude_ext.contains(*e)) {
134 return Err("--include-rc conflicts with --exclude-ext (rc/rc2/dlg)".to_string());
135 }
136 if opts.include_msbuild && MSBUILD_EXTENSIONS.iter().any(|e| exclude_ext.contains(*e)) {
137 return Err(concat!(
138 "--include-msbuild conflicts with --exclude-ext ",
139 "(sln/vcxproj/vcproj/props/targets/filters/user)"
140 )
141 .to_string());
142 }
143
144 let mut extensions: HashSet<String> = if !opts.ext_override.is_empty() {
148 let normalized = normalize_ext_list(&opts.ext_override)?;
149 if normalized.is_empty() {
150 return Err("empty --ext list: no usable extensions".to_string());
151 }
152 normalized
153 } else {
154 let mut base: HashSet<String> = DEFAULT_EXTENSIONS
155 .iter()
156 .map(|s| (*s).to_string())
157 .collect();
158 if opts.include_rc {
159 base.extend(RC_EXTENSIONS.iter().map(|s| (*s).to_string()));
160 }
161 if opts.include_msbuild {
162 base.extend(MSBUILD_EXTENSIONS.iter().map(|s| (*s).to_string()));
163 }
164 base
165 };
166 for e in &exclude_ext {
167 extensions.remove(e);
168 }
169
170 let mut exclude_dirs: HashSet<String> = DEFAULT_EXCLUDE_DIRS
171 .iter()
172 .map(|s| (*s).to_string())
173 .collect();
174 exclude_dirs.extend(normalize_dir_list(&opts.exclude_dirs));
175
176 let exclude_prefixes: Vec<String> = DEFAULT_EXCLUDE_PREFIXES
177 .iter()
178 .map(|s| (*s).to_string())
179 .collect();
180
181 let mut exclude_globs = Vec::new();
182 for pattern in &opts.exclude_globs {
183 match Glob::compile(pattern) {
184 Ok(g) => exclude_globs.push(g),
185 Err(e) => return Err(format!("invalid --exclude-glob `{pattern}`: {e}")),
186 }
187 }
188
189 Ok(FilterConfig {
190 extensions,
191 exclude_dirs,
192 exclude_prefixes,
193 exclude_globs,
194 include_hidden: opts.include_hidden,
195 })
196 }
197
198 pub fn is_excluded_dir_name(&self, name: &OsStr) -> bool {
200 let n = name.to_string_lossy().to_ascii_lowercase();
201 self.exclude_dirs.contains(&n) || self.exclude_prefixes.iter().any(|p| n.starts_with(p))
202 }
203
204 pub fn is_hidden_name(&self, name: &OsStr) -> bool {
206 !self.include_hidden && name.to_string_lossy().starts_with('.')
207 }
208
209 pub fn is_excluded_by_glob(&self, rel_components: &[&str]) -> bool {
211 self.exclude_globs.iter().any(|g| g.matches(rel_components))
212 }
213}
214
215fn normalize_ext_list(values: &[String]) -> Result<HashSet<String>, String> {
223 let mut out = HashSet::new();
224 for raw in values {
225 let v = raw.trim();
226 let v = v.strip_prefix('.').unwrap_or(v).to_ascii_lowercase();
227 if v.starts_with('.') {
228 return Err(format!(
229 "invalid extension value `{raw}`: too many leading dots"
230 ));
231 }
232 if v.contains('/') {
233 return Err(format!("invalid extension value `{raw}`: contains `/`"));
234 }
235 if !v.is_empty() {
236 out.insert(v);
237 }
238 }
239 Ok(out)
240}
241
242fn normalize_dir_list(values: &[String]) -> HashSet<String> {
246 values
247 .iter()
248 .map(|s| s.trim().to_ascii_lowercase())
249 .filter(|s| !s.is_empty())
250 .collect()
251}
252
253pub fn extension_of(path: &Path) -> Option<String> {
256 path.extension()
257 .map(|e| e.to_string_lossy().to_ascii_lowercase())
258}
259
260#[derive(Debug, Clone, PartialEq, Eq)]
271pub struct Glob {
272 parts: Vec<String>,
273}
274
275impl Glob {
276 pub fn compile(pattern: &str) -> Result<Glob, String> {
279 Glob::compile_inner(pattern, true)
280 }
281
282 pub fn compile_raw(pattern: &str) -> Result<Glob, String> {
286 Glob::compile_inner(pattern, false)
287 }
288
289 fn compile_inner(pattern: &str, normalize_backslash: bool) -> Result<Glob, String> {
290 let normalized = if normalize_backslash {
291 pattern.replace('\\', "/")
292 } else {
293 pattern.to_string()
294 };
295 let parts: Vec<String> = normalized
296 .split('/')
297 .filter(|s| !s.is_empty())
298 .map(|s| collapse_stars(&s.to_ascii_lowercase()))
299 .collect();
300 if parts.is_empty() {
301 return Err("empty pattern".to_string());
302 }
303 Ok(Glob { parts })
304 }
305
306 pub fn matches(&self, components: &[&str]) -> bool {
308 let lowered: Vec<String> = components.iter().map(|c| c.to_ascii_lowercase()).collect();
309 let refs: Vec<&str> = lowered.iter().map(String::as_str).collect();
310 match_parts(&self.parts, &refs)
311 }
312}
313
314fn collapse_stars(component: &str) -> String {
318 if component.chars().all(|c| c == '*') && component.len() >= 2 {
319 return "**".to_string();
320 }
321 let mut out = String::with_capacity(component.len());
322 let mut last_was_star = false;
323 for c in component.chars() {
324 if c == '*' {
325 if !last_was_star {
326 out.push(c);
327 }
328 } else {
329 out.push(c);
330 }
331 last_was_star = c == '*';
332 }
333 out
334}
335
336fn match_parts(pattern: &[String], path: &[&str]) -> bool {
340 let mut pattern_index = 0;
341 let mut path_index = 0;
342 let mut last_star = None;
343
344 while path_index < path.len() {
345 let part = pattern.get(pattern_index);
346 if part.is_some_and(|part| part == "**") {
347 last_star = Some((pattern_index, path_index));
348 pattern_index += 1;
349 } else if part.is_some_and(|part| match_component(part, path[path_index])) {
350 pattern_index += 1;
351 path_index += 1;
352 } else if let Some((star_index, matched_until)) = &mut last_star {
353 *matched_until += 1;
354 path_index = *matched_until;
355 pattern_index = *star_index + 1;
356 } else {
357 return false;
358 }
359 }
360
361 pattern[pattern_index..].iter().all(|part| part == "**")
362}
363
364fn match_component(pattern: &str, text: &str) -> bool {
367 let pattern: Vec<char> = pattern.chars().collect();
368 let text: Vec<char> = text.chars().collect();
369 let mut pattern_index = 0;
370 let mut text_index = 0;
371 let mut last_star = None;
372
373 while text_index < text.len() {
374 let token = pattern.get(pattern_index);
375 if token == Some(&'*') {
376 last_star = Some((pattern_index, text_index));
377 pattern_index += 1;
378 } else if token.is_some_and(|&token| token == '?' || token == text[text_index]) {
379 pattern_index += 1;
380 text_index += 1;
381 } else if let Some((star_index, matched_until)) = &mut last_star {
382 *matched_until += 1;
383 text_index = *matched_until;
384 pattern_index = *star_index + 1;
385 } else {
386 return false;
387 }
388 }
389
390 pattern[pattern_index..].iter().all(|&token| token == '*')
391}
392
393#[cfg(test)]
394mod tests {
395 use super::*;
396
397 #[test]
398 fn glob_double_star_matches_nested_and_root() {
399 let g = Glob::compile("**/Generated/**").unwrap();
400 assert!(g.matches(&["GameServer", "Generated", "a.cpp"]));
401 assert!(g.matches(&["Generated", "b.h"]));
402 assert!(!g.matches(&["GameServer", "a.cpp"]));
403 assert!(!g.matches(&["Generated.cpp"]));
404 }
405
406 #[test]
407 fn glob_is_case_insensitive_and_normalizes_slashes() {
408 let g = Glob::compile("**\\generated\\**").unwrap();
409 assert!(g.matches(&["GameServer", "GENERATED", "x.cpp"]));
410 }
411
412 #[test]
413 fn glob_component_wildcards() {
414 let g = Glob::compile("**/*.tmp.*").unwrap();
415 assert!(g.matches(&["a", "x.tmp.cpp"]));
416 assert!(!g.matches(&["a", "y.cpp"]));
417 let q = Glob::compile("??-gen").unwrap();
418 assert!(q.matches(&["ab-gen"]));
419 assert!(!q.matches(&["abc-gen"]));
420 }
421
422 #[test]
423 fn glob_empty_pattern_rejected() {
424 assert!(Glob::compile("").is_err());
425 assert!(Glob::compile("///").is_err());
426 }
427
428 #[test]
429 fn glob_retries_after_expensive_nonmatching_component() {
430 let pattern = format!("**/{}b.cpp", "*a".repeat(8));
431 let directory = "a".repeat(40);
432 let glob = Glob::compile(&pattern).unwrap();
433 assert!(glob.matches(&[&directory, "aaaaaaaab.cpp"]));
436 assert!(!glob.matches(&[&directory, "aaaaaaaac.cpp"]));
437 }
438
439 #[test]
440 fn glob_handles_long_literals_and_deep_paths_without_recursion() {
441 let literal = "a".repeat(20_000);
442 assert!(Glob::compile(&literal).unwrap().matches(&[&literal]));
443 let components = vec!["a"; 10_000];
444 let pattern = components.join("/");
445 assert!(Glob::compile(&pattern).unwrap().matches(&components));
446 }
447
448 #[test]
449 fn glob_preserves_unicode_and_raw_backslash_semantics() {
450 let glob = Glob::compile("**/?文*.CPP").unwrap();
451 assert!(glob.matches(&["目录", "中文本.cpp"]));
452 assert!(!glob.matches(&["目录", "文.cpp"]));
453 assert!(Glob::compile_raw("a\\?文").unwrap().matches(&["A\\中文"]));
454 assert!(!Glob::compile_raw("a\\?文").unwrap().matches(&["a", "中文"]));
455 }
456
457 fn short_sequences<T: Clone>(alphabet: &[T], max_len: usize) -> Vec<Vec<T>> {
459 let mut all = vec![Vec::new()];
460 let mut level = vec![Vec::new()];
461 for _ in 0..max_len {
462 let mut next = Vec::new();
463 for prefix in &level {
464 for token in alphabet {
465 let mut sequence = prefix.clone();
466 sequence.push(token.clone());
467 next.push(sequence);
468 }
469 }
470 all.extend(next.iter().cloned());
471 level = next;
472 }
473 all
474 }
475
476 fn reference_chars(pattern: &[char], text: &[char]) -> bool {
478 match pattern.first() {
479 None => text.is_empty(),
480 Some('*') => {
481 (0..=text.len()).any(|length| reference_chars(&pattern[1..], &text[length..]))
482 }
483 Some(token) => {
484 text.first()
485 .is_some_and(|first| *token == '?' || token == first)
486 && reference_chars(&pattern[1..], &text[1..])
487 }
488 }
489 }
490
491 fn reference_parts(pattern: &[&str], path: &[&str]) -> bool {
493 match pattern.first() {
494 None => path.is_empty(),
495 Some(&"**") => {
496 (0..=path.len()).any(|length| reference_parts(&pattern[1..], &path[length..]))
497 }
498 Some(part) => {
499 path.first().is_some_and(|component| {
500 reference_chars(
501 &part.chars().collect::<Vec<_>>(),
502 &component.chars().collect::<Vec<_>>(),
503 )
504 }) && reference_parts(&pattern[1..], &path[1..])
505 }
506 }
507 }
508
509 #[test]
510 fn component_matcher_agrees_with_exhaustive_short_input_oracle() {
511 let patterns = short_sequences(&['a', 'b', '?', '*'], 5);
512 let texts = short_sequences(&['a', 'b', '你'], 4);
513 for pattern in &patterns {
514 let pattern_string: String = pattern.iter().collect();
515 for text in &texts {
516 let text_string: String = text.iter().collect();
517 assert_eq!(
518 match_component(&pattern_string, &text_string),
519 reference_chars(pattern, text),
520 "pattern={pattern_string:?}, text={text_string:?}"
521 );
522 }
523 }
524 }
525
526 #[test]
527 fn path_matcher_agrees_with_exhaustive_short_input_oracle() {
528 let patterns = short_sequences(&["a", "b", "?", "a*", "**"], 3);
529 let paths = short_sequences(&["a", "b", "aa", "你"], 3);
530 for pattern in &patterns {
531 let parts: Vec<String> = pattern.iter().map(|part| part.to_string()).collect();
532 for path in &paths {
533 assert_eq!(
534 match_parts(&parts, path),
535 reference_parts(pattern, path),
536 "pattern={pattern:?}, path={path:?}"
537 );
538 }
539 }
540 }
541
542 #[test]
543 fn build_default_whitelist_contains_cpp_not_rc() {
544 let cfg = FilterConfig::build(&FilterOptions::default()).unwrap();
545 assert!(cfg.extensions.contains("cpp"));
546 assert!(cfg.extensions.contains("proto"));
547 assert!(!cfg.extensions.contains("rc"));
548 assert!(!cfg.extensions.contains("vcxproj"));
549 }
550
551 #[test]
552 fn build_opt_in_flags_add_their_sets() {
553 let cfg = FilterConfig::build(&FilterOptions {
554 include_rc: true,
555 include_msbuild: true,
556 ..Default::default()
557 })
558 .unwrap();
559 assert!(cfg.extensions.contains("rc"));
560 assert!(cfg.extensions.contains("rc2"));
561 assert!(cfg.extensions.contains("dlg"));
562 assert!(cfg.extensions.contains("vcxproj"));
563 assert!(cfg.extensions.contains("sln"));
564 }
565
566 #[test]
567 fn build_ext_override_replaces_default_set() {
568 let cfg = FilterConfig::build(&FilterOptions {
569 ext_override: vec!["H".into(), "cpp".into()],
570 include_rc: true,
571 ..Default::default()
572 })
573 .unwrap();
574 assert!(cfg.extensions.contains("h"));
575 assert!(cfg.extensions.contains("cpp"));
576 assert!(!cfg.extensions.contains("md"));
577 assert!(!cfg.extensions.contains("rc"));
579 }
580
581 #[test]
582 fn build_exclude_ext_removes_from_whitelist() {
583 let cfg = FilterConfig::build(&FilterOptions {
584 exclude_ext: vec!["CPP".into(), "".into()],
585 ..Default::default()
586 })
587 .unwrap();
588 assert!(!cfg.extensions.contains("cpp"));
589 assert!(cfg.extensions.contains("h"));
590 }
591
592 #[test]
593 fn build_detects_documented_conflicts() {
594 let err = FilterConfig::build(&FilterOptions {
595 include_rc: true,
596 exclude_ext: vec!["rc".into()],
597 ..Default::default()
598 })
599 .unwrap_err();
600 assert!(err.contains("--include-rc"));
601
602 let err = FilterConfig::build(&FilterOptions {
603 include_msbuild: true,
604 exclude_ext: vec!["vcxproj".into()],
605 ..Default::default()
606 })
607 .unwrap_err();
608 assert!(err.contains("--include-msbuild"));
609 }
610
611 #[test]
612 fn build_rejects_bad_glob() {
613 let res = FilterConfig::build(&FilterOptions {
616 exclude_globs: vec!["".into()],
617 ..Default::default()
618 });
619 assert!(res.is_err());
620 }
621
622 #[test]
623 fn excluded_dir_name_is_case_insensitive_with_prefix_rule() {
624 let cfg = FilterConfig::build(&FilterOptions {
625 exclude_dirs: vec!["GameServer201".into()],
626 ..Default::default()
627 })
628 .unwrap();
629 assert!(cfg.is_excluded_dir_name(OsStr::new("dep")));
630 assert!(cfg.is_excluded_dir_name(OsStr::new("DEP")));
631 assert!(cfg.is_excluded_dir_name(OsStr::new(".svn")));
632 assert!(cfg.is_excluded_dir_name(OsStr::new("OutputFile1")));
633 assert!(cfg.is_excluded_dir_name(OsStr::new("OutputFiles")));
634 assert!(cfg.is_excluded_dir_name(OsStr::new("gameserver201")));
635 assert!(!cfg.is_excluded_dir_name(OsStr::new("src")));
636 assert!(!cfg.is_excluded_dir_name(OsStr::new("temp.md")));
637 }
638
639 #[test]
640 fn hidden_respects_include_flag() {
641 let cfg = FilterConfig::build(&FilterOptions::default()).unwrap();
642 assert!(cfg.is_hidden_name(OsStr::new(".hidden.cpp")));
643 assert!(!cfg.is_hidden_name(OsStr::new("a.cpp")));
644 let cfg = FilterConfig::build(&FilterOptions {
645 include_hidden: true,
646 ..Default::default()
647 })
648 .unwrap();
649 assert!(!cfg.is_hidden_name(OsStr::new(".hidden.cpp")));
650 }
651
652 #[test]
653 fn extension_of_lowercases() {
654 assert_eq!(extension_of(Path::new("a.CPP")), Some("cpp".to_string()));
655 assert_eq!(extension_of(Path::new("a.tar.gz")), Some("gz".to_string()));
656 assert_eq!(extension_of(Path::new("Makefile")), None);
657 }
658}