Skip to main content

utf8_forge/
filter.rs

1//! File selection: extension whitelist + directory blacklist double gate
2//! (`DESIGN.md §5`).
3//!
4//! Both gates always apply. An extension must be whitelisted AND the path
5//! must not hit an excluded directory name, prefix rule, or glob — this is
6//! what protects `dep/`, binaries, and build outputs (invariant #4).
7
8use std::collections::HashSet;
9use std::ffi::OsStr;
10use std::path::Path;
11
12/// Default extension whitelist (source + config/data + docs, `DESIGN §5.1`).
13pub const DEFAULT_EXTENSIONS: &[&str] = &[
14    // C / C++
15    "c", "cc", "cpp", "cxx", "c++", "h", "hh", "hpp", "hxx", "h++", "inl", "ipp", "tpp", "ixx",
16    "m", "mm",
17    // .NET / JVM
18    "cs", "csx", "java", "kt", "kts",
19    // Other languages
20    "rs", "go", "py", "pyi", "rb", "php", "pl", "pm", "lua", "js", "jsx", "ts", "tsx", "mjs",
21    "cjs",
22    // Shell
23    "sh", "bash", "zsh", "ps1", "bat", "cmd",
24    // Data / config
25    "json", "jsonc", "yaml", "yml", "toml", "ini", "cfg", "conf", "xml", "csv", "tsv", "sql",
26    // Docs / protocol
27    "md", "markdown", "txt", "rst", "proto",
28];
29
30/// Opt-in resource-script extensions (`--include-rc`). rc.exe has limited
31/// UTF-8 support, so these stay off the default whitelist.
32pub const RC_EXTENSIONS: &[&str] = &["rc", "rc2", "dlg"];
33
34/// Opt-in MSBuild / Visual Studio extensions (`--include-msbuild`). VS
35/// re-saves these with a BOM, so they stay off the default whitelist.
36pub const MSBUILD_EXTENSIONS: &[&str] =
37    &["sln", "vcxproj", "vcproj", "props", "targets", "filters", "user"];
38
39/// Directory names excluded by default, matched case-insensitively on the
40/// directory name itself (`DESIGN §5.2`).
41pub 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
74/// Directory-name prefixes excluded by default (`OutputFile*` /
75/// `OutputFiles*`).
76pub const DEFAULT_EXCLUDE_PREFIXES: &[&str] = &["outputfile"];
77
78/// Raw filter inputs, normalized by [`FilterConfig::build`].
79#[derive(Debug, Clone, Default)]
80pub struct FilterOptions {
81    /// Overrides the default whitelist entirely when non-empty.
82    pub ext_override: Vec<String>,
83    /// Appended removals from the effective whitelist.
84    pub exclude_ext: Vec<String>,
85    /// Extra excluded directory names (appended to the defaults).
86    pub exclude_dirs: Vec<String>,
87    /// Extra glob patterns matched against root-relative paths.
88    pub exclude_globs: Vec<String>,
89    /// Adds `RC_EXTENSIONS` to the default whitelist.
90    pub include_rc: bool,
91    /// Adds `MSBUILD_EXTENSIONS` to the default whitelist.
92    pub include_msbuild: bool,
93    /// Processes dot-prefixed files/dirs (default excludes still apply).
94    pub include_hidden: bool,
95    /// Files above this size are recorded as `too_large`, never read.
96    pub max_file_size: u64,
97}
98
99/// Compiled, effective filter configuration.
100#[derive(Debug, Clone)]
101pub struct FilterConfig {
102    /// Effective extension whitelist (lowercased).
103    pub extensions: HashSet<String>,
104    /// Effective excluded directory names (lowercased, defaults + user).
105    pub exclude_dirs: HashSet<String>,
106    /// Effective excluded directory-name prefixes (lowercased).
107    pub exclude_prefixes: Vec<String>,
108    /// Compiled user glob patterns.
109    pub exclude_globs: Vec<Glob>,
110    /// Whether dot-prefixed entries are processed.
111    pub include_hidden: bool,
112    /// Size cap in bytes.
113    pub max_file_size: u64,
114}
115
116impl FilterConfig {
117    /// Build the effective config. Fatal-input problems (conflicting flags,
118    /// malformed globs) return `Err` → CLI exit code 2.
119    pub fn build(opts: &FilterOptions) -> Result<FilterConfig, String> {
120        let exclude_ext: HashSet<String> = normalize_list(&opts.exclude_ext);
121
122        // Documented conflict: opt-in sets must not be simultaneously included
123        // and excluded (`AGENT.md §4`, exit 2).
124        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        // `-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_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    /// Case-insensitive directory-name / prefix exclusion check.
190    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    /// 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
204            .iter()
205            .any(|g| g.matches(rel_components))
206    }
207}
208
209/// Lowercase + trim + drop empties for CLI list values.
210fn 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
218/// Lowercased file extension of `path` (`foo.PNG` → `png`); `None` when the
219/// file has no extension.
220pub fn extension_of(path: &Path) -> Option<String> {
221    path.extension()
222        .map(|e| e.to_string_lossy().to_ascii_lowercase())
223}
224
225/// A compiled `--exclude-glob` pattern.
226///
227/// Semantics: `/`-separated components; `**` matches zero or more path
228/// components; `*` / `?` are wildcards inside one component. Matching is
229/// case-insensitive (consistent with directory exclusion on Windows).
230#[derive(Debug, Clone, PartialEq, Eq)]
231pub struct Glob {
232    parts: Vec<String>,
233}
234
235impl Glob {
236    /// Compile `pattern`. Empty patterns are rejected.
237    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    /// Match a root-relative path split into components.
251    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
261/// Recursive component matcher; `**` consumes zero or more components.
262fn 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
280/// Wildcard matcher inside a single path component (`*`, `?`).
281fn 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        // Override replaces the default set, so the opt-in flag is inert.
369        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        // No bad glob can exist today (empty is the only failure), but the
405        // plumbing must surface it as Err.
406        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}