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