utf8-forge 0.1.0

A focused, idempotent, bidirectional charset transcoder for source trees. Default output: UTF-8 without BOM.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
//! File selection: extension whitelist + directory blacklist double gate
//! (`DESIGN.md §5`).
//!
//! Both gates always apply. An extension must be whitelisted AND the path
//! must not hit an excluded directory name, prefix rule, or glob — this is
//! what protects `dep/`, binaries, and build outputs (invariant #4).

use std::collections::HashSet;
use std::ffi::OsStr;
use std::path::Path;

/// Default extension whitelist (source + config/data + docs, `DESIGN §5.1`).
pub const DEFAULT_EXTENSIONS: &[&str] = &[
    // C / C++
    "c", "cc", "cpp", "cxx", "c++", "h", "hh", "hpp", "hxx", "h++", "inl", "ipp", "tpp", "ixx",
    "m", "mm",
    // .NET / JVM
    "cs", "csx", "java", "kt", "kts",
    // Other languages
    "rs", "go", "py", "pyi", "rb", "php", "pl", "pm", "lua", "js", "jsx", "ts", "tsx", "mjs",
    "cjs",
    // Shell
    "sh", "bash", "zsh", "ps1", "bat", "cmd",
    // Data / config
    "json", "jsonc", "yaml", "yml", "toml", "ini", "cfg", "conf", "xml", "csv", "tsv", "sql",
    // Docs / protocol
    "md", "markdown", "txt", "rst", "proto",
];

/// Opt-in resource-script extensions (`--include-rc`). rc.exe has limited
/// UTF-8 support, so these stay off the default whitelist.
pub const RC_EXTENSIONS: &[&str] = &["rc", "rc2", "dlg"];

/// Opt-in MSBuild / Visual Studio extensions (`--include-msbuild`). VS
/// re-saves these with a BOM, so they stay off the default whitelist.
pub const MSBUILD_EXTENSIONS: &[&str] =
    &["sln", "vcxproj", "vcproj", "props", "targets", "filters", "user"];

/// Directory names excluded by default, matched case-insensitively on the
/// directory name itself (`DESIGN §5.2`).
pub const DEFAULT_EXCLUDE_DIRS: &[&str] = &[
    "dep",
    "deps",
    "third_party",
    "third-party",
    "3rdparty",
    "vendor",
    "external",
    "extern",
    "_tools",
    "tools_bin",
    ".svn",
    ".git",
    ".hg",
    ".vs",
    ".idea",
    ".vscode",
    "build",
    "out",
    "bin",
    "obj",
    "debug",
    "release",
    "target",
    "node_modules",
    "__pycache__",
    ".venv",
    "venv",
    "temp",
    "tmp",
    "cache",
];

/// Directory-name prefixes excluded by default (`OutputFile*` /
/// `OutputFiles*`).
pub const DEFAULT_EXCLUDE_PREFIXES: &[&str] = &["outputfile"];

/// Raw filter inputs, normalized by [`FilterConfig::build`].
#[derive(Debug, Clone, Default)]
pub struct FilterOptions {
    /// Overrides the default whitelist entirely when non-empty.
    pub ext_override: Vec<String>,
    /// Appended removals from the effective whitelist.
    pub exclude_ext: Vec<String>,
    /// Extra excluded directory names (appended to the defaults).
    pub exclude_dirs: Vec<String>,
    /// Extra glob patterns matched against root-relative paths.
    pub exclude_globs: Vec<String>,
    /// Adds `RC_EXTENSIONS` to the default whitelist.
    pub include_rc: bool,
    /// Adds `MSBUILD_EXTENSIONS` to the default whitelist.
    pub include_msbuild: bool,
    /// Processes dot-prefixed files/dirs (default excludes still apply).
    pub include_hidden: bool,
    /// Files above this size are recorded as `too_large`, never read.
    pub max_file_size: u64,
}

