Skip to main content

utf8_forge/
cli.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//! clap definitions for the CLI surface.
16//!
17//! All flags carry `///` doc comments in English.
18//! clap parse failures exit with code 2, matching the documented fatal-code
19//! contract; semantic conflicts (opt-in vs `--exclude-ext`) are validated in
20//! [`FilterConfig::build`](crate::filter::FilterConfig::build).
21//!
22//! The flag surface is normalized per subcommand: `scan` / `verify` accept
23//! only detection + filtering + reporting options; conversion-only options
24//! (`--target`, `--dry-run`, `--backup-dir`, `--url`, `--output`) exist solely
25//! on `convert`, so misuse fails fast with exit 2 instead of being ignored.
26
27use std::path::PathBuf;
28
29use clap::{Args, Parser, Subcommand};
30
31use crate::transcoder::TargetEncoding;
32
33/// Built-in per-file size cap (200 MiB) used when neither the CLI nor the
34/// config file supplies `--max-file-size`.
35pub(crate) const DEFAULT_MAX_FILE_SIZE: u64 = 200 * 1024 * 1024;
36
37/// utf8-forge — a focused, idempotent, bidirectional charset transcoder.
38#[derive(Debug, Parser)]
39#[command(
40    name = "utf8-forge",
41    version,
42    about = "Idempotent charset transcoder for source trees (default target: UTF-8 without BOM)",
43    after_help = "Exit codes: 0 ok; 1 per-file issues (scan/convert/fetch, diff --fail-on-change); \
44                  2 fatal (bad args, setup failure); 3 verify/fix gate failure"
45)]
46pub struct Cli {
47    /// Selected subcommand.
48    #[command(subcommand)]
49    pub command: Commands,
50}
51
52/// Subcommands. Named `Commands` to avoid colliding with
53/// the imported `clap::Subcommand` derive trait.
54#[derive(Debug, Subcommand)]
55pub enum Commands {
56    /// Detect only; report distribution (no writes).
57    Scan(TreeArgs),
58    /// Detect + transcode + atomic write (supports --dry-run, --url).
59    Convert(ConvertArgs),
60    /// Assert all whitelisted files are UTF-8 without BOM (exit 3 on failure).
61    Verify(TreeArgs),
62    /// Detect + transcode + verify in one pass (exit 3 when the gate fails).
63    Fix(FixArgs),
64    /// Compare two utf8-forge JSON reports per path (any mode with files[]).
65    Diff(DiffArgs),
66}
67
68/// Detection / filtering / reporting options shared by `scan`, `verify`, and
69/// `convert` (tree mode). Conversion-only options live on [`ConvertArgs`].
70#[derive(Debug, Args, Clone)]
71pub struct TreeArgs {
72    /// Root directory to process recursively.
73    #[arg(short = 'r', long = "root", default_value = ".")]
74    pub root: PathBuf,
75
76    /// Override the default extension whitelist (comma-separated).
77    #[arg(short = 'e', long = "ext", value_delimiter = ',')]
78    pub ext: Vec<String>,
79
80    /// Extra excluded directory names (comma-separated, appended to defaults).
81    #[arg(short = 'x', long = "exclude", value_delimiter = ',')]
82    pub exclude: Vec<String>,
83
84    /// Extra excluded extensions (comma-separated, appended).
85    #[arg(short = 'X', long = "exclude-ext", value_delimiter = ',')]
86    pub exclude_ext: Vec<String>,
87
88    /// Extra glob pattern excluding root-relative paths (repeatable).
89    #[arg(long = "exclude-glob")]
90    pub exclude_glob: Vec<String>,
91
92    /// Include .rc/.rc2/.dlg (rc.exe has limited UTF-8 support).
93    #[arg(long = "include-rc")]
94    pub include_rc: bool,
95
96    /// Include .sln/.vcxproj/... (VS re-saves these with a BOM).
97    #[arg(long = "include-msbuild")]
98    pub include_msbuild: bool,
99
100    /// Process dot-prefixed files and directories.
101    #[arg(long = "include-hidden")]
102    pub include_hidden: bool,
103
104    /// Skip files above this size, recorded as too_large (bytes; default
105    /// 200 MiB). CLI value overrides the config file.
106    #[arg(long = "max-file-size")]
107    pub max_file_size: Option<u64>,
108
109    /// Load defaults from this TOML config file (CLI flags override config
110    /// values; missing/malformed file or unknown keys are fatal).
111    #[arg(long = "config")]
112    pub config: Option<PathBuf>,
113
114    /// Load gitignore-style exclusion patterns from this file (fatal when
115    /// missing; auto-discovery of `<root>/.utf8forgeignore` is replaced).
116    #[arg(long = "ignore-file", conflicts_with = "no_ignore_file")]
117    pub ignore_file: Option<PathBuf>,
118
119    /// Disable ignore-file handling entirely, including auto-discovery of
120    /// `<root>/.utf8forgeignore`.
121    #[arg(long = "no-ignore-file")]
122    pub no_ignore_file: bool,
123
124    /// Rayon worker thread count (default: CPU count; values below 1 are
125    /// treated as 1, values above 1024 are a fatal input error).
126    #[arg(long = "threads")]
127    pub threads: Option<usize>,
128
129    /// Write a JSON report to this path.
130    #[arg(long = "report")]
131    pub report: Option<PathBuf>,
132
133    /// Print errors only (verify/fix still print gate-critical walk
134    /// warnings; overrides --verbose).
135    #[arg(short = 'q', long = "quiet")]
136    pub quiet: bool,
137
138    /// Print one line per file.
139    #[arg(short = 'v', long = "verbose")]
140    pub verbose: bool,
141}
142
143impl Default for TreeArgs {
144    /// Mirrors the clap defaults (`root = "."`, `max_file_size` unset so the
145    /// config file merge applies, with the built-in 200 MiB cap applied by
146    /// [`TreeArgs::effective_max_file_size`]) so programmatic/test invocation
147    /// behaves exactly like the CLI.
148    fn default() -> Self {
149        TreeArgs {
150            root: PathBuf::from("."),
151            ext: Vec::new(),
152            exclude: Vec::new(),
153            exclude_ext: Vec::new(),
154            exclude_glob: Vec::new(),
155            include_rc: false,
156            include_msbuild: false,
157            include_hidden: false,
158            max_file_size: None,
159            config: None,
160            ignore_file: None,
161            no_ignore_file: false,
162            threads: None,
163            report: None,
164            quiet: false,
165            verbose: false,
166        }
167    }
168}
169
170/// `convert` additions: conversion options + remote fetch. Extends the shared
171/// [`TreeArgs`] (whose `--root` is ignored when `--url` is given).
172#[derive(Debug, Args, Clone)]
173pub struct ConvertArgs {
174    /// Shared detection / filtering / reporting options.
175    #[command(flatten)]
176    pub common: TreeArgs,
177
178    /// Target encoding: utf-8 | utf-8-bom | gb18030 | utf-16le | utf-16be
179    /// (default utf-8). CLI value overrides the config file.
180    #[arg(short = 't', long = "target")]
181    pub target: Option<TargetEncoding>,
182
183    /// Report what would change without writing anything.
184    #[arg(long = "dry-run")]
185    pub dry_run: bool,
186
187    /// Mirror original bytes under this directory before overwriting.
188    #[arg(long = "backup-dir")]
189    pub backup_dir: Option<PathBuf>,
190
191    /// Fetch this remote file and transcode it (convert only).
192    #[arg(long = "url")]
193    pub url: Option<String>,
194
195    /// Destination path for --url (derived from the URL when omitted).
196    #[arg(long = "output", requires = "url")]
197    pub output: Option<PathBuf>,
198}
199
200impl Default for ConvertArgs {
201    /// Tree-mode defaults with `utf-8` target and no remote fetch.
202    fn default() -> Self {
203        ConvertArgs {
204            common: TreeArgs::default(),
205            target: Some(TargetEncoding::Utf8),
206            dry_run: false,
207            backup_dir: None,
208            url: None,
209            output: None,
210        }
211    }
212}
213
214impl TreeArgs {
215    /// The size cap after config merge (built-in default: 200 MiB).
216    pub fn effective_max_file_size(&self) -> u64 {
217        self.max_file_size.unwrap_or(DEFAULT_MAX_FILE_SIZE)
218    }
219}
220
221impl ConvertArgs {
222    /// The target encoding after config merge (built-in default: utf-8).
223    pub fn target_or_default(&self) -> TargetEncoding {
224        self.target.unwrap_or(TargetEncoding::Utf8)
225    }
226}
227
228/// `fix` args: shared tree options plus conversion options. No `--url` /
229/// `--output` — fix is a tree operation only.
230#[derive(Debug, Args, Clone)]
231pub struct FixArgs {
232    /// Shared detection / filtering / reporting options.
233    #[command(flatten)]
234    pub common: TreeArgs,
235
236    /// Target encoding (default utf-8). CLI value overrides the config file.
237    #[arg(short = 't', long = "target")]
238    pub target: Option<TargetEncoding>,
239
240    /// Report what would change without writing anything (the verify pass
241    /// still runs read-only on the current state).
242    #[arg(long = "dry-run")]
243    pub dry_run: bool,
244
245    /// Mirror original bytes under this directory before overwriting.
246    #[arg(long = "backup-dir")]
247    pub backup_dir: Option<PathBuf>,
248}
249
250impl Default for FixArgs {
251    /// Tree-mode defaults with `utf-8` target.
252    fn default() -> Self {
253        FixArgs {
254            common: TreeArgs::default(),
255            target: Some(TargetEncoding::Utf8),
256            dry_run: false,
257            backup_dir: None,
258        }
259    }
260}
261
262impl FixArgs {
263    /// The target encoding after config merge (built-in default: utf-8).
264    pub fn target_or_default(&self) -> TargetEncoding {
265        self.target.unwrap_or(TargetEncoding::Utf8)
266    }
267}
268
269/// `diff` args: two report files to compare. No tree options.
270#[derive(Debug, Args, Clone)]
271pub struct DiffArgs {
272    /// The earlier report (JSON, any mode that has files[]).
273    #[arg(long = "before")]
274    pub before: PathBuf,
275
276    /// The later report.
277    #[arg(long = "after")]
278    pub after: PathBuf,
279
280    /// Write the diff JSON here; otherwise pretty-print to stdout.
281    #[arg(long = "report")]
282    pub report: Option<PathBuf>,
283
284    /// Exit 1 when the diff is non-empty (added + removed + changed > 0).
285    #[arg(long = "fail-on-change")]
286    pub fail_on_change: bool,
287}
288
289/// Wrap a subcommand into a full [`Cli`], mirroring what the parser would
290/// produce. Handy for tests and programmatic invocation.
291impl From<Commands> for Cli {
292    fn from(command: Commands) -> Cli {
293        Cli { command }
294    }
295}