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)]
109pub struct FilterConfig {
110 pub extensions: HashSet<String>,
112 pub exclude_dirs: HashSet<String>,
114 pub exclude_prefixes: Vec<String>,
116 pub exclude_globs: Vec<Glob>,
118 pub include_hidden: bool,
120}
121
122impl FilterConfig {
123 pub fn build(opts: &FilterOptions) -> Result<FilterConfig, String> {
126 let exclude_ext: HashSet<String> = normalize_ext_list(&opts.exclude_ext)?;
127
128 if opts.include_rc && RC_EXTENSIONS.iter().any(|e| exclude_ext.contains(*e)) {
131 return Err("--include-rc conflicts with --exclude-ext (rc/rc2/dlg)".to_string());
132 }
133 if opts.include_msbuild && MSBUILD_EXTENSIONS.iter().any(|e| exclude_ext.contains(*e)) {
134 return Err(concat!(
135 "--include-msbuild conflicts with --exclude-ext ",
136 "(sln/vcxproj/vcproj/props/targets/filters/user)"
137 )
138 .to_string());
139 }
140
141 let mut extensions: HashSet<String> = if !opts.ext_override.is_empty() {
144 normalize_ext_list(&opts.ext_override)?
145 } else {
146 let mut base: HashSet<String> = DEFAULT_EXTENSIONS
147 .iter()
148 .map(|s| (*s).to_string())
149 .collect();
150 if opts.include_rc {
151 base.extend(RC_EXTENSIONS.iter().map(|s| (*s).to_string()));
152 }
153 if opts.include_msbuild {
154 base.extend(MSBUILD_EXTENSIONS.iter().map(|s| (*s).to_string()));
155 }
156 base
157 };
158 for e in &exclude_ext {
159 extensions.remove(e);
160 }
161
162 let mut exclude_dirs: HashSet<String> = DEFAULT_EXCLUDE_DIRS
163 .iter()
164 .map(|s| (*s).to_string())
165 .collect();
166 exclude_dirs.extend(normalize_dir_list(&opts.exclude_dirs));
167
168 let exclude_prefixes: Vec<String> = DEFAULT_EXCLUDE_PREFIXES
169 .iter()
170 .map(|s| (*s).to_string())
171 .collect();
172
173 let mut exclude_globs = Vec::new();
174 for pattern in &opts.exclude_globs {
175 match Glob::compile(pattern) {
176 Ok(g) => exclude_globs.push(g),
177 Err(e) => return Err(format!("invalid --exclude-glob `{pattern}`: {e}")),
178 }
179 }
180
181 Ok(FilterConfig {
182 extensions,
183 exclude_dirs,
184 exclude_prefixes,
185 exclude_globs,
186 include_hidden: opts.include_hidden,
187 })
188 }
189
190 pub fn is_excluded_dir_name(&self, name: &OsStr) -> bool {
192 let n = name.to_string_lossy().to_ascii_lowercase();
193 self.exclude_dirs.contains(&n) || self.exclude_prefixes.iter().any(|p| n.starts_with(p))
194 }
195
196 pub fn is_hidden_name(&self, name: &OsStr) -> bool {
198 !self.include_hidden && name.to_string_lossy().starts_with('.')
199 }
200
201 pub fn is_excluded_by_glob(&self, rel_components: &[&str]) -> bool {
203 self.exclude_globs.iter().any(|g| g.matches(rel_components))
204 }
205}
206
207fn normalize_ext_list(values: &[String]) -> Result<HashSet<String>, String> {
215 let mut out = HashSet::new();
216 for raw in values {
217 let v = raw.trim();
218 let v = v.strip_prefix('.').unwrap_or(v).to_ascii_lowercase();
219 if v.starts_with('.') {
220 return Err(format!(
221 "invalid extension value `{raw}`: too many leading dots"
222 ));
223 }
224 if v.contains('/') {
225 return Err(format!("invalid extension value `{raw}`: contains `/`"));
226 }
227 if !v.is_empty() {
228 out.insert(v);
229 }
230 }
231 Ok(out)
232}
233
234fn normalize_dir_list(values: &[String]) -> HashSet<String> {
238 values
239 .iter()
240 .map(|s| s.trim().to_ascii_lowercase())
241 .filter(|s| !s.is_empty())
242 .collect()
243}
244
245pub fn extension_of(path: &Path) -> Option<String> {
248 path.extension()
249 .map(|e| e.to_string_lossy().to_ascii_lowercase())
250}
251
252#[derive(Debug, Clone, PartialEq, Eq)]
263pub struct Glob {
264 parts: Vec<String>,
265}
266
267const GLOB_STEP_BUDGET: u64 = 1_000_000;
271
272impl Glob {
273 pub fn compile(pattern: &str) -> Result<Glob, String> {
276 Glob::compile_inner(pattern, true)
277 }
278
279 pub fn compile_raw(pattern: &str) -> Result<Glob, String> {
283 Glob::compile_inner(pattern, false)
284 }
285
286 fn compile_inner(pattern: &str, normalize_backslash: bool) -> Result<Glob, String> {
287 let normalized = if normalize_backslash {
288 pattern.replace('\\', "/")
289 } else {
290 pattern.to_string()
291 };
292 let parts: Vec<String> = normalized
293 .split('/')
294 .filter(|s| !s.is_empty())
295 .map(|s| collapse_stars(&s.to_ascii_lowercase()))
296 .collect();
297 if parts.is_empty() {
298 return Err("empty pattern".to_string());
299 }
300 Ok(Glob { parts })
301 }
302
303 pub fn matches(&self, components: &[&str]) -> bool {
305 let lowered: Vec<String> = components.iter().map(|c| c.to_ascii_lowercase()).collect();
306 let refs: Vec<&str> = lowered.iter().map(String::as_str).collect();
307 let mut budget = GLOB_STEP_BUDGET;
308 match_parts(&self.parts, &refs, &mut budget)
309 }
310}
311
312fn collapse_stars(component: &str) -> String {
316 if component.chars().all(|c| c == '*') && component.len() >= 2 {
317 return "**".to_string();
318 }
319 let mut out = String::with_capacity(component.len());
320 let mut last_was_star = false;
321 for c in component.chars() {
322 if c == '*' {
323 if !last_was_star {
324 out.push(c);
325 }
326 } else {
327 out.push(c);
328 }
329 last_was_star = c == '*';
330 }
331 out
332}
333
334fn match_parts(pat: &[String], path: &[&str], budget: &mut u64) -> bool {
337 if *budget == 0 {
338 return false;
339 }
340 *budget -= 1;
341 match pat.first() {
342 None => path.is_empty(),
343 Some(first) if first == "**" => {
344 for i in 0..=path.len() {
345 if match_parts(&pat[1..], &path[i..], budget) {
346 return true;
347 }
348 }
349 false
350 }
351 Some(first) => match path.first() {
352 None => false,
353 Some(head) => {
354 match_component(first.as_str(), head, budget)
355 && match_parts(&pat[1..], &path[1..], budget)
356 }
357 },
358 }
359}
360
361fn match_component(pat: &str, s: &str, budget: &mut u64) -> bool {
363 let p: Vec<char> = pat.chars().collect();
364 let t: Vec<char> = s.chars().collect();
365 match_chars(&p, &t, budget)
366}
367
368fn match_chars(pat: &[char], text: &[char], budget: &mut u64) -> bool {
369 if *budget == 0 {
370 return false;
371 }
372 *budget -= 1;
373 match pat.first() {
374 None => text.is_empty(),
375 Some('*') => (0..=text.len()).any(|i| match_chars(&pat[1..], &text[i..], budget)),
376 Some('?') => !text.is_empty() && match_chars(&pat[1..], &text[1..], budget),
377 Some(c) => !text.is_empty() && text[0] == *c && match_chars(&pat[1..], &text[1..], budget),
378 }
379}
380
381#[cfg(test)]
382mod tests {
383 use super::*;
384
385 #[test]
386 fn glob_double_star_matches_nested_and_root() {
387 let g = Glob::compile("**/Generated/**").unwrap();
388 assert!(g.matches(&["GameServer", "Generated", "a.cpp"]));
389 assert!(g.matches(&["Generated", "b.h"]));
390 assert!(!g.matches(&["GameServer", "a.cpp"]));
391 assert!(!g.matches(&["Generated.cpp"]));
392 }
393
394 #[test]
395 fn glob_is_case_insensitive_and_normalizes_slashes() {
396 let g = Glob::compile("**\\generated\\**").unwrap();
397 assert!(g.matches(&["GameServer", "GENERATED", "x.cpp"]));
398 }
399
400 #[test]
401 fn glob_component_wildcards() {
402 let g = Glob::compile("**/*.tmp.*").unwrap();
403 assert!(g.matches(&["a", "x.tmp.cpp"]));
404 assert!(!g.matches(&["a", "y.cpp"]));
405 let q = Glob::compile("??-gen").unwrap();
406 assert!(q.matches(&["ab-gen"]));
407 assert!(!q.matches(&["abc-gen"]));
408 }
409
410 #[test]
411 fn glob_empty_pattern_rejected() {
412 assert!(Glob::compile("").is_err());
413 assert!(Glob::compile("///").is_err());
414 }
415
416 #[test]
417 fn build_default_whitelist_contains_cpp_not_rc() {
418 let cfg = FilterConfig::build(&FilterOptions::default()).unwrap();
419 assert!(cfg.extensions.contains("cpp"));
420 assert!(cfg.extensions.contains("proto"));
421 assert!(!cfg.extensions.contains("rc"));
422 assert!(!cfg.extensions.contains("vcxproj"));
423 }
424
425 #[test]
426 fn build_opt_in_flags_add_their_sets() {
427 let cfg = FilterConfig::build(&FilterOptions {
428 include_rc: true,
429 include_msbuild: true,
430 ..Default::default()
431 })
432 .unwrap();
433 assert!(cfg.extensions.contains("rc"));
434 assert!(cfg.extensions.contains("rc2"));
435 assert!(cfg.extensions.contains("dlg"));
436 assert!(cfg.extensions.contains("vcxproj"));
437 assert!(cfg.extensions.contains("sln"));
438 }
439
440 #[test]
441 fn build_ext_override_replaces_default_set() {
442 let cfg = FilterConfig::build(&FilterOptions {
443 ext_override: vec!["H".into(), "cpp".into()],
444 include_rc: true,
445 ..Default::default()
446 })
447 .unwrap();
448 assert!(cfg.extensions.contains("h"));
449 assert!(cfg.extensions.contains("cpp"));
450 assert!(!cfg.extensions.contains("md"));
451 assert!(!cfg.extensions.contains("rc"));
453 }
454
455 #[test]
456 fn build_exclude_ext_removes_from_whitelist() {
457 let cfg = FilterConfig::build(&FilterOptions {
458 exclude_ext: vec!["CPP".into(), "".into()],
459 ..Default::default()
460 })
461 .unwrap();
462 assert!(!cfg.extensions.contains("cpp"));
463 assert!(cfg.extensions.contains("h"));
464 }
465
466 #[test]
467 fn build_detects_documented_conflicts() {
468 let err = FilterConfig::build(&FilterOptions {
469 include_rc: true,
470 exclude_ext: vec!["rc".into()],
471 ..Default::default()
472 })
473 .unwrap_err();
474 assert!(err.contains("--include-rc"));
475
476 let err = FilterConfig::build(&FilterOptions {
477 include_msbuild: true,
478 exclude_ext: vec!["vcxproj".into()],
479 ..Default::default()
480 })
481 .unwrap_err();
482 assert!(err.contains("--include-msbuild"));
483 }
484
485 #[test]
486 fn build_rejects_bad_glob() {
487 let res = FilterConfig::build(&FilterOptions {
490 exclude_globs: vec!["".into()],
491 ..Default::default()
492 });
493 assert!(res.is_err());
494 }
495
496 #[test]
497 fn excluded_dir_name_is_case_insensitive_with_prefix_rule() {
498 let cfg = FilterConfig::build(&FilterOptions {
499 exclude_dirs: vec!["GameServer201".into()],
500 ..Default::default()
501 })
502 .unwrap();
503 assert!(cfg.is_excluded_dir_name(OsStr::new("dep")));
504 assert!(cfg.is_excluded_dir_name(OsStr::new("DEP")));
505 assert!(cfg.is_excluded_dir_name(OsStr::new(".svn")));
506 assert!(cfg.is_excluded_dir_name(OsStr::new("OutputFile1")));
507 assert!(cfg.is_excluded_dir_name(OsStr::new("OutputFiles")));
508 assert!(cfg.is_excluded_dir_name(OsStr::new("gameserver201")));
509 assert!(!cfg.is_excluded_dir_name(OsStr::new("src")));
510 assert!(!cfg.is_excluded_dir_name(OsStr::new("temp.md")));
511 }
512
513 #[test]
514 fn hidden_respects_include_flag() {
515 let cfg = FilterConfig::build(&FilterOptions::default()).unwrap();
516 assert!(cfg.is_hidden_name(OsStr::new(".hidden.cpp")));
517 assert!(!cfg.is_hidden_name(OsStr::new("a.cpp")));
518 let cfg = FilterConfig::build(&FilterOptions {
519 include_hidden: true,
520 ..Default::default()
521 })
522 .unwrap();
523 assert!(!cfg.is_hidden_name(OsStr::new(".hidden.cpp")));
524 }
525
526 #[test]
527 fn extension_of_lowercases() {
528 assert_eq!(extension_of(Path::new("a.CPP")), Some("cpp".to_string()));
529 assert_eq!(extension_of(Path::new("a.tar.gz")), Some("gz".to_string()));
530 assert_eq!(extension_of(Path::new("Makefile")), None);
531 }
532}