/// Compiled, effective filter configuration.
#[derive(Debug, Clone)]
pub struct FilterConfig {
    /// Effective extension whitelist (lowercased).
    pub extensions: HashSet<String>,
    /// Effective excluded directory names (lowercased, defaults + user).
    pub exclude_dirs: HashSet<String>,
    /// Effective excluded directory-name prefixes (lowercased).
    pub exclude_prefixes: Vec<String>,
    /// Compiled user glob patterns.
    pub exclude_globs: Vec<Glob>,
    /// Whether dot-prefixed entries are processed.
    pub include_hidden: bool,
    /// Size cap in bytes.
    pub max_file_size: u64,
}

impl FilterConfig {
    /// Build the effective config. Fatal-input problems (conflicting flags,
    /// malformed globs) return `Err` → CLI exit code 2.
    pub fn build(opts: &FilterOptions) -> Result<FilterConfig, String> {
        let exclude_ext: HashSet<String> = normalize_list(&opts.exclude_ext);

        // Documented conflict: opt-in sets must not be simultaneously included
        // and excluded (`AGENT.md §4`, exit 2).
        if opts.include_rc
            && RC_EXTENSIONS.iter().any(|e| exclude_ext.contains(*e))
        {
            return Err(
                "--include-rc conflicts with --exclude-ext (rc/rc2/dlg)".to_string(),
            );
        }
        if opts.include_msbuild
            && MSBUILD_EXTENSIONS.iter().any(|e| exclude_ext.contains(*e))
        {
            return Err(concat!(
                "--include-msbuild conflicts with --exclude-ext ",
                "(sln/vcxproj/vcproj/props/targets/filters/user)"
            )
            .to_string());
        }

        // `-e/--ext` overrides the default whitelist; opt-in flags only apply
        // to the default set.
        let mut extensions: HashSet<String> = if !opts.ext_override.is_empty() {
            normalize_list(&opts.ext_override)
        } else {
            let mut base: HashSet<String> =
                DEFAULT_EXTENSIONS.iter().map(|s| (*s).to_string()).collect();
            if opts.include_rc {
                base.extend(RC_EXTENSIONS.iter().map(|s| (*s).to_string()));
            }
            if opts.include_msbuild {
                base.extend(MSBUILD_EXTENSIONS.iter().map(|s| (*s).to_string()));
            }
            base
        };
        for e in &exclude_ext {
            extensions.remove(e);
        }

        let mut exclude_dirs: HashSet<String> = DEFAULT_EXCLUDE_DIRS
            .iter()
            .map(|s| (*s).to_string())
            .collect();
        exclude_dirs.extend(normalize_list(&opts.exclude_dirs));

        let exclude_prefixes: Vec<String> = DEFAULT_EXCLUDE_PREFIXES
            .iter()
            .map(|s| (*s).to_string())
            .collect();

        let mut exclude_globs = Vec::new();
        for pattern in &opts.exclude_globs {
            match Glob::compile(pattern) {
                Ok(g) => exclude_globs.push(g),
                Err(e) => return Err(format!("invalid --exclude-glob `{pattern}`: {e}")),
            }
        }

        Ok(FilterConfig {
            extensions,
            exclude_dirs,
            exclude_prefixes,
            exclude_globs,
            include_hidden: opts.include_hidden,
            max_file_size: opts.max_file_size,
        })
    }

    /// Case-insensitive directory-name / prefix exclusion check.
    pub fn is_excluded_dir_name(&self, name: &OsStr) -> bool {
        let n = name.to_string_lossy().to_ascii_lowercase();
        self.exclude_dirs.contains(&n)
            || self.exclude_prefixes.iter().any(|p| n.starts_with(p))
    }

    /// True when the dot-prefixed entry must be skipped.
    pub fn is_hidden_name(&self, name: &OsStr) -> bool {
        !self.include_hidden && name.to_string_lossy().starts_with('.')
    }

    /// True when any user glob matches the root-relative path components.
    pub fn is_excluded_by_glob(&self, rel_components: &[&str]) -> bool {
        self.exclude_globs
            .iter()
            .any(|g| g.matches(rel_components))
    }
}

/// Lowercase + trim + drop empties for CLI list values.
fn normalize_list(values: &[String]) -> HashSet<String> {
    values
        .iter()
        .map(|s| s.trim().to_ascii_lowercase())
        .filter(|s| !s.is_empty())
        .collect()
}

