Skip to main content

utf8_forge/
filter.rs

1// Copyright 2026 houseme
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15//! File selection: extension whitelist + directory blacklist double gate.
16//!
17//! Both gates always apply. An extension must be whitelisted AND the path
18//! must not hit an excluded directory name, prefix rule, or glob — this is
19//! what protects `dep/`, binaries, and build outputs from modification.
20
21use std::collections::HashSet;
22use std::ffi::OsStr;
23use std::path::Path;
24
25/// Default extension whitelist (source code + config/data + docs).
26pub const DEFAULT_EXTENSIONS: &[&str] = &[
27    // C / C++
28    "c", "cc", "cpp", "cxx", "c++", "h", "hh", "hpp", "hxx", "h++", "inl", "ipp", "tpp", "ixx", "m",
29    "mm", // .NET / JVM
30    "cs", "csx", "java", "kt", "kts", // Other languages
31    "rs", "go", "py", "pyi", "rb", "php", "pl", "pm", "lua", "js", "jsx", "ts", "tsx", "mjs",
32    "cjs", // Shell
33    "sh", "bash", "zsh", "ps1", "bat", "cmd", // Data / config
34    "json", "jsonc", "yaml", "yml", "toml", "ini", "cfg", "conf", "xml", "csv", "tsv", "sql",
35    // Docs / protocol
36    "md", "markdown", "txt", "rst", "proto",
37];
38
39/// Opt-in resource-script extensions (`--include-rc`). rc.exe has limited
40/// UTF-8 support, so these stay off the default whitelist.
41pub const RC_EXTENSIONS: &[&str] = &["rc", "rc2", "dlg"];
42
43/// Opt-in MSBuild / Visual Studio extensions (`--include-msbuild`). VS
44/// re-saves these with a BOM, so they stay off the default whitelist.
45pub const MSBUILD_EXTENSIONS: &[&str] = &[
46    "sln", "vcxproj", "vcproj", "props", "targets", "filters", "user",
47];
48
49/// Directory names excluded by default, matched case-insensitively on the
50/// directory name itself.
51pub 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
84/// Directory-name prefixes excluded by default (`OutputFile*` /
85/// `OutputFiles*`).
86pub const DEFAULT_EXCLUDE_PREFIXES: &[&str] = &["outputfile"];
87
88/// Raw filter inputs, normalized by [`FilterConfig::build`].
89#[derive(Debug, Clone, Default)]
90pub struct FilterOptions {
91    /// Overrides the default whitelist entirely when non-empty.
92    pub ext_override: Vec<String>,
93    /// Appended removals from the effective whitelist.
94    pub exclude_ext: Vec<String>,
95    /// Extra excluded directory names (appended to the defaults).
96    pub exclude_dirs: Vec<String>,
97    /// Extra glob patterns matched against root-relative paths.
98    pub exclude_globs: Vec<String>,
99    /// Adds `RC_EXTENSIONS` to the default whitelist.
100    pub include_rc: bool,
101    /// Adds `MSBUILD_EXTENSIONS` to the default whitelist.
102    pub include_msbuild: bool,
103    /// Processes dot-prefixed files/dirs (default excludes still apply).
104    pub include_hidden: bool,
105}
106
107/// Compiled, effective filter configuration.
108#[derive(Debug, Clone)]
109pub struct FilterConfig {
110    /// Effective extension whitelist (lowercased).
111    pub extensions: HashSet<String>,
112    /// Effective excluded directory names (lowercased, defaults + user).
113    pub exclude_dirs: HashSet<String>,
114    /// Effective excluded directory-name prefixes (lowercased).
115    pub exclude_prefixes: Vec<String>,
116    /// Compiled user glob patterns.
117    pub exclude_globs: Vec<Glob>,
118    /// Whether dot-prefixed entries are processed.
119    pub include_hidden: bool,
120}
121
122impl FilterConfig {
123    /// Build the effective config. Fatal-input problems (conflicting flags,
124    /// malformed globs) return `Err` → CLI exit code 2.
125    pub fn build(opts: &FilterOptions) -> Result<FilterConfig, String> {
126        let exclude_ext: HashSet<String> = normalize_ext_list(&opts.exclude_ext)?;
127
128        // Opt-in sets must not be simultaneously included and excluded; that
129        // configuration is contradictory, so it is a fatal input error.
130        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        // `-e/--ext` overrides the default whitelist; opt-in flags only apply
142        // to the default set.
143        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    /// Case-insensitive directory-name / prefix exclusion check.
191    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    /// True when the dot-prefixed entry must be skipped.
197    pub fn is_hidden_name(&self, name: &OsStr) -> bool {
198        !self.include_hidden && name.to_string_lossy().starts_with('.')
199    }
200
201    /// True when any user glob matches the root-relative path components.
202    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
207/// Lowercase + trim + drop empties for extension list values.
208///
209/// Exactly one leading dot is stripped so `--ext .cpp` matches the extension
210/// `cpp` as the dot-less spelling does. A value that still starts with a dot
211/// (`..h`) or contains a slash (`.cpp/`) can never match a real extension —
212/// it would be a silent no-op indistinguishable from "no matching files" —
213/// so those are fatal input errors instead.
214fn 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
234/// Lowercase + trim + drop empties for directory-name list values.
235/// Names are kept verbatim otherwise — `.cache` is a legitimate directory
236/// name and must not lose its dot.
237fn 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
245/// Lowercased file extension of `path` (`foo.PNG` → `png`); `None` when the
246/// file has no extension.
247pub fn extension_of(path: &Path) -> Option<String> {
248    path.extension()
249        .map(|e| e.to_string_lossy().to_ascii_lowercase())
250}
251
252/// A compiled `--exclude-glob` pattern.
253///
254/// Semantics: `/`-separated components; `**` matches zero or more path
255/// components; `*` / `?` are wildcards inside one component. Matching is
256/// case-insensitive (consistent with directory exclusion on Windows).
257///
258/// Star runs are collapsed at compile time (`***` → `**`, `a**b` → `a*b`) —
259/// semantically identical since consecutive stars match the same text — and
260/// the matchers run under a step budget so a star-heavy pattern can never
261/// backtrack exponentially (budget exhausted → no match).
262#[derive(Debug, Clone, PartialEq, Eq)]
263pub struct Glob {
264    parts: Vec<String>,
265}
266
267/// Upper bound on matcher steps per `matches()` call. Generous for any
268/// realistic path/pattern, tiny enough to make pathological backtracking
269/// (which previously hung for minutes) return instantly.
270const GLOB_STEP_BUDGET: u64 = 1_000_000;
271
272impl Glob {
273    /// Compile `pattern`. Empty patterns are rejected. Backslashes are
274    /// normalized to `/` (convenient for Windows-style `--exclude-glob`).
275    pub fn compile(pattern: &str) -> Result<Glob, String> {
276        Glob::compile_inner(pattern, true)
277    }
278
279    /// Like [`Glob::compile`], but a backslash is an ordinary literal character —
280    /// the ignore-file grammar deliberately has no escape support, so `\`
281    /// must not silently become `/` there.
282    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    /// Match a root-relative path split into components.
304    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
312/// Collapse runs of `*` inside one component: all-star components become the
313/// multi-level `**` (`***` ≡ `**`), mixed components keep a single `*`
314/// (`a**b` ≡ `a*b`). Purely syntactic — no matching semantics change.
315fn 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
334/// Recursive component matcher; `**` consumes zero or more components.
335/// `budget` shrinks on every recursive call; exhaustion returns "no match".
336fn 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
361/// Wildcard matcher inside a single path component (`*`, `?`).
362fn 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        // Override replaces the default set, so the opt-in flag is inert.
452        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        // No bad glob can exist today (empty is the only failure), but the
488        // plumbing must surface it as Err.
489        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}