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    /// Replaces the default excluded-directory set entirely when present.
98    /// `None` (or an empty `exclude_dirs`) keeps the defaults; an override
99    /// that names a default directory re-includes it for scanning.
100    pub exclude_dirs_override: Option<Vec<String>>,
101    /// Extra glob patterns matched against root-relative paths.
102    pub exclude_globs: Vec<String>,
103    /// Adds `RC_EXTENSIONS` to the default whitelist.
104    pub include_rc: bool,
105    /// Adds `MSBUILD_EXTENSIONS` to the default whitelist.
106    pub include_msbuild: bool,
107    /// Processes dot-prefixed files/dirs (default excludes still apply).
108    pub include_hidden: bool,
109}
110
111/// Compiled, effective filter configuration. The fields are the
112/// post-normalization output of [`FilterConfig::build`] (lowercased,
113/// validated, compiled) — constructing them by hand bypasses that
114/// normalization, so always go through `build`.
115#[derive(Debug, Clone)]
116pub struct FilterConfig {
117    /// Effective extension whitelist (lowercased).
118    pub extensions: HashSet<String>,
119    /// Effective excluded directory names (lowercased, defaults + user).
120    pub exclude_dirs: HashSet<String>,
121    /// Effective excluded directory-name prefixes (lowercased).
122    pub exclude_prefixes: Vec<String>,
123    /// Compiled user glob patterns.
124    pub exclude_globs: Vec<Glob>,
125    /// Whether dot-prefixed entries are processed.
126    pub include_hidden: bool,
127}
128
129impl FilterConfig {
130    /// Build the effective config. Fatal-input problems (conflicting flags,
131    /// malformed globs) return `Err` → CLI exit code 2.
132    pub fn build(opts: &FilterOptions, ext_source: &str) -> Result<FilterConfig, String> {
133        let exclude_ext: HashSet<String> = normalize_ext_list(&opts.exclude_ext, "--exclude-ext")?;
134
135        // Opt-in sets must not be simultaneously included and excluded; that
136        // configuration is contradictory, so it is a fatal input error.
137        if opts.include_rc && RC_EXTENSIONS.iter().any(|e| exclude_ext.contains(*e)) {
138            return Err("--include-rc conflicts with --exclude-ext (rc/rc2/dlg)".to_string());
139        }
140        if opts.include_msbuild && MSBUILD_EXTENSIONS.iter().any(|e| exclude_ext.contains(*e)) {
141            return Err(concat!(
142                "--include-msbuild conflicts with --exclude-ext ",
143                "(sln/vcxproj/vcproj/props/targets/filters/user)"
144            )
145            .to_string());
146        }
147
148        // `-e/--ext` overrides the default whitelist; opt-in flags only apply
149        // to the default set. An explicit override that normalizes to nothing
150        // (`--ext ""`) would silently scan zero files, so it is fatal.
151        let mut extensions: HashSet<String> = if !opts.ext_override.is_empty() {
152            let normalized = normalize_ext_list(&opts.ext_override, ext_source)?;
153            if normalized.is_empty() {
154                return Err("empty --ext list: no usable extensions".to_string());
155            }
156            normalized
157        } else {
158            let mut base: HashSet<String> = DEFAULT_EXTENSIONS
159                .iter()
160                .map(|s| (*s).to_string())
161                .collect();
162            if opts.include_rc {
163                base.extend(RC_EXTENSIONS.iter().map(|s| (*s).to_string()));
164            }
165            if opts.include_msbuild {
166                base.extend(MSBUILD_EXTENSIONS.iter().map(|s| (*s).to_string()));
167            }
168            base
169        };
170        for e in &exclude_ext {
171            extensions.remove(e);
172        }
173
174        let mut exclude_dirs: HashSet<String> = match &opts.exclude_dirs_override {
175            // A present override replaces the default set entirely; an
176            // absent one keeps the defaults underneath the extras.
177            Some(list) => list
178                .iter()
179                .map(|s| s.trim().to_ascii_lowercase())
180                .filter(|s| !s.is_empty())
181                .collect(),
182            None => DEFAULT_EXCLUDE_DIRS
183                .iter()
184                .map(|s| (*s).to_string())
185                .collect(),
186        };
187        exclude_dirs.extend(normalize_dir_list(&opts.exclude_dirs));
188
189        let exclude_prefixes: Vec<String> = DEFAULT_EXCLUDE_PREFIXES
190            .iter()
191            .map(|s| (*s).to_string())
192            .collect();
193
194        let mut exclude_globs = Vec::new();
195        for pattern in &opts.exclude_globs {
196            match Glob::compile(pattern) {
197                Ok(g) => exclude_globs.push(g),
198                Err(e) => return Err(format!("invalid --exclude-glob `{pattern}`: {e}")),
199            }
200        }
201
202        Ok(FilterConfig {
203            extensions,
204            exclude_dirs,
205            exclude_prefixes,
206            exclude_globs,
207            include_hidden: opts.include_hidden,
208        })
209    }
210
211    /// Case-insensitive directory-name / prefix exclusion check.
212    pub fn is_excluded_dir_name(&self, name: &OsStr) -> bool {
213        let n = name.to_string_lossy().to_ascii_lowercase();
214        self.exclude_dirs.contains(&n) || self.exclude_prefixes.iter().any(|p| n.starts_with(p))
215    }
216
217    /// True when the dot-prefixed entry must be skipped.
218    pub fn is_hidden_name(&self, name: &OsStr) -> bool {
219        !self.include_hidden && name.to_string_lossy().starts_with('.')
220    }
221
222    /// True when any user glob matches the root-relative path components.
223    pub fn is_excluded_by_glob(&self, rel_components: &[&str]) -> bool {
224        self.exclude_globs.iter().any(|g| g.matches(rel_components))
225    }
226}
227
228/// Lowercase + trim + drop empties for extension list values.
229///
230/// Exactly one leading dot is stripped so `--ext .cpp` matches the extension
231/// `cpp` as the dot-less spelling does. A value that still starts with a dot
232/// (`..h`) or contains a slash (`.cpp/`) can never match a real extension —
233/// it would be a silent no-op indistinguishable from "no matching files" —
234/// so those are fatal input errors instead.
235fn normalize_ext_list(values: &[String], source: &str) -> Result<HashSet<String>, String> {
236    let mut out = HashSet::new();
237    for raw in values {
238        let v = raw.trim();
239        let v = v.strip_prefix('.').unwrap_or(v).to_ascii_lowercase();
240        if v.starts_with('.') {
241            return Err(format!(
242                "invalid {source} value `{raw}`: too many leading dots"
243            ));
244        }
245        if v.contains('/') {
246            return Err(format!("invalid {source} value `{raw}`: contains `/`"));
247        }
248        if !v.is_empty() {
249            out.insert(v);
250        }
251    }
252    Ok(out)
253}
254
255/// Lowercase + trim + drop empties for directory-name list values.
256/// Names are kept verbatim otherwise — `.cache` is a legitimate directory
257/// name and must not lose its dot.
258fn normalize_dir_list(values: &[String]) -> HashSet<String> {
259    values
260        .iter()
261        .map(|s| s.trim().to_ascii_lowercase())
262        .filter(|s| !s.is_empty())
263        .collect()
264}
265
266/// Lowercased file extension of `path` (`foo.PNG` → `png`); `None` when the
267/// file has no extension.
268pub fn extension_of(path: &Path) -> Option<String> {
269    path.extension()
270        .map(|e| e.to_string_lossy().to_ascii_lowercase())
271}
272
273/// A compiled `--exclude-glob` pattern.
274///
275/// Semantics: `/`-separated components; `**` matches zero or more path
276/// components; `*` / `?` are wildcards inside one component. Matching is
277/// case-insensitive (consistent with directory exclusion on Windows).
278///
279/// Star runs are collapsed at compile time (`***` → `**`, `a**b` → `a*b`) —
280/// semantically identical since consecutive stars match the same text.
281/// Iterative matchers retry only the latest wildcard, giving polynomial
282/// worst-case work without recursion or a budget that can discard matches.
283#[derive(Debug, Clone, PartialEq, Eq)]
284pub struct Glob {
285    parts: Vec<String>,
286}
287
288impl Glob {
289    /// Compile `pattern`. Empty patterns are rejected. Backslashes are
290    /// normalized to `/` (convenient for Windows-style `--exclude-glob`).
291    pub fn compile(pattern: &str) -> Result<Glob, String> {
292        Glob::compile_inner(pattern, true)
293    }
294
295    /// Like [`Glob::compile`], but a backslash is an ordinary literal character —
296    /// the ignore-file grammar deliberately has no escape support, so `\`
297    /// must not silently become `/` there.
298    pub fn compile_raw(pattern: &str) -> Result<Glob, String> {
299        Glob::compile_inner(pattern, false)
300    }
301
302    fn compile_inner(pattern: &str, normalize_backslash: bool) -> Result<Glob, String> {
303        let normalized = if normalize_backslash {
304            pattern.replace('\\', "/")
305        } else {
306            pattern.to_string()
307        };
308        // This grammar supports only `*`, `?` and `**`. Character classes
309        // and brace expansion are not implemented — accepting them as
310        // literals would silently exclude nothing for an operator porting
311        // gitignore/bash habits, so they are a loud input error instead.
312        if normalized.contains('[') || normalized.contains('{') {
313            return Err(String::from(
314                "this grammar supports only `*`, `?` and `**`; `[` and `{` are not glob \
315                 constructs and would match literally",
316            ));
317        }
318        let parts: Vec<String> = normalized
319            .split('/')
320            .filter(|s| !s.is_empty())
321            .map(|s| collapse_stars(&s.to_ascii_lowercase()))
322            .collect();
323        if parts.is_empty() {
324            return Err("empty pattern".to_string());
325        }
326        Ok(Glob { parts })
327    }
328
329    /// Match a root-relative path split into components.
330    pub fn matches(&self, components: &[&str]) -> bool {
331        let lowered: Vec<String> = components.iter().map(|c| c.to_ascii_lowercase()).collect();
332        let refs: Vec<&str> = lowered.iter().map(String::as_str).collect();
333        match_parts(&self.parts, &refs)
334    }
335}
336
337/// Collapse runs of `*` inside one component: all-star components become the
338/// multi-level `**` (`***` ≡ `**`), mixed components keep a single `*`
339/// (`a**b` ≡ `a*b`). Purely syntactic — no matching semantics change.
340fn collapse_stars(component: &str) -> String {
341    if component.chars().all(|c| c == '*') && component.len() >= 2 {
342        return "**".to_string();
343    }
344    let mut out = String::with_capacity(component.len());
345    let mut last_was_star = false;
346    for c in component.chars() {
347        if c == '*' {
348            if !last_was_star {
349                out.push(c);
350            }
351        } else {
352            out.push(c);
353        }
354        last_was_star = c == '*';
355    }
356    out
357}
358
359/// Match path components, letting the latest `**` consume another component
360/// on a mismatch. Earlier wildcards need no retry once a later one is reached.
361/// There are at most O(pattern components * path components) comparisons.
362fn match_parts(pattern: &[String], path: &[&str]) -> bool {
363    let mut pattern_index = 0;
364    let mut path_index = 0;
365    let mut last_star = None;
366
367    while path_index < path.len() {
368        let part = pattern.get(pattern_index);
369        if part.is_some_and(|part| part == "**") {
370            last_star = Some((pattern_index, path_index));
371            pattern_index += 1;
372        } else if part.is_some_and(|part| match_component(part, path[path_index])) {
373            pattern_index += 1;
374            path_index += 1;
375        } else if let Some((star_index, matched_until)) = &mut last_star {
376            *matched_until += 1;
377            path_index = *matched_until;
378            pattern_index = *star_index + 1;
379        } else {
380            return false;
381        }
382    }
383
384    pattern[pattern_index..].iter().all(|part| part == "**")
385}
386
387/// Match `*` and `?` within one component using Unicode scalar values.
388/// Retrying only the latest `*` bounds work by O(pattern chars * text chars).
389fn match_component(pattern: &str, text: &str) -> bool {
390    let pattern: Vec<char> = pattern.chars().collect();
391    let text: Vec<char> = text.chars().collect();
392    let mut pattern_index = 0;
393    let mut text_index = 0;
394    let mut last_star = None;
395
396    while text_index < text.len() {
397        let token = pattern.get(pattern_index);
398        if token == Some(&'*') {
399            last_star = Some((pattern_index, text_index));
400            pattern_index += 1;
401        } else if token.is_some_and(|&token| token == '?' || token == text[text_index]) {
402            pattern_index += 1;
403            text_index += 1;
404        } else if let Some((star_index, matched_until)) = &mut last_star {
405            *matched_until += 1;
406            text_index = *matched_until;
407            pattern_index = *star_index + 1;
408        } else {
409            return false;
410        }
411    }
412
413    pattern[pattern_index..].iter().all(|&token| token == '*')
414}
415
416#[cfg(test)]
417mod tests {
418    use super::*;
419
420    #[test]
421    fn glob_double_star_matches_nested_and_root() {
422        let g = Glob::compile("**/Generated/**").unwrap();
423        assert!(g.matches(&["GameServer", "Generated", "a.cpp"]));
424        assert!(g.matches(&["Generated", "b.h"]));
425        assert!(!g.matches(&["GameServer", "a.cpp"]));
426        assert!(!g.matches(&["Generated.cpp"]));
427    }
428
429    #[test]
430    fn glob_is_case_insensitive_and_normalizes_slashes() {
431        let g = Glob::compile("**\\generated\\**").unwrap();
432        assert!(g.matches(&["GameServer", "GENERATED", "x.cpp"]));
433    }
434
435    #[test]
436    fn glob_component_wildcards() {
437        let g = Glob::compile("**/*.tmp.*").unwrap();
438        assert!(g.matches(&["a", "x.tmp.cpp"]));
439        assert!(!g.matches(&["a", "y.cpp"]));
440        let q = Glob::compile("??-gen").unwrap();
441        assert!(q.matches(&["ab-gen"]));
442        assert!(!q.matches(&["abc-gen"]));
443    }
444
445    #[test]
446    fn glob_empty_pattern_rejected() {
447        assert!(Glob::compile("").is_err());
448        assert!(Glob::compile("///").is_err());
449    }
450
451    #[test]
452    fn glob_retries_after_expensive_nonmatching_component() {
453        let pattern = format!("**/{}b.cpp", "*a".repeat(8));
454        let directory = "a".repeat(40);
455        let glob = Glob::compile(&pattern).unwrap();
456        // A shared recursion budget used to expire on the directory before
457        // the matcher could reach the matching filename.
458        assert!(glob.matches(&[&directory, "aaaaaaaab.cpp"]));
459        assert!(!glob.matches(&[&directory, "aaaaaaaac.cpp"]));
460    }
461
462    #[test]
463    fn glob_handles_long_literals_and_deep_paths_without_recursion() {
464        let literal = "a".repeat(20_000);
465        assert!(Glob::compile(&literal).unwrap().matches(&[&literal]));
466        let components = vec!["a"; 10_000];
467        let pattern = components.join("/");
468        assert!(Glob::compile(&pattern).unwrap().matches(&components));
469    }
470
471    #[test]
472    fn glob_preserves_unicode_and_raw_backslash_semantics() {
473        let glob = Glob::compile("**/?文*.CPP").unwrap();
474        assert!(glob.matches(&["目录", "中文本.cpp"]));
475        assert!(!glob.matches(&["目录", "文.cpp"]));
476        assert!(Glob::compile_raw("a\\?文").unwrap().matches(&["A\\中文"]));
477        assert!(!Glob::compile_raw("a\\?文").unwrap().matches(&["a", "中文"]));
478    }
479
480    /// Enumerate small finite input spaces for the recursive test oracle.
481    fn short_sequences<T: Clone>(alphabet: &[T], max_len: usize) -> Vec<Vec<T>> {
482        let mut all = vec![Vec::new()];
483        let mut level = vec![Vec::new()];
484        for _ in 0..max_len {
485            let mut next = Vec::new();
486            for prefix in &level {
487                for token in alphabet {
488                    let mut sequence = prefix.clone();
489                    sequence.push(token.clone());
490                    next.push(sequence);
491                }
492            }
493            all.extend(next.iter().cloned());
494            level = next;
495        }
496        all
497    }
498
499    /// Exhaustive wildcard expansion is deliberately limited to tiny tests.
500    fn reference_chars(pattern: &[char], text: &[char]) -> bool {
501        match pattern.first() {
502            None => text.is_empty(),
503            Some('*') => {
504                (0..=text.len()).any(|length| reference_chars(&pattern[1..], &text[length..]))
505            }
506            Some(token) => {
507                text.first()
508                    .is_some_and(|first| *token == '?' || token == first)
509                    && reference_chars(&pattern[1..], &text[1..])
510            }
511        }
512    }
513
514    /// Independent component recursion used only for short generated paths.
515    fn reference_parts(pattern: &[&str], path: &[&str]) -> bool {
516        match pattern.first() {
517            None => path.is_empty(),
518            Some(&"**") => {
519                (0..=path.len()).any(|length| reference_parts(&pattern[1..], &path[length..]))
520            }
521            Some(part) => {
522                path.first().is_some_and(|component| {
523                    reference_chars(
524                        &part.chars().collect::<Vec<_>>(),
525                        &component.chars().collect::<Vec<_>>(),
526                    )
527                }) && reference_parts(&pattern[1..], &path[1..])
528            }
529        }
530    }
531
532    #[test]
533    fn component_matcher_agrees_with_exhaustive_short_input_oracle() {
534        let patterns = short_sequences(&['a', 'b', '?', '*'], 5);
535        let texts = short_sequences(&['a', 'b', '你'], 4);
536        for pattern in &patterns {
537            let pattern_string: String = pattern.iter().collect();
538            for text in &texts {
539                let text_string: String = text.iter().collect();
540                assert_eq!(
541                    match_component(&pattern_string, &text_string),
542                    reference_chars(pattern, text),
543                    "pattern={pattern_string:?}, text={text_string:?}"
544                );
545            }
546        }
547    }
548
549    #[test]
550    fn path_matcher_agrees_with_exhaustive_short_input_oracle() {
551        let patterns = short_sequences(&["a", "b", "?", "a*", "**"], 3);
552        let paths = short_sequences(&["a", "b", "aa", "你"], 3);
553        for pattern in &patterns {
554            let parts: Vec<String> = pattern.iter().map(|part| part.to_string()).collect();
555            for path in &paths {
556                assert_eq!(
557                    match_parts(&parts, path),
558                    reference_parts(pattern, path),
559                    "pattern={pattern:?}, path={path:?}"
560                );
561            }
562        }
563    }
564
565    #[test]
566    fn build_default_whitelist_contains_cpp_not_rc() {
567        let cfg = FilterConfig::build(&FilterOptions::default(), "--ext").unwrap();
568        assert!(cfg.extensions.contains("cpp"));
569        assert!(cfg.extensions.contains("proto"));
570        assert!(!cfg.extensions.contains("rc"));
571        assert!(!cfg.extensions.contains("vcxproj"));
572    }
573
574    #[test]
575    fn build_opt_in_flags_add_their_sets() {
576        let cfg = FilterConfig::build(
577            &FilterOptions {
578                include_rc: true,
579                include_msbuild: true,
580                ..Default::default()
581            },
582            "--ext",
583        )
584        .unwrap();
585        assert!(cfg.extensions.contains("rc"));
586        assert!(cfg.extensions.contains("rc2"));
587        assert!(cfg.extensions.contains("dlg"));
588        assert!(cfg.extensions.contains("vcxproj"));
589        assert!(cfg.extensions.contains("sln"));
590    }
591
592    #[test]
593    fn build_ext_override_replaces_default_set() {
594        let cfg = FilterConfig::build(
595            &FilterOptions {
596                ext_override: vec!["H".into(), "cpp".into()],
597                include_rc: true,
598                ..Default::default()
599            },
600            "--ext",
601        )
602        .unwrap();
603        assert!(cfg.extensions.contains("h"));
604        assert!(cfg.extensions.contains("cpp"));
605        assert!(!cfg.extensions.contains("md"));
606        // Override replaces the default set, so the opt-in flag is inert.
607        assert!(!cfg.extensions.contains("rc"));
608    }
609
610    #[test]
611    fn build_exclude_ext_removes_from_whitelist() {
612        let cfg = FilterConfig::build(
613            &FilterOptions {
614                exclude_ext: vec!["CPP".into(), "".into()],
615                ..Default::default()
616            },
617            "--ext",
618        )
619        .unwrap();
620        assert!(!cfg.extensions.contains("cpp"));
621        assert!(cfg.extensions.contains("h"));
622    }
623
624    #[test]
625    fn build_detects_documented_conflicts() {
626        let err = FilterConfig::build(
627            &FilterOptions {
628                include_rc: true,
629                exclude_ext: vec!["rc".into()],
630                ..Default::default()
631            },
632            "--ext",
633        )
634        .unwrap_err();
635        assert!(err.contains("--include-rc"));
636
637        let err = FilterConfig::build(
638            &FilterOptions {
639                include_msbuild: true,
640                exclude_ext: vec!["vcxproj".into()],
641                ..Default::default()
642            },
643            "--ext",
644        )
645        .unwrap_err();
646        assert!(err.contains("--include-msbuild"));
647    }
648
649    #[test]
650    fn build_rejects_bad_glob() {
651        // No bad glob can exist today (empty is the only failure), but the
652        // plumbing must surface it as Err.
653        let res = FilterConfig::build(
654            &FilterOptions {
655                exclude_globs: vec!["".into()],
656                ..Default::default()
657            },
658            "--ext",
659        );
660        assert!(res.is_err());
661    }
662
663    #[test]
664    fn excluded_dir_name_is_case_insensitive_with_prefix_rule() {
665        let cfg = FilterConfig::build(
666            &FilterOptions {
667                exclude_dirs: vec!["GameServer201".into()],
668                ..Default::default()
669            },
670            "--ext",
671        )
672        .unwrap();
673        assert!(cfg.is_excluded_dir_name(OsStr::new("dep")));
674        assert!(cfg.is_excluded_dir_name(OsStr::new("DEP")));
675        assert!(cfg.is_excluded_dir_name(OsStr::new(".svn")));
676        assert!(cfg.is_excluded_dir_name(OsStr::new("OutputFile1")));
677        assert!(cfg.is_excluded_dir_name(OsStr::new("OutputFiles")));
678        assert!(cfg.is_excluded_dir_name(OsStr::new("gameserver201")));
679        assert!(!cfg.is_excluded_dir_name(OsStr::new("src")));
680        assert!(!cfg.is_excluded_dir_name(OsStr::new("temp.md")));
681    }
682
683    #[test]
684    fn hidden_respects_include_flag() {
685        let cfg = FilterConfig::build(&FilterOptions::default(), "--ext").unwrap();
686        assert!(cfg.is_hidden_name(OsStr::new(".hidden.cpp")));
687        assert!(!cfg.is_hidden_name(OsStr::new("a.cpp")));
688        let cfg = FilterConfig::build(
689            &FilterOptions {
690                include_hidden: true,
691                ..Default::default()
692            },
693            "--ext",
694        )
695        .unwrap();
696        assert!(!cfg.is_hidden_name(OsStr::new(".hidden.cpp")));
697    }
698
699    #[test]
700    fn extension_of_lowercases() {
701        assert_eq!(extension_of(Path::new("a.CPP")), Some("cpp".to_string()));
702        assert_eq!(extension_of(Path::new("a.tar.gz")), Some("gz".to_string()));
703        assert_eq!(extension_of(Path::new("Makefile")), None);
704    }
705}