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    /// Whitelist override. `None` = key absent (the default whitelist stays
53    /// in effect); `Some(list)` replaces it, and an empty list is a fatal
54    /// input error at merge time — silently scanning nothing is worse than a
55    /// loud failure.
56    #[serde(default)]
57    pub extensions: Option<Vec<String>>,
58    #[serde(default)]
59    pub exclude_dirs: Vec<String>,
60    #[serde(default)]
61    pub exclude_ext: Vec<String>,
62    #[serde(default)]
63    pub exclude_globs: Vec<String>,
64    #[serde(default)]
65    pub include_rc: bool,
66    #[serde(default)]
67    pub include_msbuild: bool,
68    #[serde(default)]
69    pub include_hidden: bool,
70}
71
72/// `[convert]` section: conversion options for `convert` and `fix`.
73#[derive(Debug, Clone, Default, Deserialize)]
74#[serde(deny_unknown_fields)]
75pub struct ConvertSection {
76    #[serde(default)]
77    pub target: Option<String>,
78    /// Backup directory override. An empty string is a fatal input error at
79    /// merge time — an unnamed directory can never be a usable target.
80    #[serde(default)]
81    pub backup_dir: Option<String>,
82}
83
84/// `[options]` section: run sizing.
85#[derive(Debug, Clone, Default, Deserialize)]
86#[serde(deny_unknown_fields)]
87pub struct OptionsSection {
88    #[serde(default)]
89    pub max_file_size: Option<u64>,
90    #[serde(default)]
91    pub threads: Option<usize>,
92}
93
94/// Load and parse the config file at `path`. Fatal on missing / unreadable /
95/// malformed input (exit 2) — the caller treats any `Err` as fatal.
96pub fn load(path: &Path) -> anyhow::Result<ForgeConfig> {
97    if !path.is_file() {
98        bail!("config file `{}` not found", path.display());
99    }
100    let text = std::fs::read_to_string(path)
101        .with_context(|| format!("cannot read config file `{}`", path.display()))?;
102    let cfg: ForgeConfig = toml::from_str(&text)
103        .with_context(|| format!("config file `{}` is not valid", path.display()))?;
104    Ok(cfg)
105}
106
107impl ForgeConfig {
108    /// Parse `[convert].target` with the same grammar as the CLI value.
109    /// Invalid values name the config key so the operator can find the line.
110    pub fn target(&self) -> anyhow::Result<Option<TargetEncoding>> {
111        match &self.convert.target {
112            None => Ok(None),
113            Some(raw) => TargetEncoding::parse(raw).map(Some).ok_or_else(|| {
114                anyhow::anyhow!(
115                    "config [convert].target: invalid target encoding `{raw}` (expected utf-8 | utf-8-bom | gb18030 | utf-16le | utf-16be)"
116                )
117            }),
118        }
119    }
120}
121
122#[cfg(test)]
123mod tests {
124    use super::*;
125
126    #[test]
127    fn parses_full_document() {
128        let cfg: ForgeConfig = toml::from_str(
129            r#"
130[filter]
131extensions = ["c", "cpp"]
132exclude_dirs = ["legacy"]
133include_rc = true
134
135[convert]
136target = "utf-16le"
137backup_dir = "/tmp/bk"
138
139[options]
140max_file_size = 1024
141threads = 4
142"#,
143        )
144        .unwrap();
145        assert_eq!(
146            cfg.filter.extensions,
147            Some(vec!["c".to_string(), "cpp".to_string()])
148        );
149        assert!(cfg.filter.include_rc);
150        assert_eq!(cfg.options.max_file_size, Some(1024));
151        assert_eq!(cfg.target().unwrap(), Some(TargetEncoding::Utf16Le));
152    }
153
154    #[test]
155    fn empty_document_is_valid() {
156        let cfg: ForgeConfig = toml::from_str("").unwrap();
157        assert!(cfg.filter.extensions.is_none());
158        assert_eq!(cfg.target().unwrap(), None);
159    }
160
161    #[test]
162    fn unknown_keys_are_rejected() {
163        let err = toml::from_str::<ForgeConfig>(
164            "[filter]
165typo_key = 1
166",
167        )
168        .unwrap_err();
169        assert!(err.to_string().contains("typo_key"), "{err}");
170    }
171
172    #[test]
173    fn invalid_target_value_is_rejected_with_key_name() {
174        let cfg: ForgeConfig = toml::from_str("[convert]\ntarget = \"gbk\"\n").unwrap();
175        let err = cfg.target().unwrap_err().to_string();
176        assert!(err.contains("[convert].target"), "{err}");
177    }
178}