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, resolvable directory, else exit code 2. The
793/// canonicalize check matters: traversal-exclusion and backup placement
794/// compare canonical paths, and a root that cannot be resolved (long-path or
795/// ACL edges on Windows, symlink loops) would silently disable those guards.
796fn ensure_root(root: &Path) -> anyhow::Result<()> {
797    if !root.is_dir() {
798        bail!("root `{}` is not an existing directory", root.display());
799    }
800    fs::canonicalize(root).with_context(|| {
801        format!(
802            "cannot resolve the canonical path of root `{}`",
803            root.display()
804        )
805    })?;
806    Ok(())
807}
808
809/// Prepare the backup directory up front so a broken backup path aborts
810/// before any source file is touched. A backup dir **inside** `--root` is
811/// fatal: the next run would walk the backups and re-convert them, breaking
812/// idempotence (a second run would no longer be a no-op) and silently
813/// mutating the safety net. Placement is checked existence-independently
814/// (from the deepest existing ancestor) *before* anything is created, so a
815/// rejected configuration never leaves directories behind and a dry-run
816/// never blesses what the real run would reject.
817fn ensure_backup_dir(args: &impl ConvertOptions) -> anyhow::Result<()> {
818    let Some(dir) = args.backup_dir() else {
819        return Ok(());
820    };
821    let root_canonical = fs::canonicalize(&args.common().root)?;
822    check_backup_placement(dir, &root_canonical)?;
823    if args.is_dry_run() {
824        return Ok(());
825    }
826    fs::create_dir_all(dir)
827        .with_context(|| format!("cannot create backup dir {}", dir.display()))?;
828    ensure_writable_dir(dir)?;
829    Ok(())
830}
831
832/// Resolve `dir` to its would-be canonical path without requiring it to
833/// exist: canonicalize the deepest existing ancestor, then re-attach the
834/// non-existing tail. Fatal when the projected path lands inside `root`.
835fn check_backup_placement(dir: &Path, root_canonical: &Path) -> anyhow::Result<()> {
836    // A relative dir such as `backup` targets a location under the process
837    // cwd; resolve it first so the ancestor walk starts from an existing
838    // base instead of failing on a not-yet-created relative tail.
839    let dir = if dir.is_absolute() {
840        dir.to_path_buf()
841    } else {
842        std::env::current_dir()
843            .with_context(|| format!("cannot resolve relative --backup-dir `{}`", dir.display()))?
844            .join(dir)
845    };
846    let mut tail: Vec<std::ffi::OsString> = Vec::new();
847    let mut ancestor = dir.to_path_buf();
848    let base = loop {
849        match fs::canonicalize(&ancestor) {
850            Ok(c) => break c,
851            Err(_) => {
852                let Some(name) = ancestor.file_name() else {
853                    bail!("--backup-dir `{}` has no existing ancestor", dir.display());
854                };
855                let Some(parent) = ancestor.parent() else {
856                    bail!("--backup-dir `{}` has no existing ancestor", dir.display());
857                };
858                tail.push(name.to_os_string());
859                ancestor = parent.to_path_buf();
860            }
861        }
862    };
863    let projected = tail.iter().rev().fold(base, |p, c| p.join(c));
864    if projected.starts_with(root_canonical) {
865        bail!(
866            "--backup-dir `{}` is inside `--root` `{}`; backups would be re-processed on the next run. Keep the backup directory outside the scanned tree.",
867            dir.display(),
868            root_canonical.display()
869        );
870    }
871    Ok(())
872}
873
874/// Pre-flight the report path so an unwritable report aborts (exit 2) before
875/// any file is converted, and collect the canonical report path for
876/// traversal exclusion (`--report` inside the tree must not pollute later
877/// runs). A bare filename (no directory component) is probed against the
878/// current directory. An existing write-protected report file is refused:
879/// rename would silently bypass its permission bits (and re-stamp the new
880/// report read-only), but the operator locked that file on purpose.
881fn ensure_report_dir(report: &Path) -> anyhow::Result<()> {
882    if report.is_dir() {
883        bail!("--report `{}` is an existing directory", report.display());
884    }
885    if let Ok(meta) = fs::metadata(report)
886        && meta.permissions().readonly()
887    {
888        bail!(
889            "--report `{}` is write-protected (read-only); chmod +w to replace it",
890            report.display()
891        );
892    }
893    let parent = match report.parent() {
894        Some(p) if !p.as_os_str().is_empty() => p.to_path_buf(),
895        _ => std::path::PathBuf::from("."),
896    };
897    fs::create_dir_all(&parent)
898        .with_context(|| format!("cannot create report directory {}", parent.display()))?;
899    // create_dir_all is a no-op on an existing directory regardless of
900    // permissions — probe writability so an existing read-only report
901    // directory also aborts before the tree is touched.
902    ensure_writable_dir(&parent)?;
903    Ok(())
904}
905
906/// Refuse a report target that would overwrite the active ignore rule file —
907/// the operator's filters must never be replaced by report JSON.
908fn ensure_report_not_ignore(report: Option<&Path>, ignore: Option<&str>) -> anyhow::Result<()> {
909    if let (Some(report), Some(ignore)) = (report, ignore)
910        && report == std::path::Path::new(ignore)
911    {
912        bail!(
913            "--report `{}` would overwrite the ignore file; pick another report path",
914            report.display()
915        );
916    }
917    Ok(())
918}
919
920/// Verify `dir` accepts new files by creating and immediately removing a
921/// unique probe file. Catches read-only directories that `create_dir_all`
922/// silently accepts because they already exist.
923fn ensure_writable_dir(dir: &Path) -> anyhow::Result<()> {
924    let nanos = std::time::SystemTime::now()
925        .duration_since(std::time::UNIX_EPOCH)
926        .map(|d| d.as_nanos())
927        .unwrap_or(0);
928    let probe = dir.join(format!(
929        ".utf8-forge-probe-{}-{}",
930        std::process::id(),
931        nanos
932    ));
933    match fs::File::create(&probe) {
934        Ok(_) => {
935            let _ = fs::remove_file(&probe);
936            Ok(())
937        }
938        Err(e) => bail!("directory `{}` is not writable: {e}", dir.display()),
939    }
940}
941
942/// Traversal skip list: the report path and the ignore file (so neither is
943/// ever scanned as content) — canonicalized downstream by `collect_files`.
944fn skip_paths(report: Option<&Path>, ignore: Option<&Path>) -> Vec<PathBuf> {
945    let mut v = Vec::new();
946    if let Some(p) = report {
947        v.push(p.to_path_buf());
948    }
949    if let Some(p) = ignore {
950        v.push(p.to_path_buf());
951    }
952    v
953}
954
955/// Resolve + load ignore rules per the flag precedence: `--no-ignore-file`
956/// disables everything; an explicit `--ignore-file` is fatal when missing;
957/// auto-discovery of `<root>/.utf8forgeignore` is silent when absent and a
958/// warning when unreadable. Returns the rules plus the path to record in the
959/// report (None = no ignore layer active).
960fn load_ignore(
961    args: &TreeArgs,
962) -> anyhow::Result<(Option<ignorefile::IgnoreFile>, Option<String>, Vec<String>)> {
963    if args.no_ignore_file {
964        return Ok((None, None, Vec::new()));
965    }
966    match &args.ignore_file {
967        Some(path) => {
968            if !path.is_file() {
969                bail!("ignore file `{}` not found", path.display());
970            }
971            let rules = ignorefile::IgnoreFile::load(path).map_err(anyhow::Error::msg)?;
972            let recorded = path.to_string_lossy().into_owned();
973            Ok((Some(rules), Some(recorded), Vec::new()))
974        }
975        None => {
976            let path = args.root.join(".utf8forgeignore");
977            if !path.is_file() {
978                return Ok((None, None, Vec::new()));
979            }
980            match ignorefile::IgnoreFile::load(&path) {
981                Ok(rules) => {
982                    let recorded = path.to_string_lossy().into_owned();
983                    Ok((Some(rules), Some(recorded), Vec::new()))
984                }
985                Err(e) => Ok((
986                    None,
987                    None,
988                    vec![format!(
989                        "warning: ignoring unreadable .utf8forgeignore: {e}"
990                    )],
991                )),
992            }
993        }
994    }
995}
996
997/// RFC 3339 timestamp captured when per-file processing begins (the
998/// traversal is excluded), so `started_at` + `duration_ms` line up.
999fn wall_now() -> String {
1000    crate::reporter::rfc3339_now()
1001}
1002
1003/// Upper bound for `--threads`: rayon pool startup cost grows quadratically,
1004/// and implausible values silently wedge the process for minutes of pure CPU.
1005/// Anything beyond 1024 hardware threads is not a real request, so it is a
1006/// fatal input error (symmetric with the loud-strict-input posture).
1007const MAX_THREADS: usize = 1024;
1008
1009/// Validate the configured thread count, in every mode that accepts the flag
1010/// (fetch builds no pool but still refuses implausible values up front).
1011fn ensure_thread_bound(threads: Option<usize>) -> anyhow::Result<()> {
1012    match threads {
1013        Some(n) if n > MAX_THREADS => bail!(
1014            "--threads {n} exceeds the maximum of {MAX_THREADS}; build a smaller pool instead"
1015        ),
1016        _ => Ok(()),
1017    }
1018}
1019
1020/// Run `f` on the configured rayon pool (default pool when `--threads` unset).
1021fn with_pool<R: Send>(threads: Option<usize>, f: impl FnOnce() -> R + Send) -> anyhow::Result<R> {
1022    ensure_thread_bound(threads)?;
1023    match threads {
1024        Some(n) => {
1025            let pool = rayon::ThreadPoolBuilder::new()
1026                .num_threads(n.max(1))
1027                .build()
1028                .context("failed to build rayon thread pool")?;
1029            Ok(pool.install(f))
1030        }
1031        None => Ok(f()),
1032    }
1033}
1034
1035fn console_cfg(args: &TreeArgs) -> ConsoleCfg {
1036    ConsoleCfg {
1037        quiet: args.quiet,
1038        verbose: args.verbose,
1039    }
1040}
1041
1042/// Print non-fatal traversal warnings (suppressed by `--quiet`).
1043fn print_warnings(warnings: &[String], console: ConsoleCfg) {
1044    if !console.quiet {
1045        for w in warnings {
1046            print_problem(w.clone());
1047        }
1048    }
1049}
1050
1051// ---------------------------------------------------------------------------
1052// Subcommands
1053// ---------------------------------------------------------------------------
1054
1055/// `scan`: detect only, no writes. Exit 1 when any file is `unknown` or
1056/// errored (I/O), matching the documented per-file issue contract.
1057fn cmd_scan(args: &TreeArgs) -> anyhow::Result<i32> {
1058    let mut args = args.clone();
1059    let (config_file, _) = merge_tree_config(&mut args)?;
1060    ensure_root(&args.root)?;
1061    let filter = build_filter(&args)?;
1062    if let Some(path) = &args.report {
1063        ensure_report_dir(path)?;
1064    }
1065    let console = console_cfg(&args);
1066    print_header(console, format!("mode=scan root={}", args.root.display()));
1067
1068    let (ignore, ignore_recorded, ignore_warnings) = load_ignore(&args)?;
1069    ensure_report_not_ignore(args.report.as_deref(), ignore_recorded.as_deref())?;
1070    let mut warnings = Vec::new();
1071    let walk = {
1072        let skip = skip_paths(
1073            args.report.as_deref(),
1074            ignore_recorded
1075                .as_deref()
1076                .map(std::path::PathBuf::from)
1077                .as_deref(),
1078        );
1079        let walk = collect_files(&args.root, &filter, &skip, ignore.as_ref());
1080        warnings.extend(ignore_warnings);
1081        walk
1082    };
1083    warnings.extend(walk.warnings);
1084    print_warnings(&warnings, console);
1085    let started_at = wall_now();
1086    let started = Instant::now();
1087    let records = with_pool(args.threads, || {
1088        walk.files
1089            .par_iter()
1090            .map(|p| scan_file(p, args.effective_max_file_size()))
1091            .collect::<Vec<_>>()
1092    })?;
1093    let elapsed = started.elapsed();
1094
1095    let report = finalize_report(
1096        "scan",
1097        RunFacts {
1098            root: Some(args.root.clone()),
1099            url: None,
1100            options: options_block(
1101                &args,
1102                None,
1103                &filter,
1104                config_file.as_deref(),
1105                ignore_recorded.as_deref(),
1106            ),
1107            started_at,
1108            verify_failed: None,
1109            warnings,
1110        },
1111        records,
1112        elapsed,
1113    );
1114    let unknown = match &report.summary {
1115        Summary::Scan(s) => s.unknown,
1116        _ => 0,
1117    };
1118    // Per-file I/O failures also count as issues: the tree was not fully
1119    // inventoried, so "all classified" would be a lie.
1120    let file_errors = report.files.iter().filter(|r| r.action == "error").count() as u64;
1121    if let Some(path) = &args.report {
1122        write_report(&report, path)?;
1123    }
1124    // The report is durable before any console output: a closed pipe
1125    // (`... | head`) can kill the process mid-print without losing it.
1126    print_records(&report.files, console, None);
1127    if let Summary::Scan(s) = &report.summary {
1128        print_scan_summary(s, args.report.as_deref(), elapsed, console);
1129    }
1130    Ok(if unknown > 0 || file_errors > 0 { 1 } else { 0 })
1131}
1132
1133/// `convert`: tree mode or remote fetch.
1134fn cmd_convert(args: &ConvertArgs) -> anyhow::Result<i32> {
1135    #[cfg(feature = "remote")]
1136    {
1137        if let Some(url) = &args.url {
1138            return cmd_convert_url(args, url);
1139        }
1140    }
1141    #[cfg(not(feature = "remote"))]
1142    {
1143        if args.url.is_some() {
1144            bail!("--url requires the `remote` feature; rebuild with default features");
1145        }
1146    }
1147    cmd_convert_tree(args)
1148}
1149
1150/// `convert` tree mode: detect + transcode + atomic write. Exit 1 when any
1151/// per-file issue (`unknown` / decode / io) remains.
1152fn cmd_convert_tree(args: &ConvertArgs) -> anyhow::Result<i32> {
1153    let mut args = args.clone();
1154    let config_file = merge_convert_config(&mut args)?;
1155    let common = &args.common;
1156    let target = args.target_or_default();
1157    ensure_root(&common.root)?;
1158    let filter = build_filter(common)?;
1159    // The report pre-flight is side-effect-free, so it runs before the backup
1160    // directory is created — a rejected report path must not leave a fresh
1161    // backup dir behind.
1162    if let Some(path) = &common.report {
1163        ensure_report_dir(path)?;
1164    }
1165    ensure_backup_dir(&args)?;
1166    let console = console_cfg(common);
1167    let dry_tag = if args.dry_run { " dry_run=true" } else { "" };
1168    print_header(
1169        console,
1170        format!(
1171            "mode=convert target={} root={}{}",
1172            target,
1173            common.root.display(),
1174            dry_tag
1175        ),
1176    );
1177
1178    let (ignore, ignore_recorded, ignore_warnings) = load_ignore(common)?;
1179    ensure_report_not_ignore(common.report.as_deref(), ignore_recorded.as_deref())?;
1180    // Ignore-layer problems stay advisory: a dropped ignore file only
1181    // widens the walk, so the quiet contract applies to them.
1182    print_warnings(&ignore_warnings, console);
1183    let mut warnings = ignore_warnings;
1184    let walk = {
1185        let skip = skip_paths(
1186            common.report.as_deref(),
1187            ignore_recorded
1188                .as_deref()
1189                .map(std::path::PathBuf::from)
1190                .as_deref(),
1191        );
1192        collect_files(&common.root, &filter, &skip, ignore.as_ref())
1193    };
1194    let walk_warning_count = walk.warnings.len();
1195    warnings.extend(walk.warnings);
1196    // Ignore-layer problems were already printed right after load_ignore;
1197    // only the traversal warnings belong to this line.
1198    print_warnings(&warnings[warnings.len() - walk_warning_count..], console);
1199    let ctx = ConvertCtx {
1200        root: common.root.clone(),
1201        target,
1202        dry_run: args.dry_run,
1203        backup_dir: args.backup_dir.clone(),
1204        max_file_size: common.effective_max_file_size(),
1205    };
1206    let started_at = wall_now();
1207    let started = Instant::now();
1208    let records = with_pool(common.threads, || {
1209        walk.files
1210            .par_iter()
1211            .map(|p| convert_file(p, &ctx))
1212            .collect::<Vec<_>>()
1213    })?;
1214    let elapsed = started.elapsed();
1215
1216    let report = finalize_report(
1217        "convert",
1218        RunFacts {
1219            root: Some(common.root.clone()),
1220            url: None,
1221            options: options_block(
1222                common,
1223                Some(&args as &dyn ConvertOptions),
1224                &filter,
1225                config_file.as_deref(),
1226                ignore_recorded.as_deref(),
1227            ),
1228            started_at,
1229            verify_failed: None,
1230            warnings,
1231        },
1232        records,
1233        elapsed,
1234    );
1235    let summary = match &report.summary {
1236        Summary::Convert(s) => s.clone(),
1237        _ => ConvertSummary::default(),
1238    };
1239    if let Some(path) = &common.report {
1240        write_report(&report, path)?;
1241    }
1242    // Report durable before console output (pipe-safe ordering).
1243    print_records(&report.files, console, Some(target.tag()));
1244    print_convert_summary(&summary, common.report.as_deref(), elapsed, console);
1245    Ok(
1246        if summary.unknown > 0
1247            || summary.decode_errors > 0
1248            || summary.encode_errors > 0
1249            || summary.io_errors > 0
1250        {
1251            1
1252        } else {
1253            0
1254        },
1255    )
1256}
1257
1258/// `verify`: assert all whitelisted files are UTF-8 without BOM.
1259/// Exit 0 on success, 3 on any failure.
1260fn cmd_verify(args: &TreeArgs) -> anyhow::Result<i32> {
1261    let mut args = args.clone();
1262    let (config_file, _) = merge_tree_config(&mut args)?;
1263    ensure_root(&args.root)?;
1264    let filter = build_filter(&args)?;
1265    if let Some(path) = &args.report {
1266        ensure_report_dir(path)?;
1267    }
1268    let console = console_cfg(&args);
1269    print_header(console, format!("mode=verify root={}", args.root.display()));
1270
1271    let (ignore, ignore_recorded, ignore_warnings) = load_ignore(&args)?;
1272    ensure_report_not_ignore(args.report.as_deref(), ignore_recorded.as_deref())?;
1273    // Ignore-layer problems stay advisory: a dropped ignore file only
1274    // widens the walk, so the quiet contract applies to them.
1275    print_warnings(&ignore_warnings, console);
1276    let mut warnings = Vec::new();
1277    let walk = {
1278        let skip = skip_paths(
1279            args.report.as_deref(),
1280            ignore_recorded
1281                .as_deref()
1282                .map(std::path::PathBuf::from)
1283                .as_deref(),
1284        );
1285        let walk = collect_files(&args.root, &filter, &skip, ignore.as_ref());
1286        warnings.extend(ignore_warnings);
1287        walk
1288    };
1289    let gate_warned = !walk.warnings.is_empty();
1290    warnings.extend(walk.warnings);
1291    // A gate must not wave through what it could not inspect: only traversal
1292    // warnings (an uninspectable subtree) fail the gate, and they are shown
1293    // even under --quiet.
1294    for w in warnings.iter().skip(warnings.len() - gate_warned as usize) {
1295        print_problem(w.clone());
1296    }
1297    let started_at = wall_now();
1298    let started = Instant::now();
1299    let records = with_pool(args.threads, || {
1300        walk.files
1301            .par_iter()
1302            .map(|p| verify_file(p, args.effective_max_file_size()))
1303            .collect::<Vec<_>>()
1304    })?;
1305    let elapsed = started.elapsed();
1306
1307    let report = finalize_report(
1308        "verify",
1309        RunFacts {
1310            root: Some(args.root.clone()),
1311            url: None,
1312            options: options_block(
1313                &args,
1314                None,
1315                &filter,
1316                config_file.as_deref(),
1317                ignore_recorded.as_deref(),
1318            ),
1319            started_at,
1320            verify_failed: None,
1321            warnings,
1322        },
1323        records,
1324        elapsed,
1325    );
1326    let summary = match &report.summary {
1327        Summary::Verify(s) => s.clone(),
1328        _ => VerifySummary::default(),
1329    };
1330    if let Some(path) = &args.report {
1331        write_report(&report, path)?;
1332    }
1333    // Report durable before console output (pipe-safe ordering).
1334    print_records(&report.files, console, None);
1335    if !console.quiet {
1336        println!(
1337            "[utf8-forge] checked={}  passed={}  failed={}",
1338            summary.total_files, summary.passed, summary.failed
1339        );
1340    }
1341    print_duration(args.report.as_deref(), elapsed, console);
1342    Ok(if summary.failed > 0 || gate_warned {
1343        3
1344    } else {
1345        0
1346    })
1347}
1348
1349/// `convert --url`: fetch → detect → transcode → save.
1350///
1351/// The transcode result is always materialized unless the destination already
1352/// holds the identical bytes — in that case the record is `unchanged` and no
1353/// write happens (same no-churn contract as tree mode; a
1354/// missing destination is still written, so downloads always materialize).
1355/// Exit 1 on fetch/decode/unknown/too-large issues; the report is still
1356/// written for post-mortem.
1357#[cfg(feature = "remote")]
1358fn cmd_convert_url(args: &ConvertArgs, url: &str) -> anyhow::Result<i32> {
1359    let common = &args.common;
1360    if args.backup_dir.is_some() {
1361        bail!("--backup-dir is not supported with --url");
1362    }
1363    // Fetch reads no config file: the only mergeable key ([convert].target)
1364    // would silently change nothing here, so combining them is refused.
1365    if common.config.is_some() {
1366        bail!("--config is not supported with --url");
1367    }
1368    // Fetch builds no rayon pool (a single file), but the same implausible
1369    // thread counts the tree modes reject are refused here too.
1370    ensure_thread_bound(common.threads)?;
1371    // Same report pre-flight as the tree modes: an unwritable report aborts
1372    // before the download, so no output is produced for a run that cannot be
1373    // audited.
1374    if let Some(path) = &common.report {
1375        ensure_report_dir(path)?;
1376    }
1377    let console = console_cfg(common);
1378    print_header(
1379        console,
1380        format!("mode=fetch target={} url={url}", args.target_or_default()),
1381    );
1382    let started_at = wall_now();
1383    let started = Instant::now();
1384    let out_path = args
1385        .output
1386        .clone()
1387        .unwrap_or_else(|| fetcher::derive_output_path(url));
1388
1389    let record = match fetcher::fetch_bytes(url, common.effective_max_file_size()) {
1390        Err(e) => {
1391            // An oversized payload is the documented `too_large` bucket; any
1392            // other fetch failure is a generic error row. The console line
1393            // must match the report action.
1394            let action = match e {
1395                ForgeError::TooLarge { .. } => "skipped_too_large",
1396                _ => "error",
1397            };
1398            // The oversized bucket keeps its immediate console line (its
1399            // report action has no problem print); generic errors are printed
1400            // exactly once, by `print_records`, against the output path.
1401            if action == "skipped_too_large" {
1402                print_problem(format!("skipped_too_large {url} ({}: {e})", e.category()));
1403            }
1404            RecBuilder::new(&out_path).done(
1405                None,
1406                action,
1407                None,
1408                None,
1409                Some(format!("{}: {e}", e.category())),
1410            )
1411        }
1412        Ok(bytes) => {
1413            let raw_len = bytes.len() as u64;
1414            let det = detect(&bytes);
1415            let tag = det.tag();
1416            match transcode_detected(&bytes, det, args.target_or_default()) {
1417                Err(ForgeError::UnknownEncoding) => {
1418                    // Same verdict as tree mode for identical bytes: recorded
1419                    // as `skipped_unknown` (summary `unknown` bucket,
1420                    // `unknown_files` list), printed once by `print_records`.
1421                    RecBuilder::new(&out_path).done(
1422                        Some(tag),
1423                        "skipped_unknown",
1424                        Some(raw_len),
1425                        None,
1426                        None,
1427                    )
1428                }
1429                Err(e) => {
1430                    // Printed exactly once, by `print_records`, against the
1431                    // output path — the same single-line contract as the
1432                    // generic fetch-error branch.
1433                    RecBuilder::new(&out_path).done(
1434                        Some(tag),
1435                        "error",
1436                        Some(raw_len),
1437                        None,
1438                        Some(format!("{}: {e}", e.category())),
1439                    )
1440                }
1441                Ok(outcome) => {
1442                    let new_bytes = match outcome {
1443                        TranscodeOutcome::Unchanged => bytes,
1444                        TranscodeOutcome::Changed(v) => v,
1445                    };
1446                    // Destination already holds the identical bytes → same
1447                    // no-churn contract as tree mode: `unchanged`, no write.
1448                    if read_file_limited(&out_path, new_bytes.len() as u64)
1449                        .is_ok_and(|existing| existing == new_bytes)
1450                    {
1451                        RecBuilder::new(&out_path).done(
1452                            Some(tag),
1453                            "unchanged",
1454                            Some(raw_len),
1455                            Some(new_bytes.len() as u64),
1456                            None,
1457                        )
1458                    } else if args.dry_run {
1459                        RecBuilder::new(&out_path).done(
1460                            Some(tag),
1461                            "would_convert",
1462                            Some(raw_len),
1463                            Some(new_bytes.len() as u64),
1464                            None,
1465                        )
1466                    } else {
1467                        // Same refusal as tree mode: POSIX rename would
1468                        // silently bypass the permission bits, but the
1469                        // operator locked that file on purpose.
1470                        let write_protected = fs::metadata(&out_path)
1471                            .map(|m| m.permissions().readonly())
1472                            .unwrap_or(false);
1473                        if write_protected {
1474                            RecBuilder::new(&out_path).done(
1475                                Some(tag),
1476                                "error",
1477                                Some(raw_len),
1478                                None,
1479                                Some(
1480                                    "io_error: file is write-protected (read-only); chmod +w to convert"
1481                                        .into(),
1482                                ),
1483                            )
1484                        } else {
1485                            if let Some(parent) = out_path.parent()
1486                                && !parent.as_os_str().is_empty()
1487                            {
1488                                fs::create_dir_all(parent).with_context(|| {
1489                                    format!("cannot create output dir {}", parent.display())
1490                                })?;
1491                            }
1492                            match writer::atomic_write(&out_path, &new_bytes) {
1493                                Ok(()) => RecBuilder::new(&out_path).done(
1494                                    Some(tag),
1495                                    "converted",
1496                                    Some(raw_len),
1497                                    Some(new_bytes.len() as u64),
1498                                    None,
1499                                ),
1500                                Err(e) => RecBuilder::new(&out_path).done(
1501                                    Some(tag),
1502                                    "error",
1503                                    Some(raw_len),
1504                                    None,
1505                                    Some(format!("{}: write failed: {e}", e.category())),
1506                                ),
1507                            }
1508                        }
1509                    }
1510                }
1511            }
1512        }
1513    };
1514    let elapsed = started.elapsed();
1515
1516    let options = OptionsBlock {
1517        target: args.target_or_default().tag(),
1518        dry_run: args.dry_run,
1519        extensions: Vec::new(),
1520        exclude_dirs: Vec::new(),
1521        exclude_ext: Vec::new(),
1522        exclude_globs: Vec::new(),
1523        backup_dir: None,
1524        config_file: None,
1525        ignore_file: None,
1526    };
1527    let report = finalize_report(
1528        "fetch",
1529        RunFacts {
1530            root: None,
1531            url: Some(url.to_string()),
1532            options,
1533            started_at,
1534            verify_failed: None,
1535            warnings: Vec::new(),
1536        },
1537        vec![record],
1538        elapsed,
1539    );
1540    let summary = match &report.summary {
1541        Summary::Convert(s) => s.clone(),
1542        _ => ConvertSummary::default(),
1543    };
1544    if let Some(path) = &common.report {
1545        write_report(&report, path)?;
1546    }
1547    // Report durable before console output (pipe-safe ordering).
1548    print_records(&report.files, console, Some(args.target_or_default().tag()));
1549    print_convert_summary(&summary, common.report.as_deref(), elapsed, console);
1550    // Unlike tree mode, an oversized payload fails the run: the single file
1551    // the user asked to save was not written.
1552    Ok(
1553        if summary.unknown > 0
1554            || summary.decode_errors > 0
1555            || summary.encode_errors > 0
1556            || summary.io_errors > 0
1557            || summary.fetch_error > 0
1558            || summary.too_large > 0
1559        {
1560            1
1561        } else {
1562            0
1563        },
1564    )
1565}
1566
1567// ---------------------------------------------------------------------------
1568// fix / diff subcommands
1569// ---------------------------------------------------------------------------
1570
1571/// `fix`: convert + verify in one pass over a single traversal.
1572///
1573/// Exit code describes the END state of the tree — the gate wins: `3` when
1574/// any file fails the verify pass (unknown files, oversized files, and I/O
1575/// errors all fail closed), else `1` for convert-side issues, else `0`.
1576/// With `--dry-run` the convert pass writes nothing but the verify pass still
1577/// runs read-only, so the preview reports the tree's current end state.
1578fn cmd_fix(args: &FixArgs) -> anyhow::Result<i32> {
1579    let mut args = args.clone();
1580    let config_file = merge_convert_config(&mut args)?;
1581    let common = &args.common;
1582    let target = args.target_or_default();
1583    // The verify gate asserts UTF-8 without BOM no matter what the convert
1584    // pass targeted, so any other target would guarantee exit 3 while having
1585    // rewritten the tree into a state the gate itself rejects. Refuse it up
1586    // front, covering both the CLI flag and the config file.
1587    if target != TargetEncoding::Utf8 {
1588        bail!(
1589            "fix requires --target utf-8 (the verify gate asserts UTF-8 without BOM); got `{}`",
1590            target
1591        );
1592    }
1593    ensure_root(&common.root)?;
1594    let filter = build_filter(common)?;
1595    // Same ordering as convert: probe the report path before creating the
1596    // backup directory, so a rejected report leaves nothing behind.
1597    if let Some(path) = &common.report {
1598        ensure_report_dir(path)?;
1599    }
1600    ensure_backup_dir(&args)?;
1601    let console = console_cfg(common);
1602    let dry_tag = if args.dry_run { " dry_run=true" } else { "" };
1603    print_header(
1604        console,
1605        format!(
1606            "mode=fix target={} root={}{}",
1607            target,
1608            common.root.display(),
1609            dry_tag
1610        ),
1611    );
1612
1613    let (ignore, ignore_recorded, ignore_warnings) = load_ignore(common)?;
1614    ensure_report_not_ignore(common.report.as_deref(), ignore_recorded.as_deref())?;
1615    // Ignore-layer problems stay advisory: a dropped ignore file only
1616    // widens the walk, so the quiet contract applies to them.
1617    print_warnings(&ignore_warnings, console);
1618    let mut warnings = ignore_warnings;
1619    let walk = {
1620        let skip = skip_paths(
1621            common.report.as_deref(),
1622            ignore_recorded.as_deref().map(PathBuf::from).as_deref(),
1623        );
1624        collect_files(&common.root, &filter, &skip, ignore.as_ref())
1625    };
1626    let gate_warned = !walk.warnings.is_empty();
1627    warnings.extend(walk.warnings);
1628    // Gate modes surface traversal problems even under --quiet: an
1629    // uninspectable subtree fails the gate below.
1630    for w in warnings.iter().skip(warnings.len() - gate_warned as usize) {
1631        print_problem(w.clone());
1632    }
1633
1634    let started_at = wall_now();
1635    let started = Instant::now();
1636    let ctx = ConvertCtx {
1637        root: common.root.clone(),
1638        target,
1639        dry_run: args.dry_run,
1640        backup_dir: args.backup_dir.clone(),
1641        max_file_size: common.effective_max_file_size(),
1642    };
1643    let convert_records = with_pool(common.threads, || {
1644        walk.files
1645            .par_iter()
1646            .map(|p| convert_file(p, &ctx))
1647            .collect::<Vec<_>>()
1648    })?;
1649
1650    // Verify pass over the SAME traversal — no re-walk, so both passes see an
1651    // identical candidate list.
1652    let verify_records = with_pool(common.threads, || {
1653        walk.files
1654            .par_iter()
1655            .map(|p| verify_file(p, common.effective_max_file_size()))
1656            .collect::<Vec<_>>()
1657    })?;
1658    let mut verify_failed: Vec<String> = verify_records
1659        .iter()
1660        .filter(|r| r.action == "failed")
1661        .map(|r| r.path.clone())
1662        .collect();
1663    verify_failed.sort();
1664    for r in &verify_records {
1665        if r.action == "failed" {
1666            let reason = r
1667                .error
1668                .clone()
1669                .unwrap_or_else(|| format!("detected={}", r.detected.unwrap_or("?")));
1670            print_problem(format!("failed {} ({reason})", r.path));
1671        }
1672    }
1673    let elapsed = started.elapsed();
1674
1675    let mut report = finalize_report(
1676        "fix",
1677        RunFacts {
1678            root: Some(common.root.clone()),
1679            url: None,
1680            options: options_block(
1681                common,
1682                Some(&args as &dyn ConvertOptions),
1683                &filter,
1684                config_file.as_deref(),
1685                ignore_recorded.as_deref(),
1686            ),
1687            started_at,
1688            verify_failed: Some(verify_failed.clone()),
1689            warnings: warnings.clone(),
1690        },
1691        convert_records,
1692        elapsed,
1693    );
1694    // The verify pass counts ride on the fix summary; they are computed from
1695    // the gate records, not the convert records.
1696    let verify_failed_count = verify_failed.len() as u64;
1697    if let Summary::Fix(f) = &mut report.summary {
1698        f.passed = verify_records
1699            .iter()
1700            .filter(|r| r.action == "passed")
1701            .count() as u64;
1702        f.failed = verify_failed_count;
1703    }
1704    let convert_issues = match &report.summary {
1705        Summary::Fix(f) => f.unknown + f.decode_errors + f.encode_errors + f.io_errors,
1706        _ => 0,
1707    };
1708    if let Some(path) = &common.report {
1709        write_report(&report, path)?;
1710    }
1711    // Report durable before console output (pipe-safe ordering). The fix
1712    // summary already carries the gate lines; per-file convert rows print
1713    // here alongside them.
1714    print_records(&report.files, console, Some(target.tag()));
1715    if let Summary::Fix(f) = &report.summary
1716        && !console.quiet
1717    {
1718        println!(
1719            "[utf8-forge] scanned={}  candidates={}",
1720            f.total_files, f.candidates
1721        );
1722        println!(
1723            "[utf8-forge] already_utf8={}  converted={}  unknown={}  errors={}",
1724            f.already_utf8,
1725            f.converted,
1726            f.unknown,
1727            f.decode_errors + f.encode_errors + f.io_errors
1728        );
1729        if f.too_large > 0 {
1730            println!("[utf8-forge] too_large={}", f.too_large);
1731        }
1732        println!(
1733            "[utf8-forge] verify: checked={}  passed={}  failed={}",
1734            f.passed + f.failed,
1735            f.passed,
1736            f.failed
1737        );
1738    }
1739    print_duration(common.report.as_deref(), elapsed, console);
1740    // Gate wins: the exit code describes the end state of the tree.
1741    Ok(if verify_failed_count > 0 || gate_warned {
1742        3
1743    } else if convert_issues > 0 {
1744        1
1745    } else {
1746        0
1747    })
1748}
1749
1750/// `diff`: compare two report JSONs per path. Inspection tool — exit 0 by
1751/// default even when differences exist; `--fail-on-change` turns a non-empty
1752/// diff into exit 1 for CI gates.
1753fn cmd_diff(args: &DiffArgs) -> anyhow::Result<i32> {
1754    let load = |p: &Path, flag: &str| -> anyhow::Result<DiffInput> {
1755        let text = fs::read_to_string(p)
1756            .with_context(|| format!("cannot load {flag} report `{}`", p.display()))?;
1757        serde_json::from_str(&text)
1758            .with_context(|| format!("cannot load {flag} report `{}`", p.display()))
1759    };
1760    let before_raw = load(&args.before, "--before")?;
1761    let after_raw = load(&args.after, "--after")?;
1762    if let (Some(r1), Some(r2)) = (&before_raw.root, &after_raw.root)
1763        && r1 != r2
1764    {
1765        print_problem(format!(
1766            "warning: roots differ (`{r1}` vs `{r2}`); paths are compared relative to each root"
1767        ));
1768    }
1769
1770    // Records are compared relative to each report's own root, so the same
1771    // tree scanned under two root directories diffs clean.
1772    let before = DiffInput {
1773        mode: before_raw.mode.clone(),
1774        root: before_raw.root.clone(),
1775        files: differ::relativize_files(before_raw.files, before_raw.root.as_deref()),
1776    };
1777    let after = DiffInput {
1778        mode: after_raw.mode.clone(),
1779        root: after_raw.root.clone(),
1780        files: differ::relativize_files(after_raw.files, after_raw.root.as_deref()),
1781    };
1782    let mut doc = differ::compare(&before, &after);
1783    doc.before = args.before.to_string_lossy().into_owned();
1784    doc.after = args.after.to_string_lossy().into_owned();
1785    let summary = &doc.summary;
1786
1787    // The summary line goes to stderr; stdout carries only the JSON document
1788    // (when no --report), so piping the diff into other tools stays clean.
1789    if let Some(path) = &args.report {
1790        ensure_report_dir(path)?;
1791        let json = serde_json::to_string_pretty(&doc).context("diff serialization failed")?;
1792        writer::atomic_write(path, (json + "\n").as_bytes())
1793            .with_context(|| format!("cannot write diff report {}", path.display()))?;
1794        eprintln!(
1795            "[utf8-forge] diff: added={}  removed={}  changed={}  unchanged={}  report={}",
1796            summary.added,
1797            summary.removed,
1798            summary.action_changed,
1799            summary.unchanged,
1800            path.display()
1801        );
1802    } else {
1803        eprintln!(
1804            "[utf8-forge] diff: added={}  removed={}  changed={}  unchanged={}",
1805            summary.added, summary.removed, summary.action_changed, summary.unchanged
1806        );
1807        let json = serde_json::to_string_pretty(&doc).context("diff serialization failed")?;
1808        println!("{json}");
1809    }
1810    let drifted = summary.added + summary.removed + summary.action_changed;
1811    Ok(if args.fail_on_change && drifted > 0 {
1812        1
1813    } else {
1814        0
1815    })
1816}
1817
1818#[cfg(test)]
1819mod bounded_read_tests {
1820    use super::read_file_limited;
1821    use std::fs;
1822
1823    #[test]
1824    fn reads_only_cap_plus_one_bytes() {
1825        let dir = tempfile::tempdir().unwrap();
1826        let path = dir.path().join("growing.cpp");
1827        // Exercise the read independently of the stat pre-check, as when a
1828        // file grows between the pre-check and opening it.
1829        fs::write(&path, vec![b'x'; 65536]).unwrap();
1830        let bytes = read_file_limited(&path, 4096).unwrap();
1831        assert_eq!(bytes, vec![b'x'; 4097]);
1832        assert_eq!(read_file_limited(&path, 0).unwrap(), b"x");
1833    }
1834
1835    #[test]
1836    fn handles_exact_limit_empty_files_and_unlimited_size() {
1837        let dir = tempfile::tempdir().unwrap();
1838        let path = dir.path().join("a.cpp");
1839        fs::write(&path, b"abc").unwrap();
1840        assert_eq!(read_file_limited(&path, 3).unwrap(), b"abc");
1841        assert_eq!(read_file_limited(&path, u64::MAX).unwrap(), b"abc");
1842        fs::write(&path, b"").unwrap();
1843        assert!(read_file_limited(&path, 0).unwrap().is_empty());
1844        assert_eq!(
1845            read_file_limited(&dir.path().join("missing.cpp"), 3)
1846                .unwrap_err()
1847                .kind(),
1848            std::io::ErrorKind::NotFound
1849        );
1850    }
1851}
1852
1853#[cfg(test)]
1854mod backup_placement_tests {
1855    use super::check_backup_placement;
1856    use std::path::Path;
1857
1858    #[test]
1859    fn relative_backup_dir_resolves_against_cwd() {
1860        // The root argument must be canonicalized, exactly as the real
1861        // caller passes it: on Windows canonicalize yields a `\\?\`
1862        // verbatim prefix, so a plain current_dir() would never compare
1863        // equal to the projected path.
1864        let cwd = std::fs::canonicalize(std::env::current_dir().unwrap()).unwrap();
1865        // A not-yet-created relative dir lands under the cwd, outside a root
1866        // elsewhere.
1867        check_backup_placement(Path::new("backup"), &cwd.join("elsewhere-root")).unwrap();
1868        // Deep non-existing relative tails resolve through the cwd too.
1869        check_backup_placement(Path::new("a/b/c"), &cwd.join("elsewhere-root")).unwrap();
1870        // The same relative dir is fatal when the cwd itself is the root.
1871        let err = check_backup_placement(Path::new("backup"), &cwd).unwrap_err();
1872        assert!(err.to_string().contains("inside"), "{err}");
1873    }
1874}