1use std::collections::HashSet;
9use std::ffi::OsStr;
10use std::path::Path;
11
12pub const DEFAULT_EXTENSIONS: &[&str] = &[
14 "c", "cc", "cpp", "cxx", "c++", "h", "hh", "hpp", "hxx", "h++", "inl", "ipp", "tpp", "ixx",
16 "m", "mm",
17 "cs", "csx", "java", "kt", "kts",
19 "rs", "go", "py", "pyi", "rb", "php", "pl", "pm", "lua", "js", "jsx", "ts", "tsx", "mjs",
21 "cjs",
22 "sh", "bash", "zsh", "ps1", "bat", "cmd",
24 "json", "jsonc", "yaml", "yml", "toml", "ini", "cfg", "conf", "xml", "csv", "tsv", "sql",
26 "md", "markdown", "txt", "rst", "proto",
28];
29
30pub const RC_EXTENSIONS: &[&str] = &["rc", "rc2", "dlg"];
33
34pub const MSBUILD_EXTENSIONS: &[&str] =
37 &["sln", "vcxproj", "vcproj", "props", "targets", "filters", "user"];
38
39pub const DEFAULT_EXCLUDE_DIRS: &[&str] = &[
42 "dep",
43 "deps",
44 "third_party",
45 "third-party",
46 "3rdparty",
47 "vendor",
48 "external",
49 "extern",
50 "_tools",
51 "tools_bin",
52 ".svn",
53 ".git",
54 ".hg",
55 ".vs",
56 ".idea",
57 ".vscode",
58 "build",
59 "out",
60 "bin",
61 "obj",
62 "debug",
63 "release",
64 "target",
65 "node_modules",
66 "__pycache__",
67 ".venv",
68 "venv",
69 "temp",
70 "tmp",
71 "cache",
72];
73
74pub const DEFAULT_EXCLUDE_PREFIXES: &[&str] = &["outputfile"];
77
78#[derive(Debug, Clone, Default)]
80pub struct FilterOptions {
81 pub ext_override: Vec<String>,
83 pub exclude_ext: Vec<String>,
85 pub exclude_dirs: Vec<String>,
87 pub exclude_globs: Vec<String>,
89 pub include_rc: bool,
91 pub include_msbuild: bool,
93 pub include_hidden: bool,
95 pub max_file_size: u64,
97}
98
99#[derive(Debug, Clone)]
101pub struct FilterConfig {
102 pub extensions: HashSet<String>,
104 pub exclude_dirs: HashSet<String>,
106 pub exclude_prefixes: Vec<String>,
108 pub exclude_globs: Vec<Glob>,
110 pub include_hidden: bool,
112 pub max_file_size: u64,
114}
115
116impl FilterConfig {
117 pub fn build(opts: &FilterOptions) -> Result<FilterConfig, String> {
120 let exclude_ext: HashSet<String> = normalize_list(&opts.exclude_ext);
121
122 if opts.include_rc
125 && RC_EXTENSIONS.iter().any(|e| exclude_ext.contains(*e))
126 {
127 return Err(
128 "--include-rc conflicts with --exclude-ext (rc/rc2/dlg)".to_string(),
129 );
130 }
131 if opts.include_msbuild
132 && MSBUILD_EXTENSIONS.iter().any(|e| exclude_ext.contains(*e))
133 {
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_list(&opts.ext_override)
145 } else {
146 let mut base: HashSet<String> =
147 DEFAULT_EXTENSIONS.iter().map(|s| (*s).to_string()).collect();
148 if opts.include_rc {
149 base.extend(RC_EXTENSIONS.iter().map(|s| (*s).to_string()));
150 }
151 if opts.include_msbuild {
152 base.extend(MSBUILD_EXTENSIONS.iter().map(|s| (*s).to_string()));
153 }
154 base
155 };
156 for e in &exclude_ext {
157 extensions.remove(e);
158 }
159
160 let mut exclude_dirs: HashSet<String> = DEFAULT_EXCLUDE_DIRS
161 .iter()
162 .map(|s| (*s).to_string())
163 .collect();
164 exclude_dirs.extend(normalize_list(&opts.exclude_dirs));
165
166 let exclude_prefixes: Vec<String> = DEFAULT_EXCLUDE_PREFIXES
167 .iter()
168 .map(|s| (*s).to_string())
169 .collect();
170
171 let mut exclude_globs = Vec::new();
172 for pattern in &opts.exclude_globs {
173 match Glob::compile(pattern) {
174 Ok(g) => exclude_globs.push(g),
175 Err(e) => return Err(format!("invalid --exclude-glob `{pattern}`: {e}")),
176 }
177 }
178
179 Ok(FilterConfig {
180 extensions,
181 exclude_dirs,
182 exclude_prefixes,
183 exclude_globs,
184 include_hidden: opts.include_hidden,
185 max_file_size: opts.max_file_size,
186 })
187 }
188
189 pub fn is_excluded_dir_name(&self, name: &OsStr) -> bool {
191 let n = name.to_string_lossy().to_ascii_lowercase();
192 self.exclude_dirs.contains(&n)
193 || 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
204 .iter()
205 .any(|g| g.matches(rel_components))
206 }
207}
208
209fn normalize_list(values: &[String]) -> HashSet<String> {
211 values
212 .iter()
213 .map(|s| s.trim().to_ascii_lowercase())
214 .filter(|s| !s.is_empty())
215 .collect()
216}
217
218pub fn extension_of(path: &Path) -> Option<String> {
221 path.extension()
222 .map(|e| e.to_string_lossy().to_ascii_lowercase())
223}
224
225#[derive(Debug, Clone, PartialEq, Eq)]
231pub struct Glob {
232 parts: Vec<String>,
233}
234
235impl Glob {
236 pub fn compile(pattern: &str) -> Result<Glob, String> {
238 let normalized = pattern.replace('\\', "/");
239 let parts: Vec<String> = normalized
240 .split('/')
241 .filter(|s| !s.is_empty())
242 .map(|s| s.to_ascii_lowercase())
243 .collect();
244 if parts.is_empty() {
245 return Err("empty pattern".to_string());
246 }
247 Ok(Glob { parts })
248 }
249
250 pub fn matches(&self, components: &[&str]) -> bool {
252 let lowered: Vec<String> = components
253 .iter()
254 .map(|c| c.to_ascii_lowercase())
255 .collect();
256 let refs: Vec<&str> = lowered.iter().map(String::as_str).collect();
257 match_parts(&self.parts, &refs)
258 }
259}
260
261fn match_parts(pat: &[String], path: &[&str]) -> bool {
263 match pat.first() {
264 None => path.is_empty(),
265 Some(first) if first == "**" => {
266 for i in 0..=path.len() {
267 if match_parts(&pat[1..], &path[i..]) {
268 return true;
269 }
270 }
271 false
272 }
273 Some(first) => match path.first() {
274 None => false,
275 Some(head) => match_component(first.as_str(), head) && match_parts(&pat[1..], &path[1..]),
276 },
277 }
278}
279
280fn match_component(pat: &str, s: &str) -> bool {
282 let p: Vec<char> = pat.chars().collect();
283 let t: Vec<char> = s.chars().collect();
284 match_chars(&p, &t)
285}
286
287fn match_chars(pat: &[char], text: &[char]) -> bool {
288 match pat.first() {
289 None => text.is_empty(),
290 Some('*') => (0..=text.len()).any(|i| match_chars(&pat[1..], &text[i..])),
291 Some('?') => {
292 !text.is_empty() && match_chars(&pat[1..], &text[1..])
293 }
294 Some(c) => !text.is_empty() && text[0] == *c && match_chars(&pat[1..], &text[1..]),
295 }
296}
297
298#[cfg(test)]
299mod tests {
300 use super::*;
301
302 #[test]
303 fn glob_double_star_matches_nested_and_root() {
304 let g = Glob::compile("**/Generated/**").unwrap();
305 assert!(g.matches(&["GameServer", "Generated", "a.cpp"]));
306 assert!(g.matches(&["Generated", "b.h"]));
307 assert!(!g.matches(&["GameServer", "a.cpp"]));
308 assert!(!g.matches(&["Generated.cpp"]));
309 }
310
311 #[test]
312 fn glob_is_case_insensitive_and_normalizes_slashes() {
313 let g = Glob::compile("**\\generated\\**").unwrap();
314 assert!(g.matches(&["GameServer", "GENERATED", "x.cpp"]));
315 }
316
317 #[test]
318 fn glob_component_wildcards() {
319 let g = Glob::compile("**/*.tmp.*").unwrap();
320 assert!(g.matches(&["a", "x.tmp.cpp"]));
321 assert!(!g.matches(&["a", "y.cpp"]));
322 let q = Glob::compile("??-gen").unwrap();
323 assert!(q.matches(&["ab-gen"]));
324 assert!(!q.matches(&["abc-gen"]));
325 }
326
327 #[test]
328 fn glob_empty_pattern_rejected() {
329 assert!(Glob::compile("").is_err());
330 assert!(Glob::compile("///").is_err());
331 }
332
333 #[test]
334 fn build_default_whitelist_contains_cpp_not_rc() {
335 let cfg = FilterConfig::build(&FilterOptions::default()).unwrap();
336 assert!(cfg.extensions.contains("cpp"));
337 assert!(cfg.extensions.contains("proto"));
338 assert!(!cfg.extensions.contains("rc"));
339 assert!(!cfg.extensions.contains("vcxproj"));
340 }
341
342 #[test]
343 fn build_opt_in_flags_add_their_sets() {
344 let cfg = FilterConfig::build(&FilterOptions {
345 include_rc: true,
346 include_msbuild: true,
347 ..Default::default()
348 })
349 .unwrap();
350 assert!(cfg.extensions.contains("rc"));
351 assert!(cfg.extensions.contains("rc2"));
352 assert!(cfg.extensions.contains("dlg"));
353 assert!(cfg.extensions.contains("vcxproj"));
354 assert!(cfg.extensions.contains("sln"));
355 }
356
357 #[test]
358 fn build_ext_override_replaces_default_set() {
359 let cfg = FilterConfig::build(&FilterOptions {
360 ext_override: vec!["H".into(), "cpp".into()],
361 include_rc: true,
362 ..Default::default()
363 })
364 .unwrap();
365 assert!(cfg.extensions.contains("h"));
366 assert!(cfg.extensions.contains("cpp"));
367 assert!(!cfg.extensions.contains("md"));
368 assert!(!cfg.extensions.contains("rc"));
370 }
371
372 #[test]
373 fn build_exclude_ext_removes_from_whitelist() {
374 let cfg = FilterConfig::build(&FilterOptions {
375 exclude_ext: vec!["CPP".into(), "".into()],
376 ..Default::default()
377 })
378 .unwrap();
379 assert!(!cfg.extensions.contains("cpp"));
380 assert!(cfg.extensions.contains("h"));
381 }
382
383 #[test]
384 fn build_detects_documented_conflicts() {
385 let err = FilterConfig::build(&FilterOptions {
386 include_rc: true,
387 exclude_ext: vec!["rc".into()],
388 ..Default::default()
389 })
390 .unwrap_err();
391 assert!(err.contains("--include-rc"));
392
393 let err = FilterConfig::build(&FilterOptions {
394 include_msbuild: true,
395 exclude_ext: vec!["vcxproj".into()],
396 ..Default::default()
397 })
398 .unwrap_err();
399 assert!(err.contains("--include-msbuild"));
400 }
401
402 #[test]
403 fn build_rejects_bad_glob() {
404 let res = FilterConfig::build(&FilterOptions {
407 exclude_globs: vec!["".into()],
408 ..Default::default()
409 });
410 assert!(res.is_err());
411 }
412
413 #[test]
414 fn excluded_dir_name_is_case_insensitive_with_prefix_rule() {
415 let cfg = FilterConfig::build(&FilterOptions {
416 exclude_dirs: vec!["GameServer201".into()],
417 ..Default::default()
418 })
419 .unwrap();
420 assert!(cfg.is_excluded_dir_name(OsStr::new("dep")));
421 assert!(cfg.is_excluded_dir_name(OsStr::new("DEP")));
422 assert!(cfg.is_excluded_dir_name(OsStr::new(".svn")));
423 assert!(cfg.is_excluded_dir_name(OsStr::new("OutputFile1")));
424 assert!(cfg.is_excluded_dir_name(OsStr::new("OutputFiles")));
425 assert!(cfg.is_excluded_dir_name(OsStr::new("gameserver201")));
426 assert!(!cfg.is_excluded_dir_name(OsStr::new("src")));
427 assert!(!cfg.is_excluded_dir_name(OsStr::new("temp.md")));
428 }
429
430 #[test]
431 fn hidden_respects_include_flag() {
432 let cfg = FilterConfig::build(&FilterOptions::default()).unwrap();
433 assert!(cfg.is_hidden_name(OsStr::new(".hidden.cpp")));
434 assert!(!cfg.is_hidden_name(OsStr::new("a.cpp")));
435 let cfg = FilterConfig::build(&FilterOptions {
436 include_hidden: true,
437 ..Default::default()
438 })
439 .unwrap();
440 assert!(!cfg.is_hidden_name(OsStr::new(".hidden.cpp")));
441 }
442
443 #[test]
444 fn extension_of_lowercases() {
445 assert_eq!(extension_of(Path::new("a.CPP")), Some("cpp".to_string()));
446 assert_eq!(extension_of(Path::new("a.tar.gz")), Some("gz".to_string()));
447 assert_eq!(extension_of(Path::new("Makefile")), None);
448 }
449}