Skip to main content

utf8_forge/
lib.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//! `utf8-forge` — a focused, idempotent, bidirectional charset transcoder for
16//! source trees (default output: UTF-8 without BOM).
17//!
18//! This crate primarily ships the [`utf8-forge` CLI](cli::Cli); the library
19//! surface is public so integration tests and downstream pipelines can drive
20//! the same detection and transcoding machinery the binary uses. Detection is
21//! rule-based (BOM prefixes, then strict UTF-8, then strict GB18030) and
22//! never guesses; transcoding is strict on both ends, so mojibake is never
23//! written.
24//!
25//! ```rust
26//! use utf8_forge::detector::detect;
27//! use utf8_forge::transcoder::{TargetEncoding, transcode};
28//!
29//! let bytes = [0xEF, 0xBB, 0xBF, b'h', b'i'];
30//! assert_eq!(detect(&bytes).tag(), "utf-8-bom");
31//!
32//! let converted = transcode(&bytes, TargetEncoding::Utf8).unwrap();
33//! match converted {
34//!     utf8_forge::transcoder::TranscodeOutcome::Changed(out) => assert_eq!(out, b"hi"),
35//!     utf8_forge::transcoder::TranscodeOutcome::Unchanged => panic!("BOM must be stripped"),
36//! }
37//! ```
38//!
39//! # CLI orchestration
40//! Per-file pipelines, report assembly, and the [`run()`](fn@run) entry point
41//! with exit-code mapping:
42//! - `0` success
43//! - `1` non-fatal per-file issues (`unknown`, `decode_error`, `encode_error`,
44//!   `io_error`, `fetch_error`)
45//! - `2` fatal (bad args, missing root, I/O setup failure) — also emitted by
46//!   clap on parse errors
47//! - `3` `verify`/`fix` gate failure (non-UTF-8 whitelisted files; fix's
48//!   verify gate wins over convert-side issues)
49
50// Public modules (lib target so integration tests can exercise the
51// pipeline directly; the binary in `main.rs` stays a thin wrapper).
52pub mod cli;
53pub mod config;
54pub mod detector;
55pub mod differ;
56pub mod error;
57#[cfg(feature = "remote")]
58pub mod fetcher;
59pub mod filter;
60pub mod ignorefile;
61pub mod reporter;
62pub mod transcoder;
63pub mod walker;
64pub mod writer;
65
66use std::fs;
67use std::io::Read;
68use std::path::{Path, PathBuf};
69use std::time::Instant;
70
71use anyhow::{Context, bail};
72use rayon::prelude::*;
73
74use crate::cli::{Cli, Commands, ConvertArgs, DiffArgs, FixArgs, TreeArgs};
75use crate::detector::{DetectedEncoding, detect};
76use crate::differ::DiffInput;
77use crate::error::ForgeError;
78use crate::filter::{FilterConfig, FilterOptions};
79use crate::reporter::{
80    ConsoleCfg, ConvertSummary, FileRecord, FixSummary, OptionsBlock, Report, ScanSummary, Summary,
81    VerifySummary, print_header, print_problem, print_verbose, write_report,
82};
83use crate::transcoder::{TargetEncoding, TranscodeOutcome, transcode_detected};
84use crate::walker::collect_files;
85
86/// Dispatch a parsed CLI and map the outcome to a process exit code.
87/// Fatal setup errors print to stderr and yield exit code 2.
88pub fn run(cli: Cli) -> i32 {
89    let outcome = match cli.command {
90        Commands::Scan(args) => cmd_scan(&args),
91        Commands::Convert(args) => cmd_convert(&args),
92        Commands::Verify(args) => cmd_verify(&args),
93        Commands::Fix(args) => cmd_fix(&args),
94        Commands::Diff(args) => cmd_diff(&args),
95    };
96    outcome.unwrap_or_else(|err| {
97        eprintln!("[utf8-forge] fatal: {err:#}");
98        2
99    })
100}
101
102// ---------------------------------------------------------------------------
103// Per-file processors
104// ---------------------------------------------------------------------------
105
106/// Read at most one byte beyond the cap so callers can distinguish an exact
107/// fit from oversized content even when the file grows after the metadata
108/// check. The extra byte is only used for the size verdict, never transcoded.
109fn read_file_limited(path: &Path, max_file_size: u64) -> std::io::Result<Vec<u8>> {
110    let mut bytes = Vec::new();
111    fs::File::open(path)?
112        .take(max_file_size.saturating_add(1))
113        .read_to_end(&mut bytes)?;
114    Ok(bytes)
115}
116
117/// Deferred `FileRecord` builder that stamps per-file duration at completion.
118struct RecBuilder<'a> {
119    path: &'a Path,
120    started: Instant,
121}
122
123impl<'a> RecBuilder<'a> {
124    fn new(path: &'a Path) -> RecBuilder<'a> {
125        RecBuilder {
126            path,
127            started: Instant::now(),
128        }
129    }
130
131    fn done(
132        self,
133        detected: Option<&'static str>,
134        action: &'static str,
135        bytes_before: Option<u64>,
136        bytes_after: Option<u64>,
137        error: Option<String>,
138    ) -> FileRecord {
139        FileRecord {
140            path: self.path.to_string_lossy().into_owned(),
141            detected,
142            action,
143            bytes_before,
144            bytes_after,
145            duration_us: self.started.elapsed().as_micros() as u64,
146            error,
147        }
148    }
149}
150
151/// Detect only. Oversized files are never read.
152pub fn scan_file(path: &Path, max_file_size: u64) -> FileRecord {
153    let b = RecBuilder::new(path);
154    let size = fs::metadata(path).map(|m| m.len()).ok();
155    if let Some(sz) = size
156        && sz > max_file_size
157    {
158        return b.done(None, "skipped_too_large", Some(sz), None, None);
159    }
160    let bytes = match read_file_limited(path, max_file_size) {
161        Ok(bytes) => bytes,
162        Err(e) => return b.done(None, "error", size, None, Some(format!("io_error: {e}"))),
163    };
164    let sz = bytes.len() as u64;
165    if sz > max_file_size {
166        return b.done(None, "skipped_too_large", Some(sz), None, None);
167    }
168    let det = detect(&bytes);
169    b.done(Some(det.tag()), "detected", Some(sz), None, None)
170}
171
172/// Shared context for tree-mode conversion.
173#[derive(Debug, Clone)]
174pub struct ConvertCtx {
175    pub root: std::path::PathBuf,
176    pub target: TargetEncoding,
177    pub dry_run: bool,
178    pub backup_dir: Option<std::path::PathBuf>,
179    pub max_file_size: u64,
180}
181
182/// Detect + transcode + (unless dry-run) backup + atomic write.
183///
184/// Byte-identical outcomes are recorded as `unchanged` and never touch the
185/// filesystem, so unchanged files keep their mtime. Every failure is
186/// contained in this one record (per-file error isolation).
187pub fn convert_file(path: &Path, ctx: &ConvertCtx) -> FileRecord {
188    let b = RecBuilder::new(path);
189    let size = fs::metadata(path).map(|m| m.len()).ok();
190    if let Some(sz) = size
191        && sz > ctx.max_file_size
192    {
193        return b.done(None, "skipped_too_large", Some(sz), None, None);
194    }
195    let bytes = match read_file_limited(path, ctx.max_file_size) {
196        Ok(bytes) => bytes,
197        Err(e) => return b.done(None, "error", size, None, Some(format!("io_error: {e}"))),
198    };
199    let sz = bytes.len() as u64;
200    if sz > ctx.max_file_size {
201        return b.done(None, "skipped_too_large", Some(sz), None, None);
202    }
203    let det = detect(&bytes);
204    let tag = det.tag();
205
206    match transcode_detected(&bytes, det, ctx.target) {
207        Err(ForgeError::UnknownEncoding) => {
208            b.done(Some(tag), "skipped_unknown", Some(sz), None, None)
209        }
210        Err(e) => b.done(
211            Some(tag),
212            "error",
213            Some(sz),
214            None,
215            Some(format!("{}: {e}", e.category())),
216        ),
217        Ok(TranscodeOutcome::Unchanged) => b.done(Some(tag), "unchanged", Some(sz), Some(sz), None),
218        Ok(TranscodeOutcome::Changed(new_bytes)) => {
219            if ctx.dry_run {
220                return b.done(
221                    Some(tag),
222                    "would_convert",
223                    Some(sz),
224                    Some(new_bytes.len() as u64),
225                    None,
226                );
227            }
228            // Refuse to clobber write-protected files: POSIX rename would
229            // silently bypass the permission bits, but the operator locked
230            // that file on purpose.
231            let write_protected = fs::metadata(path)
232                .map(|m| m.permissions().readonly())
233                .unwrap_or(false);
234            if write_protected {
235                return b.done(
236                    Some(tag),
237                    "error",
238                    Some(sz),
239                    None,
240                    Some(
241                        "io_error: file is write-protected (read-only); chmod +w to convert".into(),
242                    ),
243                );
244            }
245            // Backup the original bytes before the rename, so the backup
246            // always holds the pre-conversion content.
247            if let Some(backup_dir) = &ctx.backup_dir
248                && let Err(e) = writer::backup_original(&ctx.root, path, backup_dir, &bytes)
249            {
250                return b.done(
251                    Some(tag),
252                    "error",
253                    Some(sz),
254                    None,
255                    Some(format!("{}: backup failed: {e}", e.category())),
256                );
257            }
258            match writer::atomic_write(path, &new_bytes) {
259                Ok(()) => b.done(
260                    Some(tag),
261                    "converted",
262                    Some(sz),
263                    Some(new_bytes.len() as u64),
264                    None,
265                ),
266                Err(e) => b.done(
267                    Some(tag),
268                    "error",
269                    Some(sz),
270                    None,
271                    Some(format!("{}: write failed: {e}", e.category())),
272                ),
273            }
274        }
275    }
276}
277
278/// Verify a file is UTF-8 without BOM. Unreadable / oversized files fail
279/// closed (a gate must not wave through what it cannot inspect). The size is
280/// re-checked after the read, mirroring the other processors, so a file that
281/// grows between stat and read cannot slip past the cap.
282pub fn verify_file(path: &Path, max_file_size: u64) -> FileRecord {
283    let b = RecBuilder::new(path);
284    let size = fs::metadata(path).map(|m| m.len()).ok();
285    if let Some(sz) = size
286        && sz > max_file_size
287    {
288        return b.done(
289            None,
290            "failed",
291            Some(sz),
292            None,
293            Some("too_large: exceeds --max-file-size".to_string()),
294        );
295    }
296    let bytes = match read_file_limited(path, max_file_size) {
297        Ok(bytes) => bytes,
298        Err(e) => return b.done(None, "failed", size, None, Some(format!("io_error: {e}"))),
299    };
300    let sz = bytes.len() as u64;
301    if sz > max_file_size {
302        return b.done(
303            None,
304            "failed",
305            Some(sz),
306            None,
307            Some("too_large: exceeds --max-file-size".to_string()),
308        );
309    }
310    let det = detect(&bytes);
311    let tag = det.tag();
312    if det == DetectedEncoding::Utf8 {
313        b.done(Some(tag), "passed", Some(sz), None, None)
314    } else {
315        b.done(Some(tag), "failed", Some(sz), None, None)
316    }
317}
318
319// ---------------------------------------------------------------------------
320// Report assembly
321// ---------------------------------------------------------------------------
322
323/// Run-level facts that flow into the report document unchanged.
324struct RunFacts {
325    root: Option<std::path::PathBuf>,
326    url: Option<String>,
327    options: OptionsBlock,
328    started_at: String,
329    verify_failed: Option<Vec<String>>,
330    warnings: Vec<String>,
331}
332
333/// Sort records by path (reports stay reproducible run to run), compute the
334/// mode-specific summary, and assemble the final report document.
335fn finalize_report(
336    mode: &'static str,
337    facts: RunFacts,
338    mut records: Vec<FileRecord>,
339    elapsed: std::time::Duration,
340) -> Report {
341    records.sort_by(|a, b| a.path.cmp(&b.path));
342    let total = records.len() as u64;
343
344    let summary = match mode {
345        "scan" => {
346            let mut s = ScanSummary {
347                total_files: total,
348                ..ScanSummary::default()
349            };
350            for r in &records {
351                if r.action == "skipped_too_large" {
352                    s.too_large += 1;
353                }
354                if r.action == "error" {
355                    s.errors += 1;
356                }
357                match r.detected {
358                    Some("utf-8") => s.utf8 += 1,
359                    Some("utf-8-bom") => s.utf8_bom += 1,
360                    Some("utf-16le") => s.utf16le += 1,
361                    Some("utf-16be") => s.utf16be += 1,
362                    Some("utf-32le") => s.utf32le += 1,
363                    Some("utf-32be") => s.utf32be += 1,
364                    Some("gb18030") => s.gb18030 += 1,
365                    Some("unknown") => s.unknown += 1,
366                    _ => {}
367                }
368            }
369            s.candidates = total - s.too_large;
370            Summary::Scan(s)
371        }
372        "verify" => {
373            let passed = records.iter().filter(|r| r.action == "passed").count() as u64;
374            let failed = records.iter().filter(|r| r.action == "failed").count() as u64;
375            Summary::Verify(VerifySummary {
376                total_files: total,
377                candidates: total,
378                passed,
379                failed,
380            })
381        }
382        "fix" => {
383            let mut s = FixSummary {
384                total_files: total,
385                ..FixSummary::default()
386            };
387            for r in &records {
388                if r.action == "skipped_too_large" {
389                    s.too_large += 1;
390                }
391                match r.action {
392                    "unchanged" => s.already_utf8 += 1,
393                    "converted" | "would_convert" => s.converted += 1,
394                    "skipped_unknown" => s.unknown += 1,
395                    "error" => {
396                        let msg = r.error.as_deref().unwrap_or("");
397                        if msg.starts_with("decode_error") {
398                            s.decode_errors += 1;
399                        } else if msg.starts_with("encode_error") {
400                            s.encode_errors += 1;
401                        } else {
402                            s.io_errors += 1;
403                        }
404                    }
405                    _ => {}
406                }
407            }
408            s.candidates = total - s.too_large;
409            Summary::Fix(s)
410        }
411        _ => {
412            let mut s = ConvertSummary {
413                total_files: total,
414                ..ConvertSummary::default()
415            };
416            for r in &records {
417                match r.action {
418                    "unchanged" => s.already_utf8 += 1,
419                    "converted" | "would_convert" => s.converted += 1,
420                    "skipped_unknown" => s.unknown += 1,
421                    "skipped_too_large" => s.too_large += 1,
422                    "error" => {
423                        let msg = r.error.as_deref().unwrap_or("");
424                        if msg.starts_with("decode_error") {
425                            s.decode_errors += 1;
426                        } else if msg.starts_with("encode_error") {
427                            s.encode_errors += 1;
428                        } else if msg.starts_with("fetch_error") {
429                            s.fetch_error += 1;
430                        } else {
431                            s.io_errors += 1;
432                        }
433                    }
434                    _ => {}
435                }
436            }
437            s.candidates = total - s.too_large;
438            Summary::Convert(s)
439        }
440    };
441
442    let unknown_files: Vec<String> = records
443        .iter()
444        .filter(|r| r.action == "skipped_unknown" || r.detected == Some("unknown"))
445        .map(|r| r.path.clone())
446        .collect();
447    let error_files: Vec<String> = records
448        .iter()
449        .filter(|r| r.action == "error" || r.action == "failed")
450        .map(|r| r.path.clone())
451        .collect();
452    // Fix mode's verify gate; empty (and omitted) in every other mode.
453
454    Report {
455        tool: "utf8-forge",
456        version: env!("CARGO_PKG_VERSION"),
457        mode,
458        root: facts.root.map(|p| p.to_string_lossy().into_owned()),
459        url: facts.url,
460        started_at: facts.started_at,
461        duration_ms: elapsed.as_millis() as u64,
462        options: facts.options,
463        summary,
464        files: records,
465        unknown_files,
466        error_files,
467        verify_failed_files: facts.verify_failed.unwrap_or_default(),
468        warnings: facts.warnings,
469    }
470}
471
472/// Snapshot of effective options for the report's `options` block.
473/// Conversion-only fields are taken from `conv` (absent in scan/verify).
474fn options_block(
475    args: &TreeArgs,
476    conv: Option<&dyn ConvertOptions>,
477    filter: &FilterConfig,
478    config_file: Option<&str>,
479    ignore_file: Option<&str>,
480) -> OptionsBlock {
481    let mut extensions: Vec<String> = filter.extensions.iter().cloned().collect();
482    extensions.sort();
483    let mut exclude_dirs: Vec<String> = filter.exclude_dirs.iter().cloned().collect();
484    exclude_dirs.sort();
485    let mut exclude_ext: Vec<String> = args.exclude_ext.clone();
486    exclude_ext.sort();
487    OptionsBlock {
488        target: conv.map(|c| c.effective_target()).unwrap_or("utf-8"),
489        dry_run: conv.is_some_and(|c| c.is_dry_run()),
490        extensions,
491        exclude_dirs,
492        exclude_ext,
493        exclude_globs: args.exclude_glob.clone(),
494        backup_dir: conv.and_then(|c| c.backup_dir().map(|p| p.to_string_lossy().into_owned())),
495        config_file: config_file.map(str::to_string),
496        ignore_file: ignore_file.map(str::to_string),
497    }
498}
499
500// ---------------------------------------------------------------------------
501// Console output
502// ---------------------------------------------------------------------------
503
504/// Print problem lines (stderr, always) and verbose detail lines (stdout, -v).
505///
506/// `target_tag` is the destination encoding shown in converted /
507/// would_convert lines (convert/fetch modes); `None` for scan/verify whose
508/// verbose lines carry no target.
509fn print_records(records: &[FileRecord], console: ConsoleCfg, target_tag: Option<&'static str>) {
510    for r in records {
511        match r.action {
512            "error" => print_problem(format!(
513                "error {} ({})",
514                r.path,
515                r.error.as_deref().unwrap_or("unspecified")
516            )),
517            "skipped_unknown" => print_problem(format!("unknown {}", r.path)),
518            // Scan records unknown files as `detected` with the `unknown` tag;
519            // they are still per-file issues (scan exits 1) and get the same
520            // stderr line as `skipped_unknown` in the other modes.
521            "detected" if r.detected == Some("unknown") => {
522                print_problem(format!("unknown {}", r.path))
523            }
524            "failed" => {
525                let reason = r
526                    .error
527                    .clone()
528                    .unwrap_or_else(|| format!("detected={}", r.detected.unwrap_or("?")));
529                print_problem(format!("failed {} ({reason})", r.path));
530            }
531            _ => {}
532        }
533        match r.action {
534            // Unknown files already got their stderr problem line; the
535            // verbose classification line would repeat it verbatim under -v.
536            "detected" if r.detected != Some("unknown") => {
537                print_verbose(console, format!("{} {}", r.detected.unwrap_or("?"), r.path))
538            }
539            "unchanged" => print_verbose(
540                console,
541                format!("unchanged {} ({})", r.path, r.detected.unwrap_or("?")),
542            ),
543            "converted" | "would_convert" => print_verbose(
544                console,
545                format!(
546                    "{} {} ({} → {}, {} → {} bytes)",
547                    r.action,
548                    r.path,
549                    r.detected.unwrap_or("?"),
550                    target_tag.unwrap_or("?"),
551                    r.bytes_before.unwrap_or(0),
552                    r.bytes_after.unwrap_or(0)
553                ),
554            ),
555            "skipped_too_large" => print_verbose(
556                console,
557                format!(
558                    "skipped_too_large {} ({} bytes)",
559                    r.path,
560                    r.bytes_before.unwrap_or(0)
561                ),
562            ),
563            "passed" => print_verbose(console, format!("passed {}", r.path)),
564            _ => {}
565        }
566    }
567}
568
569/// Final duration (+ report path) line.
570fn print_duration(report: Option<&Path>, elapsed: std::time::Duration, console: ConsoleCfg) {
571    if console.quiet {
572        return;
573    }
574    match report {
575        Some(p) => println!(
576            "[utf8-forge] duration={:.1}s  report={}",
577            elapsed.as_secs_f64(),
578            p.display()
579        ),
580        None => println!("[utf8-forge] duration={:.1}s", elapsed.as_secs_f64()),
581    }
582}
583
584/// `convert` / `fetch` console summary.
585fn print_convert_summary(
586    s: &ConvertSummary,
587    report: Option<&Path>,
588    elapsed: std::time::Duration,
589    console: ConsoleCfg,
590) {
591    if !console.quiet {
592        println!(
593            "[utf8-forge] scanned={}  candidates={}",
594            s.total_files, s.candidates
595        );
596        let errors = s.decode_errors + s.encode_errors + s.io_errors;
597        println!(
598            "[utf8-forge] already_utf8={}  converted={}  unknown={}  errors={}",
599            s.already_utf8, s.converted, s.unknown, errors
600        );
601        if s.too_large > 0 {
602            println!("[utf8-forge] too_large={}", s.too_large);
603        }
604        if s.fetch_error > 0 {
605            println!("[utf8-forge] fetch_error={}", s.fetch_error);
606        }
607    }
608    print_duration(report, elapsed, console);
609}
610
611/// `scan` console summary (encoding distribution).
612fn print_scan_summary(
613    s: &ScanSummary,
614    report: Option<&Path>,
615    elapsed: std::time::Duration,
616    console: ConsoleCfg,
617) {
618    if !console.quiet {
619        println!(
620            "[utf8-forge] scanned={}  candidates={}",
621            s.total_files, s.candidates
622        );
623        println!(
624            "[utf8-forge] utf8={}  utf8_bom={}  utf16le={}  utf16be={}  utf32le={}  utf32be={}  gb18030={}  unknown={}",
625            s.utf8, s.utf8_bom, s.utf16le, s.utf16be, s.utf32le, s.utf32be, s.gb18030, s.unknown
626        );
627        if s.errors > 0 {
628            println!("[utf8-forge] errors={}", s.errors);
629        }
630        if s.too_large > 0 {
631            println!("[utf8-forge] too_large={}", s.too_large);
632        }
633    }
634    print_duration(report, elapsed, console);
635}
636
637// ---------------------------------------------------------------------------
638// Shared helpers
639// ---------------------------------------------------------------------------
640
641/// Build the effective filter; conflicting flags / bad globs are fatal.
642fn build_filter(args: &TreeArgs) -> anyhow::Result<FilterConfig> {
643    let opts = FilterOptions {
644        ext_override: args.ext.clone(),
645        exclude_ext: args.exclude_ext.clone(),
646        exclude_dirs: args.exclude.clone(),
647        exclude_globs: args.exclude_glob.clone(),
648        include_rc: args.include_rc,
649        include_msbuild: args.include_msbuild,
650        include_hidden: args.include_hidden,
651    };
652    FilterConfig::build(&opts).map_err(anyhow::Error::msg)
653}
654
655/// Load the TOML config (no-op default when `--config` absent) and merge it
656/// into the shared tree args. CLI flags win over config values; lists replace
657/// across layers (never concatenate) so the effective whitelist stays
658/// auditable. Runs before any pre-flight so downstream `ensure_*` checks see
659/// resolved values. Returns the parsed config for conversion-option merging.
660fn merge_tree_config(
661    common: &mut TreeArgs,
662) -> anyhow::Result<(Option<String>, crate::config::ForgeConfig)> {
663    let Some(path) = common.config.clone() else {
664        return Ok((None, crate::config::ForgeConfig::default()));
665    };
666    let cfg = crate::config::load(&path)?;
667    if common.ext.is_empty()
668        && let Some(list) = &cfg.filter.extensions
669    {
670        // An explicitly empty whitelist would silently scan nothing — the
671        // same fatal-input rule as `--ext ""`.
672        if list.is_empty() {
673            bail!("config [filter].extensions is empty: no usable extensions");
674        }
675        common.ext = list.clone();
676    }
677    if common.exclude.is_empty() {
678        common.exclude = cfg.filter.exclude_dirs.clone();
679    }
680    if common.exclude_ext.is_empty() {
681        common.exclude_ext = cfg.filter.exclude_ext.clone();
682    }
683    if common.exclude_glob.is_empty() {
684        common.exclude_glob = cfg.filter.exclude_globs.clone();
685    }
686    common.include_rc |= cfg.filter.include_rc;
687    common.include_msbuild |= cfg.filter.include_msbuild;
688    common.include_hidden |= cfg.filter.include_hidden;
689    if common.max_file_size.is_none() {
690        common.max_file_size = cfg.options.max_file_size;
691    }
692    if common.threads.is_none() {
693        common.threads = cfg.options.threads;
694    }
695    // Validate `[convert].target` even in modes that ignore the section, so
696    // an invalid value is always a loud, key-naming error instead of being
697    // silently dropped by scan/verify.
698    cfg.target()?;
699    Ok((Some(path.to_string_lossy().into_owned()), cfg))
700}
701
702/// Conversion-option surface shared by `convert` and `fix`, so the
703/// `[convert]` config section merges identically into both.
704trait ConvertOptions {
705    fn common(&self) -> &TreeArgs;
706    fn common_mut(&mut self) -> &mut TreeArgs;
707    fn set_target(&mut self, t: Option<crate::transcoder::TargetEncoding>);
708    fn set_backup_dir(&mut self, p: Option<std::path::PathBuf>);
709    fn target(&self) -> Option<crate::transcoder::TargetEncoding>;
710    fn backup_dir(&self) -> Option<&std::path::PathBuf>;
711    fn is_dry_run(&self) -> bool;
712
713    /// The target tag after CLI/config merge (built-in default: utf-8).
714    fn effective_target(&self) -> &'static str {
715        self.target()
716            .unwrap_or(crate::transcoder::TargetEncoding::Utf8)
717            .tag()
718    }
719}
720
721impl ConvertOptions for ConvertArgs {
722    fn common(&self) -> &TreeArgs {
723        &self.common
724    }
725    fn target(&self) -> Option<crate::transcoder::TargetEncoding> {
726        self.target
727    }
728    fn common_mut(&mut self) -> &mut TreeArgs {
729        &mut self.common
730    }
731    fn set_target(&mut self, t: Option<crate::transcoder::TargetEncoding>) {
732        self.target = t;
733    }
734    fn set_backup_dir(&mut self, p: Option<std::path::PathBuf>) {
735        self.backup_dir = p;
736    }
737    fn backup_dir(&self) -> Option<&std::path::PathBuf> {
738        self.backup_dir.as_ref()
739    }
740    fn is_dry_run(&self) -> bool {
741        self.dry_run
742    }
743}
744
745impl ConvertOptions for FixArgs {
746    fn common(&self) -> &TreeArgs {
747        &self.common
748    }
749    fn target(&self) -> Option<crate::transcoder::TargetEncoding> {
750        self.target
751    }
752    fn common_mut(&mut self) -> &mut TreeArgs {
753        &mut self.common
754    }
755    fn set_target(&mut self, t: Option<crate::transcoder::TargetEncoding>) {
756        self.target = t;
757    }
758    fn set_backup_dir(&mut self, p: Option<std::path::PathBuf>) {
759        self.backup_dir = p;
760    }
761    fn backup_dir(&self) -> Option<&std::path::PathBuf> {
762        self.backup_dir.as_ref()
763    }
764    fn is_dry_run(&self) -> bool {
765        self.dry_run
766    }
767}
768
769/// Apply the tree merge plus the `[convert]` section (convert / fix).
770/// CLI flags win over config values; runs before any pre-flight. Both
771/// sections use the same parsed snapshot of the file.
772fn merge_convert_config(conv: &mut impl ConvertOptions) -> anyhow::Result<Option<String>> {
773    let (recorded, cfg) = merge_tree_config(conv.common_mut())?;
774    if conv.target().is_none()
775        && let Some(t) = cfg.target()?
776    {
777        conv.set_target(Some(t));
778    }
779    if conv.backup_dir().is_none()
780        && let Some(dir) = &cfg.convert.backup_dir
781    {
782        // An empty directory name is a fatal input error: it is not a usable
783        // target anywhere, and the CLI form rejects it the same way.
784        if dir.trim().is_empty() {
785            bail!("config [convert].backup_dir is empty: name a real directory");
786        }
787        conv.set_backup_dir(Some(std::path::PathBuf::from(dir)));
788    }
789    Ok(recorded)
790}
791
792/// Root must be an existing directory, else exit code 2.
793fn ensure_root(root: &Path) -> anyhow::Result<()> {
794    if !root.is_dir() {
795        bail!("root `{}` is not an existing directory", root.display());
796    }
797    Ok(())
798}
799
800/// Prepare the backup directory up front so a broken backup path aborts
801/// before any source file is touched. A backup dir **inside** `--root` is
802/// fatal: the next run would walk the backups and re-convert them, breaking
803/// idempotence (a second run would no longer be a no-op) and silently
804/// mutating the safety net. Placement is checked existence-independently
805/// (from the deepest existing ancestor) *before* anything is created, so a
806/// rejected configuration never leaves directories behind and a dry-run
807/// never blesses what the real run would reject.
808fn ensure_backup_dir(args: &impl ConvertOptions) -> anyhow::Result<()> {
809    let Some(dir) = args.backup_dir() else {
810        return Ok(());
811    };
812    let root_canonical = fs::canonicalize(&args.common().root)?;
813    check_backup_placement(dir, &root_canonical)?;
814    if args.is_dry_run() {
815        return Ok(());
816    }
817    fs::create_dir_all(dir)
818        .with_context(|| format!("cannot create backup dir {}", dir.display()))?;
819    ensure_writable_dir(dir)?;
820    Ok(())
821}
822
823/// Resolve `dir` to its would-be canonical path without requiring it to
824/// exist: canonicalize the deepest existing ancestor, then re-attach the
825/// non-existing tail. Fatal when the projected path lands inside `root`.
826fn check_backup_placement(dir: &Path, root_canonical: &Path) -> anyhow::Result<()> {
827    // A relative dir such as `backup` targets a location under the process
828    // cwd; resolve it first so the ancestor walk starts from an existing
829    // base instead of failing on a not-yet-created relative tail.
830    let dir = if dir.is_absolute() {
831        dir.to_path_buf()
832    } else {
833        std::env::current_dir()
834            .with_context(|| format!("cannot resolve relative --backup-dir `{}`", dir.display()))?
835            .join(dir)
836    };
837    let mut tail: Vec<std::ffi::OsString> = Vec::new();
838    let mut ancestor = dir.to_path_buf();
839    let base = loop {
840        match fs::canonicalize(&ancestor) {
841            Ok(c) => break c,
842            Err(_) => {
843                let Some(name) = ancestor.file_name() else {
844                    bail!("--backup-dir `{}` has no existing ancestor", dir.display());
845                };
846                let Some(parent) = ancestor.parent() else {
847                    bail!("--backup-dir `{}` has no existing ancestor", dir.display());
848                };
849                tail.push(name.to_os_string());
850                ancestor = parent.to_path_buf();
851            }
852        }
853    };
854    let projected = tail.iter().rev().fold(base, |p, c| p.join(c));
855    if projected.starts_with(root_canonical) {
856        bail!(
857            "--backup-dir `{}` is inside `--root` `{}`; backups would be re-processed on the next run. Keep the backup directory outside the scanned tree.",
858            dir.display(),
859            root_canonical.display()
860        );
861    }
862    Ok(())
863}
864
865/// Pre-flight the report path so an unwritable report aborts (exit 2) before
866/// any file is converted, and collect the canonical report path for
867/// traversal exclusion (`--report` inside the tree must not pollute later
868/// runs). A bare filename (no directory component) is probed against the
869/// current directory. An existing write-protected report file is refused:
870/// rename would silently bypass its permission bits (and re-stamp the new
871/// report read-only), but the operator locked that file on purpose.
872fn ensure_report_dir(report: &Path) -> anyhow::Result<()> {
873    if report.is_dir() {
874        bail!("--report `{}` is an existing directory", report.display());
875    }
876    if let Ok(meta) = fs::metadata(report)
877        && meta.permissions().readonly()
878    {
879        bail!(
880            "--report `{}` is write-protected (read-only); chmod +w to replace it",
881            report.display()
882        );
883    }
884    let parent = match report.parent() {
885        Some(p) if !p.as_os_str().is_empty() => p.to_path_buf(),
886        _ => std::path::PathBuf::from("."),
887    };
888    fs::create_dir_all(&parent)
889        .with_context(|| format!("cannot create report directory {}", parent.display()))?;
890    // create_dir_all is a no-op on an existing directory regardless of
891    // permissions — probe writability so an existing read-only report
892    // directory also aborts before the tree is touched.
893    ensure_writable_dir(&parent)?;
894    Ok(())
895}
896
897/// Refuse a report target that would overwrite the active ignore rule file —
898/// the operator's filters must never be replaced by report JSON.
899fn ensure_report_not_ignore(report: Option<&Path>, ignore: Option<&str>) -> anyhow::Result<()> {
900    if let (Some(report), Some(ignore)) = (report, ignore)
901        && report == std::path::Path::new(ignore)
902    {
903        bail!(
904            "--report `{}` would overwrite the ignore file; pick another report path",
905            report.display()
906        );
907    }
908    Ok(())
909}
910
911/// Verify `dir` accepts new files by creating and immediately removing a
912/// unique probe file. Catches read-only directories that `create_dir_all`
913/// silently accepts because they already exist.
914fn ensure_writable_dir(dir: &Path) -> anyhow::Result<()> {
915    let nanos = std::time::SystemTime::now()
916        .duration_since(std::time::UNIX_EPOCH)
917        .map(|d| d.as_nanos())
918        .unwrap_or(0);
919    let probe = dir.join(format!(
920        ".utf8-forge-probe-{}-{}",
921        std::process::id(),
922        nanos
923    ));
924    match fs::File::create(&probe) {
925        Ok(_) => {
926            let _ = fs::remove_file(&probe);
927            Ok(())
928        }
929        Err(e) => bail!("directory `{}` is not writable: {e}", dir.display()),
930    }
931}
932
933/// Traversal skip list: the report path and the ignore file (so neither is
934/// ever scanned as content) — canonicalized downstream by `collect_files`.
935fn skip_paths(report: Option<&Path>, ignore: Option<&Path>) -> Vec<PathBuf> {
936    let mut v = Vec::new();
937    if let Some(p) = report {
938        v.push(p.to_path_buf());
939    }
940    if let Some(p) = ignore {
941        v.push(p.to_path_buf());
942    }
943    v
944}
945
946/// Resolve + load ignore rules per the flag precedence: `--no-ignore-file`
947/// disables everything; an explicit `--ignore-file` is fatal when missing;
948/// auto-discovery of `<root>/.utf8forgeignore` is silent when absent and a
949/// warning when unreadable. Returns the rules plus the path to record in the
950/// report (None = no ignore layer active).
951fn load_ignore(
952    args: &TreeArgs,
953) -> anyhow::Result<(Option<ignorefile::IgnoreFile>, Option<String>, Vec<String>)> {
954    if args.no_ignore_file {
955        return Ok((None, None, Vec::new()));
956    }
957    match &args.ignore_file {
958        Some(path) => {
959            if !path.is_file() {
960                bail!("ignore file `{}` not found", path.display());
961            }
962            let rules = ignorefile::IgnoreFile::load(path).map_err(anyhow::Error::msg)?;
963            let recorded = path.to_string_lossy().into_owned();
964            Ok((Some(rules), Some(recorded), Vec::new()))
965        }
966        None => {
967            let path = args.root.join(".utf8forgeignore");
968            if !path.is_file() {
969                return Ok((None, None, Vec::new()));
970            }
971            match ignorefile::IgnoreFile::load(&path) {
972                Ok(rules) => {
973                    let recorded = path.to_string_lossy().into_owned();
974                    Ok((Some(rules), Some(recorded), Vec::new()))
975                }
976                Err(e) => Ok((
977                    None,
978                    None,
979                    vec![format!(
980                        "warning: ignoring unreadable .utf8forgeignore: {e}"
981                    )],
982                )),
983            }
984        }
985    }
986}
987
988/// RFC 3339 timestamp captured when per-file processing begins (the
989/// traversal is excluded), so `started_at` + `duration_ms` line up.
990fn wall_now() -> String {
991    crate::reporter::rfc3339_now()
992}
993
994/// Upper bound for `--threads`: rayon pool startup cost grows quadratically,
995/// and implausible values silently wedge the process for minutes of pure CPU.
996/// Anything beyond 1024 hardware threads is not a real request, so it is a
997/// fatal input error (symmetric with the loud-strict-input posture).
998const MAX_THREADS: usize = 1024;
999
1000/// Validate the configured thread count, in every mode that accepts the flag
1001/// (fetch builds no pool but still refuses implausible values up front).
1002fn ensure_thread_bound(threads: Option<usize>) -> anyhow::Result<()> {
1003    match threads {
1004        Some(n) if n > MAX_THREADS => bail!(
1005            "--threads {n} exceeds the maximum of {MAX_THREADS}; build a smaller pool instead"
1006        ),
1007        _ => Ok(()),
1008    }
1009}
1010
1011/// Run `f` on the configured rayon pool (default pool when `--threads` unset).
1012fn with_pool<R: Send>(threads: Option<usize>, f: impl FnOnce() -> R + Send) -> anyhow::Result<R> {
1013    ensure_thread_bound(threads)?;
1014    match threads {
1015        Some(n) => {
1016            let pool = rayon::ThreadPoolBuilder::new()
1017                .num_threads(n.max(1))
1018                .build()
1019                .context("failed to build rayon thread pool")?;
1020            Ok(pool.install(f))
1021        }
1022        None => Ok(f()),
1023    }
1024}
1025
1026fn console_cfg(args: &TreeArgs) -> ConsoleCfg {
1027    ConsoleCfg {
1028        quiet: args.quiet,
1029        verbose: args.verbose,
1030    }
1031}
1032
1033/// Print non-fatal traversal warnings (suppressed by `--quiet`).
1034fn print_warnings(warnings: &[String], console: ConsoleCfg) {
1035    if !console.quiet {
1036        for w in warnings {
1037            print_problem(w.clone());
1038        }
1039    }
1040}
1041
1042// ---------------------------------------------------------------------------
1043// Subcommands
1044// ---------------------------------------------------------------------------
1045
1046/// `scan`: detect only, no writes. Exit 1 when any file is `unknown` or
1047/// errored (I/O), matching the documented per-file issue contract.
1048fn cmd_scan(args: &TreeArgs) -> anyhow::Result<i32> {
1049    let mut args = args.clone();
1050    let (config_file, _) = merge_tree_config(&mut args)?;
1051    ensure_root(&args.root)?;
1052    let filter = build_filter(&args)?;
1053    if let Some(path) = &args.report {
1054        ensure_report_dir(path)?;
1055    }
1056    let console = console_cfg(&args);
1057    print_header(console, format!("mode=scan root={}", args.root.display()));
1058
1059    let (ignore, ignore_recorded, ignore_warnings) = load_ignore(&args)?;
1060    ensure_report_not_ignore(args.report.as_deref(), ignore_recorded.as_deref())?;
1061    let mut warnings = Vec::new();
1062    let walk = {
1063        let skip = skip_paths(
1064            args.report.as_deref(),
1065            ignore_recorded
1066                .as_deref()
1067                .map(std::path::PathBuf::from)
1068                .as_deref(),
1069        );
1070        let walk = collect_files(&args.root, &filter, &skip, ignore.as_ref());
1071        warnings.extend(ignore_warnings);
1072        walk
1073    };
1074    warnings.extend(walk.warnings);
1075    print_warnings(&warnings, console);
1076    let started_at = wall_now();
1077    let started = Instant::now();
1078    let records = with_pool(args.threads, || {
1079        walk.files
1080            .par_iter()
1081            .map(|p| scan_file(p, args.effective_max_file_size()))
1082            .collect::<Vec<_>>()
1083    })?;
1084    print_records(&records, console, None);
1085    let elapsed = started.elapsed();
1086
1087    let report = finalize_report(
1088        "scan",
1089        RunFacts {
1090            root: Some(args.root.clone()),
1091            url: None,
1092            options: options_block(
1093                &args,
1094                None,
1095                &filter,
1096                config_file.as_deref(),
1097                ignore_recorded.as_deref(),
1098            ),
1099            started_at,
1100            verify_failed: None,
1101            warnings,
1102        },
1103        records,
1104        elapsed,
1105    );
1106    let unknown = match &report.summary {
1107        Summary::Scan(s) => s.unknown,
1108        _ => 0,
1109    };
1110    // Per-file I/O failures also count as issues: the tree was not fully
1111    // inventoried, so "all classified" would be a lie.
1112    let file_errors = report.files.iter().filter(|r| r.action == "error").count() as u64;
1113    if let Some(path) = &args.report {
1114        write_report(&report, path)?;
1115    }
1116    if let Summary::Scan(s) = &report.summary {
1117        print_scan_summary(s, args.report.as_deref(), elapsed, console);
1118    }
1119    Ok(if unknown > 0 || file_errors > 0 { 1 } else { 0 })
1120}
1121
1122/// `convert`: tree mode or remote fetch.
1123fn cmd_convert(args: &ConvertArgs) -> anyhow::Result<i32> {
1124    #[cfg(feature = "remote")]
1125    {
1126        if let Some(url) = &args.url {
1127            return cmd_convert_url(args, url);
1128        }
1129    }
1130    #[cfg(not(feature = "remote"))]
1131    {
1132        if args.url.is_some() {
1133            bail!("--url requires the `remote` feature; rebuild with default features");
1134        }
1135    }
1136    cmd_convert_tree(args)
1137}
1138
1139/// `convert` tree mode: detect + transcode + atomic write. Exit 1 when any
1140/// per-file issue (`unknown` / decode / io) remains.
1141fn cmd_convert_tree(args: &ConvertArgs) -> anyhow::Result<i32> {
1142    let mut args = args.clone();
1143    let config_file = merge_convert_config(&mut args)?;
1144    let common = &args.common;
1145    let target = args.target_or_default();
1146    ensure_root(&common.root)?;
1147    let filter = build_filter(common)?;
1148    // The report pre-flight is side-effect-free, so it runs before the backup
1149    // directory is created — a rejected report path must not leave a fresh
1150    // backup dir behind.
1151    if let Some(path) = &common.report {
1152        ensure_report_dir(path)?;
1153    }
1154    ensure_backup_dir(&args)?;
1155    let console = console_cfg(common);
1156    let dry_tag = if args.dry_run { " dry_run=true" } else { "" };
1157    print_header(
1158        console,
1159        format!(
1160            "mode=convert target={} root={}{}",
1161            target,
1162            common.root.display(),
1163            dry_tag
1164        ),
1165    );
1166
1167    let (ignore, ignore_recorded, ignore_warnings) = load_ignore(common)?;
1168    ensure_report_not_ignore(common.report.as_deref(), ignore_recorded.as_deref())?;
1169    // Ignore-layer problems stay advisory: a dropped ignore file only
1170    // widens the walk, so the quiet contract applies to them.
1171    print_warnings(&ignore_warnings, console);
1172    let mut warnings = ignore_warnings;
1173    let walk = {
1174        let skip = skip_paths(
1175            common.report.as_deref(),
1176            ignore_recorded
1177                .as_deref()
1178                .map(std::path::PathBuf::from)
1179                .as_deref(),
1180        );
1181        collect_files(&common.root, &filter, &skip, ignore.as_ref())
1182    };
1183    let walk_warning_count = walk.warnings.len();
1184    warnings.extend(walk.warnings);
1185    // Ignore-layer problems were already printed right after load_ignore;
1186    // only the traversal warnings belong to this line.
1187    print_warnings(&warnings[warnings.len() - walk_warning_count..], console);
1188    let ctx = ConvertCtx {
1189        root: common.root.clone(),
1190        target,
1191        dry_run: args.dry_run,
1192        backup_dir: args.backup_dir.clone(),
1193        max_file_size: common.effective_max_file_size(),
1194    };
1195    let started_at = wall_now();
1196    let started = Instant::now();
1197    let records = with_pool(common.threads, || {
1198        walk.files
1199            .par_iter()
1200            .map(|p| convert_file(p, &ctx))
1201            .collect::<Vec<_>>()
1202    })?;
1203    print_records(&records, console, Some(target.tag()));
1204    let elapsed = started.elapsed();
1205
1206    let report = finalize_report(
1207        "convert",
1208        RunFacts {
1209            root: Some(common.root.clone()),
1210            url: None,
1211            options: options_block(
1212                common,
1213                Some(&args as &dyn ConvertOptions),
1214                &filter,
1215                config_file.as_deref(),
1216                ignore_recorded.as_deref(),
1217            ),
1218            started_at,
1219            verify_failed: None,
1220            warnings,
1221        },
1222        records,
1223        elapsed,
1224    );
1225    let summary = match &report.summary {
1226        Summary::Convert(s) => s.clone(),
1227        _ => ConvertSummary::default(),
1228    };
1229    if let Some(path) = &common.report {
1230        write_report(&report, path)?;
1231    }
1232    print_convert_summary(&summary, common.report.as_deref(), elapsed, console);
1233    Ok(
1234        if summary.unknown > 0
1235            || summary.decode_errors > 0
1236            || summary.encode_errors > 0
1237            || summary.io_errors > 0
1238        {
1239            1
1240        } else {
1241            0
1242        },
1243    )
1244}
1245
1246/// `verify`: assert all whitelisted files are UTF-8 without BOM.
1247/// Exit 0 on success, 3 on any failure.
1248fn cmd_verify(args: &TreeArgs) -> anyhow::Result<i32> {
1249    let mut args = args.clone();
1250    let (config_file, _) = merge_tree_config(&mut args)?;
1251    ensure_root(&args.root)?;
1252    let filter = build_filter(&args)?;
1253    if let Some(path) = &args.report {
1254        ensure_report_dir(path)?;
1255    }
1256    let console = console_cfg(&args);
1257    print_header(console, format!("mode=verify root={}", args.root.display()));
1258
1259    let (ignore, ignore_recorded, ignore_warnings) = load_ignore(&args)?;
1260    ensure_report_not_ignore(args.report.as_deref(), ignore_recorded.as_deref())?;
1261    // Ignore-layer problems stay advisory: a dropped ignore file only
1262    // widens the walk, so the quiet contract applies to them.
1263    print_warnings(&ignore_warnings, console);
1264    let mut warnings = Vec::new();
1265    let walk = {
1266        let skip = skip_paths(
1267            args.report.as_deref(),
1268            ignore_recorded
1269                .as_deref()
1270                .map(std::path::PathBuf::from)
1271                .as_deref(),
1272        );
1273        let walk = collect_files(&args.root, &filter, &skip, ignore.as_ref());
1274        warnings.extend(ignore_warnings);
1275        walk
1276    };
1277    let gate_warned = !walk.warnings.is_empty();
1278    warnings.extend(walk.warnings);
1279    // A gate must not wave through what it could not inspect: only traversal
1280    // warnings (an uninspectable subtree) fail the gate, and they are shown
1281    // even under --quiet.
1282    for w in warnings.iter().skip(warnings.len() - gate_warned as usize) {
1283        print_problem(w.clone());
1284    }
1285    let started_at = wall_now();
1286    let started = Instant::now();
1287    let records = with_pool(args.threads, || {
1288        walk.files
1289            .par_iter()
1290            .map(|p| verify_file(p, args.effective_max_file_size()))
1291            .collect::<Vec<_>>()
1292    })?;
1293    print_records(&records, console, None);
1294    let elapsed = started.elapsed();
1295
1296    let report = finalize_report(
1297        "verify",
1298        RunFacts {
1299            root: Some(args.root.clone()),
1300            url: None,
1301            options: options_block(
1302                &args,
1303                None,
1304                &filter,
1305                config_file.as_deref(),
1306                ignore_recorded.as_deref(),
1307            ),
1308            started_at,
1309            verify_failed: None,
1310            warnings,
1311        },
1312        records,
1313        elapsed,
1314    );
1315    let summary = match &report.summary {
1316        Summary::Verify(s) => s.clone(),
1317        _ => VerifySummary::default(),
1318    };
1319    if let Some(path) = &args.report {
1320        write_report(&report, path)?;
1321    }
1322    if !console.quiet {
1323        println!(
1324            "[utf8-forge] checked={}  passed={}  failed={}",
1325            summary.total_files, summary.passed, summary.failed
1326        );
1327    }
1328    print_duration(args.report.as_deref(), elapsed, console);
1329    Ok(if summary.failed > 0 || gate_warned {
1330        3
1331    } else {
1332        0
1333    })
1334}
1335
1336/// `convert --url`: fetch → detect → transcode → save.
1337///
1338/// The transcode result is always materialized unless the destination already
1339/// holds the identical bytes — in that case the record is `unchanged` and no
1340/// write happens (same no-churn contract as tree mode; a
1341/// missing destination is still written, so downloads always materialize).
1342/// Exit 1 on fetch/decode/unknown/too-large issues; the report is still
1343/// written for post-mortem.
1344#[cfg(feature = "remote")]
1345fn cmd_convert_url(args: &ConvertArgs, url: &str) -> anyhow::Result<i32> {
1346    let common = &args.common;
1347    if args.backup_dir.is_some() {
1348        bail!("--backup-dir is not supported with --url");
1349    }
1350    // Fetch reads no config file: the only mergeable key ([convert].target)
1351    // would silently change nothing here, so combining them is refused.
1352    if common.config.is_some() {
1353        bail!("--config is not supported with --url");
1354    }
1355    // Fetch builds no rayon pool (a single file), but the same implausible
1356    // thread counts the tree modes reject are refused here too.
1357    ensure_thread_bound(common.threads)?;
1358    // Same report pre-flight as the tree modes: an unwritable report aborts
1359    // before the download, so no output is produced for a run that cannot be
1360    // audited.
1361    if let Some(path) = &common.report {
1362        ensure_report_dir(path)?;
1363    }
1364    let console = console_cfg(common);
1365    print_header(
1366        console,
1367        format!("mode=fetch target={} url={url}", args.target_or_default()),
1368    );
1369    let started_at = wall_now();
1370    let started = Instant::now();
1371    let out_path = args
1372        .output
1373        .clone()
1374        .unwrap_or_else(|| fetcher::derive_output_path(url));
1375
1376    let record = match fetcher::fetch_bytes(url, common.effective_max_file_size()) {
1377        Err(e) => {
1378            // An oversized payload is the documented `too_large` bucket; any
1379            // other fetch failure is a generic error row. The console line
1380            // must match the report action.
1381            let action = match e {
1382                ForgeError::TooLarge { .. } => "skipped_too_large",
1383                _ => "error",
1384            };
1385            // The oversized bucket keeps its immediate console line (its
1386            // report action has no problem print); generic errors are printed
1387            // exactly once, by `print_records`, against the output path.
1388            if action == "skipped_too_large" {
1389                print_problem(format!("skipped_too_large {url} ({}: {e})", e.category()));
1390            }
1391            RecBuilder::new(&out_path).done(
1392                None,
1393                action,
1394                None,
1395                None,
1396                Some(format!("{}: {e}", e.category())),
1397            )
1398        }
1399        Ok(bytes) => {
1400            let raw_len = bytes.len() as u64;
1401            let det = detect(&bytes);
1402            let tag = det.tag();
1403            match transcode_detected(&bytes, det, args.target_or_default()) {
1404                Err(ForgeError::UnknownEncoding) => {
1405                    // Same verdict as tree mode for identical bytes: recorded
1406                    // as `skipped_unknown` (summary `unknown` bucket,
1407                    // `unknown_files` list), printed once by `print_records`.
1408                    RecBuilder::new(&out_path).done(
1409                        Some(tag),
1410                        "skipped_unknown",
1411                        Some(raw_len),
1412                        None,
1413                        None,
1414                    )
1415                }
1416                Err(e) => {
1417                    // Printed exactly once, by `print_records`, against the
1418                    // output path — the same single-line contract as the
1419                    // generic fetch-error branch.
1420                    RecBuilder::new(&out_path).done(
1421                        Some(tag),
1422                        "error",
1423                        Some(raw_len),
1424                        None,
1425                        Some(format!("{}: {e}", e.category())),
1426                    )
1427                }
1428                Ok(outcome) => {
1429                    let new_bytes = match outcome {
1430                        TranscodeOutcome::Unchanged => bytes,
1431                        TranscodeOutcome::Changed(v) => v,
1432                    };
1433                    // Destination already holds the identical bytes → same
1434                    // no-churn contract as tree mode: `unchanged`, no write.
1435                    if read_file_limited(&out_path, new_bytes.len() as u64)
1436                        .is_ok_and(|existing| existing == new_bytes)
1437                    {
1438                        RecBuilder::new(&out_path).done(
1439                            Some(tag),
1440                            "unchanged",
1441                            Some(raw_len),
1442                            Some(new_bytes.len() as u64),
1443                            None,
1444                        )
1445                    } else if args.dry_run {
1446                        RecBuilder::new(&out_path).done(
1447                            Some(tag),
1448                            "would_convert",
1449                            Some(raw_len),
1450                            Some(new_bytes.len() as u64),
1451                            None,
1452                        )
1453                    } else {
1454                        // Same refusal as tree mode: POSIX rename would
1455                        // silently bypass the permission bits, but the
1456                        // operator locked that file on purpose.
1457                        let write_protected = fs::metadata(&out_path)
1458                            .map(|m| m.permissions().readonly())
1459                            .unwrap_or(false);
1460                        if write_protected {
1461                            RecBuilder::new(&out_path).done(
1462                                Some(tag),
1463                                "error",
1464                                Some(raw_len),
1465                                None,
1466                                Some(
1467                                    "io_error: file is write-protected (read-only); chmod +w to convert"
1468                                        .into(),
1469                                ),
1470                            )
1471                        } else {
1472                            if let Some(parent) = out_path.parent()
1473                                && !parent.as_os_str().is_empty()
1474                            {
1475                                fs::create_dir_all(parent).with_context(|| {
1476                                    format!("cannot create output dir {}", parent.display())
1477                                })?;
1478                            }
1479                            match writer::atomic_write(&out_path, &new_bytes) {
1480                                Ok(()) => RecBuilder::new(&out_path).done(
1481                                    Some(tag),
1482                                    "converted",
1483                                    Some(raw_len),
1484                                    Some(new_bytes.len() as u64),
1485                                    None,
1486                                ),
1487                                Err(e) => RecBuilder::new(&out_path).done(
1488                                    Some(tag),
1489                                    "error",
1490                                    Some(raw_len),
1491                                    None,
1492                                    Some(format!("{}: write failed: {e}", e.category())),
1493                                ),
1494                            }
1495                        }
1496                    }
1497                }
1498            }
1499        }
1500    };
1501    let elapsed = started.elapsed();
1502
1503    let options = OptionsBlock {
1504        target: args.target_or_default().tag(),
1505        dry_run: args.dry_run,
1506        extensions: Vec::new(),
1507        exclude_dirs: Vec::new(),
1508        exclude_ext: Vec::new(),
1509        exclude_globs: Vec::new(),
1510        backup_dir: None,
1511        config_file: None,
1512        ignore_file: None,
1513    };
1514    let report = finalize_report(
1515        "fetch",
1516        RunFacts {
1517            root: None,
1518            url: Some(url.to_string()),
1519            options,
1520            started_at,
1521            verify_failed: None,
1522            warnings: Vec::new(),
1523        },
1524        vec![record],
1525        elapsed,
1526    );
1527    let summary = match &report.summary {
1528        Summary::Convert(s) => s.clone(),
1529        _ => ConvertSummary::default(),
1530    };
1531    print_records(&report.files, console, Some(args.target_or_default().tag()));
1532    if let Some(path) = &common.report {
1533        write_report(&report, path)?;
1534    }
1535    print_convert_summary(&summary, common.report.as_deref(), elapsed, console);
1536    // Unlike tree mode, an oversized payload fails the run: the single file
1537    // the user asked to save was not written.
1538    Ok(
1539        if summary.unknown > 0
1540            || summary.decode_errors > 0
1541            || summary.encode_errors > 0
1542            || summary.io_errors > 0
1543            || summary.fetch_error > 0
1544            || summary.too_large > 0
1545        {
1546            1
1547        } else {
1548            0
1549        },
1550    )
1551}
1552
1553// ---------------------------------------------------------------------------
1554// fix / diff subcommands
1555// ---------------------------------------------------------------------------
1556
1557/// `fix`: convert + verify in one pass over a single traversal.
1558///
1559/// Exit code describes the END state of the tree — the gate wins: `3` when
1560/// any file fails the verify pass (unknown files, oversized files, and I/O
1561/// errors all fail closed), else `1` for convert-side issues, else `0`.
1562/// With `--dry-run` the convert pass writes nothing but the verify pass still
1563/// runs read-only, so the preview reports the tree's current end state.
1564fn cmd_fix(args: &FixArgs) -> anyhow::Result<i32> {
1565    let mut args = args.clone();
1566    let config_file = merge_convert_config(&mut args)?;
1567    let common = &args.common;
1568    let target = args.target_or_default();
1569    // The verify gate asserts UTF-8 without BOM no matter what the convert
1570    // pass targeted, so any other target would guarantee exit 3 while having
1571    // rewritten the tree into a state the gate itself rejects. Refuse it up
1572    // front, covering both the CLI flag and the config file.
1573    if target != TargetEncoding::Utf8 {
1574        bail!(
1575            "fix requires --target utf-8 (the verify gate asserts UTF-8 without BOM); got `{}`",
1576            target
1577        );
1578    }
1579    ensure_root(&common.root)?;
1580    let filter = build_filter(common)?;
1581    // Same ordering as convert: probe the report path before creating the
1582    // backup directory, so a rejected report leaves nothing behind.
1583    if let Some(path) = &common.report {
1584        ensure_report_dir(path)?;
1585    }
1586    ensure_backup_dir(&args)?;
1587    let console = console_cfg(common);
1588    let dry_tag = if args.dry_run { " dry_run=true" } else { "" };
1589    print_header(
1590        console,
1591        format!(
1592            "mode=fix target={} root={}{}",
1593            target,
1594            common.root.display(),
1595            dry_tag
1596        ),
1597    );
1598
1599    let (ignore, ignore_recorded, ignore_warnings) = load_ignore(common)?;
1600    ensure_report_not_ignore(common.report.as_deref(), ignore_recorded.as_deref())?;
1601    // Ignore-layer problems stay advisory: a dropped ignore file only
1602    // widens the walk, so the quiet contract applies to them.
1603    print_warnings(&ignore_warnings, console);
1604    let mut warnings = ignore_warnings;
1605    let walk = {
1606        let skip = skip_paths(
1607            common.report.as_deref(),
1608            ignore_recorded.as_deref().map(PathBuf::from).as_deref(),
1609        );
1610        collect_files(&common.root, &filter, &skip, ignore.as_ref())
1611    };
1612    let gate_warned = !walk.warnings.is_empty();
1613    warnings.extend(walk.warnings);
1614    // Gate modes surface traversal problems even under --quiet: an
1615    // uninspectable subtree fails the gate below.
1616    for w in warnings.iter().skip(warnings.len() - gate_warned as usize) {
1617        print_problem(w.clone());
1618    }
1619
1620    let started_at = wall_now();
1621    let started = Instant::now();
1622    let ctx = ConvertCtx {
1623        root: common.root.clone(),
1624        target,
1625        dry_run: args.dry_run,
1626        backup_dir: args.backup_dir.clone(),
1627        max_file_size: common.effective_max_file_size(),
1628    };
1629    let convert_records = with_pool(common.threads, || {
1630        walk.files
1631            .par_iter()
1632            .map(|p| convert_file(p, &ctx))
1633            .collect::<Vec<_>>()
1634    })?;
1635    print_records(&convert_records, console, Some(target.tag()));
1636
1637    // Verify pass over the SAME traversal — no re-walk, so both passes see an
1638    // identical candidate list.
1639    let verify_records = with_pool(common.threads, || {
1640        walk.files
1641            .par_iter()
1642            .map(|p| verify_file(p, common.effective_max_file_size()))
1643            .collect::<Vec<_>>()
1644    })?;
1645    let mut verify_failed: Vec<String> = verify_records
1646        .iter()
1647        .filter(|r| r.action == "failed")
1648        .map(|r| r.path.clone())
1649        .collect();
1650    verify_failed.sort();
1651    for r in &verify_records {
1652        if r.action == "failed" {
1653            let reason = r
1654                .error
1655                .clone()
1656                .unwrap_or_else(|| format!("detected={}", r.detected.unwrap_or("?")));
1657            print_problem(format!("failed {} ({reason})", r.path));
1658        }
1659    }
1660    let elapsed = started.elapsed();
1661
1662    let mut report = finalize_report(
1663        "fix",
1664        RunFacts {
1665            root: Some(common.root.clone()),
1666            url: None,
1667            options: options_block(
1668                common,
1669                Some(&args as &dyn ConvertOptions),
1670                &filter,
1671                config_file.as_deref(),
1672                ignore_recorded.as_deref(),
1673            ),
1674            started_at,
1675            verify_failed: Some(verify_failed.clone()),
1676            warnings: warnings.clone(),
1677        },
1678        convert_records,
1679        elapsed,
1680    );
1681    // The verify pass counts ride on the fix summary; they are computed from
1682    // the gate records, not the convert records.
1683    let verify_failed_count = verify_failed.len() as u64;
1684    if let Summary::Fix(f) = &mut report.summary {
1685        f.passed = verify_records
1686            .iter()
1687            .filter(|r| r.action == "passed")
1688            .count() as u64;
1689        f.failed = verify_failed_count;
1690    }
1691    let convert_issues = match &report.summary {
1692        Summary::Fix(f) => f.unknown + f.decode_errors + f.encode_errors + f.io_errors,
1693        _ => 0,
1694    };
1695    if let Some(path) = &common.report {
1696        write_report(&report, path)?;
1697    }
1698    if let Summary::Fix(f) = &report.summary
1699        && !console.quiet
1700    {
1701        println!(
1702            "[utf8-forge] scanned={}  candidates={}",
1703            f.total_files, f.candidates
1704        );
1705        println!(
1706            "[utf8-forge] already_utf8={}  converted={}  unknown={}  errors={}",
1707            f.already_utf8,
1708            f.converted,
1709            f.unknown,
1710            f.decode_errors + f.encode_errors + f.io_errors
1711        );
1712        if f.too_large > 0 {
1713            println!("[utf8-forge] too_large={}", f.too_large);
1714        }
1715        println!(
1716            "[utf8-forge] verify: checked={}  passed={}  failed={}",
1717            f.passed + f.failed,
1718            f.passed,
1719            f.failed
1720        );
1721    }
1722    print_duration(common.report.as_deref(), elapsed, console);
1723    // Gate wins: the exit code describes the end state of the tree.
1724    Ok(if verify_failed_count > 0 || gate_warned {
1725        3
1726    } else if convert_issues > 0 {
1727        1
1728    } else {
1729        0
1730    })
1731}
1732
1733/// `diff`: compare two report JSONs per path. Inspection tool — exit 0 by
1734/// default even when differences exist; `--fail-on-change` turns a non-empty
1735/// diff into exit 1 for CI gates.
1736fn cmd_diff(args: &DiffArgs) -> anyhow::Result<i32> {
1737    let load = |p: &Path, flag: &str| -> anyhow::Result<DiffInput> {
1738        let text = fs::read_to_string(p)
1739            .with_context(|| format!("cannot load {flag} report `{}`", p.display()))?;
1740        serde_json::from_str(&text)
1741            .with_context(|| format!("cannot load {flag} report `{}`", p.display()))
1742    };
1743    let before_raw = load(&args.before, "--before")?;
1744    let after_raw = load(&args.after, "--after")?;
1745    if let (Some(r1), Some(r2)) = (&before_raw.root, &after_raw.root)
1746        && r1 != r2
1747    {
1748        print_problem(format!(
1749            "warning: roots differ (`{r1}` vs `{r2}`); paths are compared relative to each root"
1750        ));
1751    }
1752
1753    // Records are compared relative to each report's own root, so the same
1754    // tree scanned under two root directories diffs clean.
1755    let before = DiffInput {
1756        mode: before_raw.mode.clone(),
1757        root: before_raw.root.clone(),
1758        files: differ::relativize_files(before_raw.files, before_raw.root.as_deref()),
1759    };
1760    let after = DiffInput {
1761        mode: after_raw.mode.clone(),
1762        root: after_raw.root.clone(),
1763        files: differ::relativize_files(after_raw.files, after_raw.root.as_deref()),
1764    };
1765    let mut doc = differ::compare(&before, &after);
1766    doc.before = args.before.to_string_lossy().into_owned();
1767    doc.after = args.after.to_string_lossy().into_owned();
1768    let summary = &doc.summary;
1769
1770    // The summary line goes to stderr; stdout carries only the JSON document
1771    // (when no --report), so piping the diff into other tools stays clean.
1772    if let Some(path) = &args.report {
1773        ensure_report_dir(path)?;
1774        let json = serde_json::to_string_pretty(&doc).context("diff serialization failed")?;
1775        writer::atomic_write(path, (json + "\n").as_bytes())
1776            .with_context(|| format!("cannot write diff report {}", path.display()))?;
1777        eprintln!(
1778            "[utf8-forge] diff: added={}  removed={}  changed={}  unchanged={}  report={}",
1779            summary.added,
1780            summary.removed,
1781            summary.action_changed,
1782            summary.unchanged,
1783            path.display()
1784        );
1785    } else {
1786        eprintln!(
1787            "[utf8-forge] diff: added={}  removed={}  changed={}  unchanged={}",
1788            summary.added, summary.removed, summary.action_changed, summary.unchanged
1789        );
1790        let json = serde_json::to_string_pretty(&doc).context("diff serialization failed")?;
1791        println!("{json}");
1792    }
1793    let drifted = summary.added + summary.removed + summary.action_changed;
1794    Ok(if args.fail_on_change && drifted > 0 {
1795        1
1796    } else {
1797        0
1798    })
1799}
1800
1801#[cfg(test)]
1802mod bounded_read_tests {
1803    use super::read_file_limited;
1804    use std::fs;
1805
1806    #[test]
1807    fn reads_only_cap_plus_one_bytes() {
1808        let dir = tempfile::tempdir().unwrap();
1809        let path = dir.path().join("growing.cpp");
1810        // Exercise the read independently of the stat pre-check, as when a
1811        // file grows between the pre-check and opening it.
1812        fs::write(&path, vec![b'x'; 65536]).unwrap();
1813        let bytes = read_file_limited(&path, 4096).unwrap();
1814        assert_eq!(bytes, vec![b'x'; 4097]);
1815        assert_eq!(read_file_limited(&path, 0).unwrap(), b"x");
1816    }
1817
1818    #[test]
1819    fn handles_exact_limit_empty_files_and_unlimited_size() {
1820        let dir = tempfile::tempdir().unwrap();
1821        let path = dir.path().join("a.cpp");
1822        fs::write(&path, b"abc").unwrap();
1823        assert_eq!(read_file_limited(&path, 3).unwrap(), b"abc");
1824        assert_eq!(read_file_limited(&path, u64::MAX).unwrap(), b"abc");
1825        fs::write(&path, b"").unwrap();
1826        assert!(read_file_limited(&path, 0).unwrap().is_empty());
1827        assert_eq!(
1828            read_file_limited(&dir.path().join("missing.cpp"), 3)
1829                .unwrap_err()
1830                .kind(),
1831            std::io::ErrorKind::NotFound
1832        );
1833    }
1834}
1835
1836#[cfg(test)]
1837mod backup_placement_tests {
1838    use super::check_backup_placement;
1839    use std::path::Path;
1840
1841    #[test]
1842    fn relative_backup_dir_resolves_against_cwd() {
1843        // The root argument must be canonicalized, exactly as the real
1844        // caller passes it: on Windows canonicalize yields a `\\?\`
1845        // verbatim prefix, so a plain current_dir() would never compare
1846        // equal to the projected path.
1847        let cwd = std::fs::canonicalize(std::env::current_dir().unwrap()).unwrap();
1848        // A not-yet-created relative dir lands under the cwd, outside a root
1849        // elsewhere.
1850        check_backup_placement(Path::new("backup"), &cwd.join("elsewhere-root")).unwrap();
1851        // Deep non-existing relative tails resolve through the cwd too.
1852        check_backup_placement(Path::new("a/b/c"), &cwd.join("elsewhere-root")).unwrap();
1853        // The same relative dir is fatal when the cwd itself is the root.
1854        let err = check_backup_placement(Path::new("backup"), &cwd).unwrap_err();
1855        assert!(err.to_string().contains("inside"), "{err}");
1856    }
1857}