Skip to main content

utf8_forge/
config.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//! TOML config file support (`--config <PATH>`).
16//!
17//! Precedence: CLI flags > config values > built-in defaults. Lists replace
18//! (never concatenate) across layers so the effective whitelist stays
19//! auditable. Unknown keys, malformed TOML, and wrong types are fatal input
20//! errors — a typo that silently does nothing is worse than a loud failure.
21//! Deliberately absent from the schema: `root`, `report`, `dry_run`, `url`,
22//! `output`, `quiet`, `verbose`, `ignore_file` — options that select what
23//! gets written where or flip write behavior must stay visible on the
24//! command line.
25
26use std::path::Path;
27
28use anyhow::{Context, bail};
29use serde::Deserialize;
30
31use crate::transcoder::TargetEncoding;
32
33/// Whole config document. Every section and field is optional.
34#[derive(Debug, Clone, Default, Deserialize)]
35#[serde(deny_unknown_fields)]
36pub struct ForgeConfig {
37    /// Whitelist / exclusion overrides (`[filter]`).
38    #[serde(default)]
39    pub filter: FilterSection,
40    /// Conversion options (`[convert]`).
41    #[serde(default)]
42    pub convert: ConvertSection,
43    /// Run options (`[options]`).
44    #[serde(default)]
45    pub options: OptionsSection,
46}
47
48/// `[filter]` section: mirrors the corresponding CLI flags.
49#[derive(Debug, Clone, Default, Deserialize)]
50#[serde(deny_unknown_fields)]
51pub struct FilterSection {
52    #[serde(default)]
53    pub extensions: Vec<String>,
54    #[serde(default)]
55    pub exclude_dirs: Vec<String>,
56    #[serde(default)]
57    pub exclude_ext: Vec<String>,
58    #[serde(default)]
59    pub exclude_globs: Vec<String>,
60    #[serde(default)]
61    pub include_rc: bool,
62    #[serde(default)]
63    pub include_msbuild: bool,
64    #[serde(default)]
65    pub include_hidden: bool,
66}
67
68/// `[convert]` section: conversion options for `convert` and `fix`.
69#[derive(Debug, Clone, Default, Deserialize)]
70#[serde(deny_unknown_fields)]
71pub struct ConvertSection {
72    #[serde(default)]
73    pub target: Option<String>,
74    #[serde(default)]
75    pub backup_dir: Option<String>,
76}
77
78/// `[options]` section: run sizing.
79#[derive(Debug, Clone, Default, Deserialize)]
80#[serde(deny_unknown_fields)]
81pub struct OptionsSection {
82    #[serde(default)]
83    pub max_file_size: Option<u64>,
84    #[serde(default)]
85    pub threads: Option<usize>,
86}
87
88/// Load and parse the config file at `path`. Fatal on missing / unreadable /
89/// malformed input (exit 2) — the caller treats any `Err` as fatal.
90pub fn load(path: &Path) -> anyhow::Result<ForgeConfig> {
91    if !path.is_file() {
92        bail!("config file `{}` not found", path.display());
93    }
94    let text = std::fs::read_to_string(path)
95        .with_context(|| format!("cannot read config file `{}`", path.display()))?;
96    let cfg: ForgeConfig = toml::from_str(&text)
97        .with_context(|| format!("config file `{}` is not valid", path.display()))?;
98    Ok(cfg)
99}
100
101impl ForgeConfig {
102    /// Parse `[convert].target` with the same grammar as the CLI value.
103    /// Invalid values name the config key so the operator can find the line.
104    pub fn target(&self) -> anyhow::Result<Option<TargetEncoding>> {
105        match &self.convert.target {
106            None => Ok(None),
107            Some(raw) => TargetEncoding::parse(raw).map(Some).ok_or_else(|| {
108                anyhow::anyhow!(
109                    "config [convert].target: invalid target encoding `{raw}` (expected utf-8 | utf-8-bom | gb18030 | utf-16le | utf-16be)"
110                )
111            }),
112        }
113    }
114}
115
116#[cfg(test)]
117mod tests {
118    use super::*;
119
120    #[test]
121    fn parses_full_document() {
122        let cfg: ForgeConfig = toml::from_str(
123            r#"
124[filter]
125extensions = ["c", "cpp"]
126exclude_dirs = ["legacy"]
127include_rc = true
128
129[convert]
130target = "utf-16le"
131backup_dir = "/tmp/bk"
132
133[options]
134max_file_size = 1024
135threads = 4
136"#,
137        )
138        .unwrap();
139        assert_eq!(cfg.filter.extensions, vec!["c", "cpp"]);
140        assert!(cfg.filter.include_rc);
141        assert_eq!(cfg.options.max_file_size, Some(1024));
142        assert_eq!(cfg.target().unwrap(), Some(TargetEncoding::Utf16Le));
143    }
144
145    #[test]
146    fn empty_document_is_valid() {
147        let cfg: ForgeConfig = toml::from_str("").unwrap();
148        assert!(cfg.filter.extensions.is_empty());
149        assert_eq!(cfg.target().unwrap(), None);
150    }
151
152    #[test]
153    fn unknown_keys_are_rejected() {
154        let err = toml::from_str::<ForgeConfig>(
155            "[filter]
156typo_key = 1
157",
158        )
159        .unwrap_err();
160        assert!(err.to_string().contains("typo_key"), "{err}");
161    }
162
163    #[test]
164    fn invalid_target_value_is_rejected_with_key_name() {
165        let cfg: ForgeConfig = toml::from_str("[convert]\ntarget = \"gbk\"\n").unwrap();
166        let err = cfg.target().unwrap_err().to_string();
167        assert!(err.contains("[convert].target"), "{err}");
168    }
169}