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