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