/// Lowercased file extension of `path` (`foo.PNG` → `png`); `None` when the
/// file has no extension.
pub fn extension_of(path: &Path) -> Option<String> {
    path.extension()
        .map(|e| e.to_string_lossy().to_ascii_lowercase())
}

/// A compiled `--exclude-glob` pattern.
///
/// Semantics: `/`-separated components; `**` matches zero or more path
/// components; `*` / `?` are wildcards inside one component. Matching is
/// case-insensitive (consistent with directory exclusion on Windows).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Glob {
    parts: Vec<String>,
}

impl Glob {
    /// Compile `pattern`. Empty patterns are rejected.
    pub fn compile(pattern: &str) -> Result<Glob, String> {
        let normalized = pattern.replace('\\', "/");
        let parts: Vec<String> = normalized
            .split('/')
            .filter(|s| !s.is_empty())
            .map(|s| s.to_ascii_lowercase())
            .collect();
        if parts.is_empty() {
            return Err("empty pattern".to_string());
        }
        Ok(Glob { parts })
    }

    /// Match a root-relative path split into components.
    pub fn matches(&self, components: &[&str]) -> bool {
        let lowered: Vec<String> = components
            .iter()
            .map(|c| c.to_ascii_lowercase())
            .collect();
        let refs: Vec<&str> = lowered.iter().map(String::as_str).collect();
        match_parts(&self.parts, &refs)
    }
}

/// Recursive component matcher; `**` consumes zero or more components.
fn match_parts(pat: &[String], path: &[&str]) -> bool {
    match pat.first() {
        None => path.is_empty(),
        Some(first) if first == "**" => {
            for i in 0..=path.len() {
                if match_parts(&pat[1..], &path[i..]) {
                    return true;
                }
            }
            false
        }
        Some(first) => match path.first() {
            None => false,
            Some(head) => match_component(first.as_str(), head) && match_parts(&pat[1..], &path[1..]),
        },
    }
}

/// Wildcard matcher inside a single path component (`*`, `?`).
fn match_component(pat: &str, s: &str) -> bool {
    let p: Vec<char> = pat.chars().collect();
    let t: Vec<char> = s.chars().collect();
    match_chars(&p, &t)
}

fn match_chars(pat: &[char], text: &[char]) -> bool {
    match pat.first() {
        None => text.is_empty(),
        Some('*') => (0..=text.len()).any(|i| match_chars(&pat[1..], &text[i..])),
        Some('?') => {
            !text.is_empty() && match_chars(&pat[1..], &text[1..])
        }
        Some(c) => !text.is_empty() && text[0] == *c && match_chars(&pat[1..], &text[1..]),
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn glob_double_star_matches_nested_and_root() {
        let g = Glob::compile("**/Generated/**").unwrap();
        assert!(g.matches(&["GameServer", "Generated", "a.cpp"]));
        assert!(g.matches(&["Generated", "b.h"]));
        assert!(!g.matches(&["GameServer", "a.cpp"]));
        assert!(!g.matches(&["Generated.cpp"]));
    }

    #[test]
    fn glob_is_case_insensitive_and_normalizes_slashes() {
        let g = Glob::compile("**\\generated\\**").unwrap();
        assert!(g.matches(&["GameServer", "GENERATED", "x.cpp"]));
    }

    #[test]
    fn glob_component_wildcards() {
        let g = Glob::compile("**/*.tmp.*").unwrap();
        assert!(g.matches(&["a", "x.tmp.cpp"]));
        assert!(!g.matches(&["a", "y.cpp"]));
        let q = Glob::compile("??-gen").unwrap();
        assert!(q.matches(&["ab-gen"]));
        assert!(!q.matches(&["abc-gen"]));
    }

    #[test]
    fn glob_empty_pattern_rejected() {
        assert!(Glob::compile("").is_err());
        assert!(Glob::compile("///").is_err());
    }

    #[test]
    fn build_default_whitelist_contains_cpp_not_rc() {
        let cfg = FilterConfig::build(&FilterOptions::default()).unwrap();
        assert!(cfg.extensions.contains("cpp"));
        assert!(cfg.extensions.contains("proto"));
        assert!(!cfg.extensions.contains("rc"));
        assert!(!cfg.extensions.contains("vcxproj"));
    }

    #[test]
    fn build_opt_in_flags_add_their_sets() {
        let cfg = FilterConfig::build(&FilterOptions {
            include_rc: true,
            include_msbuild: true,
            ..Default::default()
        })
        .unwrap();
        assert!(cfg.extensions.contains("rc"));
        assert!(cfg.extensions.contains("rc2"));
        assert!(cfg.extensions.contains("dlg"));
        assert!(cfg.extensions.contains("vcxproj"));
        assert!(cfg.extensions.contains("sln"));
    }

    #[test]
    fn build_ext_override_replaces_default_set() {
        let cfg = FilterConfig::build(&FilterOptions {
            ext_override: vec!["H".into(), "cpp".into()],
            include_rc: true,
            ..Default::default()
        })
        .unwrap();
        assert!(cfg.extensions.contains("h"));
        assert!(cfg.extensions.contains("cpp"));
        assert!(!cfg.extensions.contains("md"));
        // Override replaces the default set, so the opt-in flag is inert.
        assert!(!cfg.extensions.contains("rc"));
    }

    #[test]
    fn build_exclude_ext_removes_from_whitelist() {
        let cfg = FilterConfig::build(&FilterOptions {
            exclude_ext: vec!["CPP".into(), "".into()],
            ..Default::default()
        })
        .unwrap();
        assert!(!cfg.extensions.contains("cpp"));
        assert!(cfg.extensions.contains("h"));
    }

    #[test]
    fn build_detects_documented_conflicts() {
        let err = FilterConfig::build(&FilterOptions {
            include_rc: true,
            exclude_ext: vec!["rc".into()],
            ..Default::default()
        })
        .unwrap_err();
        assert!(err.contains("--include-rc"));

        let err = FilterConfig::build(&FilterOptions {
            include_msbuild: true,
            exclude_ext: vec!["vcxproj".into()],
            ..Default::default()
        })
        .unwrap_err();
        assert!(err.contains("--include-msbuild"));
    }

    #[test]
    fn build_rejects_bad_glob() {
        // No bad glob can exist today (empty is the only failure), but the
        // plumbing must surface it as Err.
        let res = FilterConfig::build(&FilterOptions {
            exclude_globs: vec!["".into()],
            ..Default::default()
        });
        assert!(res.is_err());
    }

    #[test]
    fn excluded_dir_name_is_case_insensitive_with_prefix_rule() {
        let cfg = FilterConfig::build(&FilterOptions {
            exclude_dirs: vec!["GameServer201".into()],
            ..Default::default()
        })
        .unwrap();
        assert!(cfg.is_excluded_dir_name(OsStr::new("dep")));
        assert!(cfg.is_excluded_dir_name(OsStr::new("DEP")));
        assert!(cfg.is_excluded_dir_name(OsStr::new(".svn")));
        assert!(cfg.is_excluded_dir_name(OsStr::new("OutputFile1")));
        assert!(cfg.is_excluded_dir_name(OsStr::new("OutputFiles")));
        assert!(cfg.is_excluded_dir_name(OsStr::new("gameserver201")));
        assert!(!cfg.is_excluded_dir_name(OsStr::new("src")));
        assert!(!cfg.is_excluded_dir_name(OsStr::new("temp.md")));
    }

    #[test]
    fn hidden_respects_include_flag() {
        let cfg = FilterConfig::build(&FilterOptions::default()).unwrap();
        assert!(cfg.is_hidden_name(OsStr::new(".hidden.cpp")));
        assert!(!cfg.is_hidden_name(OsStr::new("a.cpp")));
        let cfg = FilterConfig::build(&FilterOptions {
            include_hidden: true,
            ..Default::default()
        })
        .unwrap();
        assert!(!cfg.is_hidden_name(OsStr::new(".hidden.cpp")));
    }

    #[test]
    fn extension_of_lowercases() {
        assert_eq!(extension_of(Path::new("a.CPP")), Some("cpp".to_string()));
        assert_eq!(extension_of(Path::new("a.tar.gz")), Some("gz".to_string()));
        assert_eq!(extension_of(Path::new("Makefile")), None);
    }
}