utf8-forge 0.1.0

A focused, idempotent, bidirectional charset transcoder for source trees. Default output: UTF-8 without BOM.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
//! utf8-forge orchestration: per-file pipelines, report assembly, and the
//! `run()` entry point with exit-code mapping.
//!
//! Exit codes (`docs/USAGE.md §7`):
//! - `0` success
//! - `1` non-fatal per-file issues (`unknown`, `decode_error`, `io_error`,
//!   `fetch_error`)
//! - `2` fatal (bad args, missing root, I/O setup failure) — also emitted by
//!   clap on parse errors
//! - `3` `verify` found non-UTF-8 whitelisted files

// Public modules (lib target so integration tests can exercise the
// pipeline directly; the binary in `main.rs` stays a thin wrapper).
pub mod cli;
pub mod detector;
pub mod error;
#[cfg(feature = "remote")]
pub mod fetcher;
pub mod filter;
pub mod reporter;
pub mod transcoder;
pub mod walker;
pub mod writer;

use std::fs;
use std::path::Path;
use std::time::Instant;

use anyhow::{Context, bail};
use rayon::prelude::*;

use crate::cli::{Cli, Commands, ConvertArgs, TreeArgs};
use crate::detector::{DetectedEncoding, detect};
use crate::error::ForgeError;
use crate::filter::{FilterConfig, FilterOptions};
use crate::reporter::{
    ConsoleCfg, ConvertSummary, FileRecord, OptionsBlock, Report, ScanSummary, Summary,
    VerifySummary, print_header, print_problem, print_verbose, write_report,
};
use crate::transcoder::{TargetEncoding, TranscodeOutcome, transcode_detected};
use crate::walker::collect_files;

/// Dispatch a parsed CLI and map the outcome to a process exit code.
/// Fatal setup errors print to stderr and yield exit code 2.
pub fn run(cli: Cli) -> i32 {
    let outcome = match cli.command {
        Commands::Scan(args) => cmd_scan(&args),
        Commands::Convert(args) => cmd_convert(&args),
        Commands::Verify(args) => cmd_verify(&args),
    };
    outcome.unwrap_or_else(|err| {
        eprintln!("[utf8-forge] fatal: {err:#}");
        2
    })
}

// ---------------------------------------------------------------------------
// Per-file processors
// ---------------------------------------------------------------------------

/// Deferred `FileRecord` builder that stamps per-file duration at completion.
struct RecBuilder<'a> {
    path: &'a Path,
    started: Instant,
}

impl<'a> RecBuilder<'a> {
    fn new(path: &'a Path) -> RecBuilder<'a> {
        RecBuilder {
            path,
            started: Instant::now(),
        }
    }

    fn done(
        self,
        detected: Option<&'static str>,
        action: &'static str,
        bytes_before: Option<u64>,
        bytes_after: Option<u64>,
        error: Option<String>,
    ) -> FileRecord {
        FileRecord {
            path: self.path.to_string_lossy().into_owned(),
            detected,
            action,
            bytes_before,
            bytes_after,
            duration_us: self.started.elapsed().as_micros() as u64,
            error,
        }
    }
}

/// Detect only. Oversized files are never read.
pub fn scan_file(path: &Path, max_file_size: u64) -> FileRecord {
    let b = RecBuilder::new(path);
    let size = fs::metadata(path).map(|m| m.len()).ok();
    if let Some(sz) = size {
        if sz > max_file_size {
            return b.done(None, "skipped_too_large", Some(sz), None, None);
        }
    }
    let bytes = match fs::read(path) {
        Ok(bytes) => bytes,
        Err(e) => return b.done(None, "error", size, None, Some(format!("io_error: {e}"))),
    };
    let sz = bytes.len() as u64;
    if sz > max_file_size {
        return b.done(None, "skipped_too_large", Some(sz), None, None);
    }
    let det = detect(&bytes);
    b.done(Some(det.tag()), "detected", Some(sz), None, None)
}

/// Shared context for tree-mode conversion.
#[derive(Debug, Clone)]
pub struct ConvertCtx {
    pub root: std::path::PathBuf,
    pub target: TargetEncoding,
    pub dry_run: bool,
    pub backup_dir: Option<std::path::PathBuf>,
    pub max_file_size: u64,
}

/// Detect + transcode + (unless dry-run) backup + atomic write.
///
/// Byte-identical outcomes are recorded as `unchanged` and never touch the
/// filesystem (invariant #5). Every failure is contained in this one record
/// (per-file error isolation).
pub fn convert_file(path: &Path, ctx: &ConvertCtx) -> FileRecord {
    let b = RecBuilder::new(path);
    let size = fs::metadata(path).map(|m| m.len()).ok();
    if let Some(sz) = size {
        if sz > ctx.max_file_size {
            return b.done(None, "skipped_too_large", Some(sz), None, None);
        }
    }
    let bytes = match fs::read(path) {
        Ok(bytes) => bytes,
        Err(e) => return b.done(None, "error", size, None, Some(format!("io_error: {e}"))),
    };
    let sz = bytes.len() as u64;
    if sz > ctx.max_file_size {
        return b.done(None, "skipped_too_large", Some(sz), None, None);
    }
    let det = detect(&bytes);
    let tag = det.tag();

    match transcode_detected(&bytes, det, ctx.target) {
        Err(ForgeError::UnknownEncoding) => {
            b.done(Some(tag), "skipped_unknown", Some(sz), None, None)
        }
        Err(e) => b.done(
            Some(tag),
            "error",
            Some(sz),
            None,
            Some(format!("{}: {e}", e.category())),
        ),
        Ok(TranscodeOutcome::Unchanged) => b.done(Some(tag), "unchanged", Some(sz), Some(sz), None),
        Ok(TranscodeOutcome::Changed(new_bytes)) => {
            if ctx.dry_run {
                return b.done(
                    Some(tag),
                    "would_convert",
                    Some(sz),
                    Some(new_bytes.len() as u64),
                    None,
                );
            }
            // Backup the original bytes before the rename (EXECUTION.md §3.2.2).
            if let Some(backup_dir) = &ctx.backup_dir {
                if let Err(e) = writer::backup_original(&ctx.root, path, backup_dir, &bytes) {
                    return b.done(
                        Some(tag),
                        "error",
                        Some(sz),
                        None,
                        Some(format!("{}: backup failed: {e}", e.category())),
                    );
                }
            }
            match writer::atomic_write(path, &new_bytes) {
                Ok(()) => b.done(
                    Some(tag),
                    "converted",
                    Some(sz),
                    Some(new_bytes.len() as u64),
                    None,
                ),
                Err(e) => b.done(
                    Some(tag),
                    "error",
                    Some(sz),
                    None,
                    Some(format!("{}: write failed: {e}", e.category())),
                ),
            }
        }
    }
}

/// Verify a file is UTF-8 without BOM. Unreadable / oversized files fail
/// closed (a gate must not wave through what it cannot inspect).
pub fn verify_file(path: &Path, max_file_size: u64) -> FileRecord {
    let b = RecBuilder::new(path);
    let size = fs::metadata(path).map(|m| m.len()).ok();
    if let Some(sz) = size {
        if sz > max_file_size {
            return b.done(
                None,
                "failed",
                Some(sz),
                None,
                Some("too_large: exceeds --max-file-size".to_string()),
            );
        }
    }
    let bytes = match fs::read(path) {
        Ok(bytes) => bytes,
        Err(e) => return b.done(None, "failed", size, None, Some(format!("io_error: {e}"))),
    };
    let sz = bytes.len() as u64;
    let det = detect(&bytes);
    let tag = det.tag();
    if det == DetectedEncoding::Utf8 {
        b.done(Some(tag), "passed", Some(sz), None, None)
    } else {
        b.done(Some(tag), "failed", Some(sz), None, None)
    }
}

// ---------------------------------------------------------------------------
// Report assembly
// ---------------------------------------------------------------------------

/// Sort records by path (invariant #8), compute the mode-specific summary,
/// and assemble the final report document.
fn finalize_report(
    mode: &'static str,
    root: Option<&Path>,
    url: Option<String>,
    options: OptionsBlock,
    mut records: Vec<FileRecord>,
    elapsed: std::time::Duration,
) -> Report {
    records.sort_by(|a, b| a.path.cmp(&b.path));
    let total = records.len() as u64;

    let summary = match mode {
        "scan" => {
            let mut s = ScanSummary {
                total_files: total,
                ..ScanSummary::default()
            };
            for r in &records {
                if r.action == "skipped_too_large" {
                    s.too_large += 1;
                }
                match r.detected {
                    Some("utf-8") => s.utf8 += 1,
                    Some("utf-8-bom") => s.utf8_bom += 1,
                    Some("utf-16le") => s.utf16le += 1,
                    Some("utf-16be") => s.utf16be += 1,
                    Some("gb18030") => s.gb18030 += 1,
                    Some("unknown") => s.unknown += 1,
                    _ => {}
                }
            }
            s.candidates = total - s.too_large;
            Summary::Scan(s)
        }
        "verify" => {
            let passed = records.iter().filter(|r| r.action == "passed").count() as u64;
            let failed = records.iter().filter(|r| r.action == "failed").count() as u64;
            Summary::Verify(VerifySummary {
                total_files: total,
                candidates: total,
                passed,
                failed,
            })
        }
        _ => {
            let mut s = ConvertSummary {
                total_files: total,
                ..ConvertSummary::default()
            };
            for r in &records {
                match r.action {
                    "unchanged" => s.already_utf8 += 1,
                    "converted" | "would_convert" => s.converted += 1,
                    "skipped_unknown" => s.unknown += 1,
                    "skipped_too_large" => s.too_large += 1,
                    "error" => {
                        let msg = r.error.as_deref().unwrap_or("");
                        if msg.starts_with("decode_error") {
                            s.decode_errors += 1;
                        } else if msg.starts_with("fetch_error") {
                            s.fetch_error += 1;
                        } else {
                            s.io_errors += 1;
                        }
                    }
                    _ => {}
                }
            }
            s.candidates = total - s.too_large;
            Summary::Convert(s)
        }
    };

    let unknown_files: Vec<String> = records
        .iter()
        .filter(|r| r.action == "skipped_unknown" || r.detected == Some("unknown"))
        .map(|r| r.path.clone())
        .collect();
    let error_files: Vec<String> = records
        .iter()
        .filter(|r| r.action == "error" || r.action == "failed")
        .map(|r| r.path.clone())
        .collect();

    Report {
        tool: "utf8-forge",
        version: env!("CARGO_PKG_VERSION"),
        mode,
        root: root.map(|p| p.to_string_lossy().into_owned()),
        url,
        started_at: reporter::rfc3339_now(),
        duration_ms: elapsed.as_millis() as u64,
        options,
        summary,
        files: records,
        unknown_files,
        error_files,
    }
}

/// Snapshot of effective options for the report's `options` block.
fn options_block(args: &TreeArgs, filter: &FilterConfig) -> OptionsBlock {
    let mut extensions: Vec<String> = filter.extensions.iter().cloned().collect();
    extensions.sort();
    let mut exclude_dirs: Vec<String> = filter.exclude_dirs.iter().cloned().collect();
    exclude_dirs.sort();
    let mut exclude_ext: Vec<String> = args.exclude_ext.clone();
    exclude_ext.sort();
    OptionsBlock {
        target: args.target.tag(),
        dry_run: args.dry_run,
        extensions,
        exclude_dirs,
        exclude_ext,
        exclude_globs: args.exclude_glob.clone(),
        backup_dir: args
            .backup_dir
            .as_ref()
            .map(|p| p.to_string_lossy().into_owned()),
    }
}

// ---------------------------------------------------------------------------
// Console output
// ---------------------------------------------------------------------------

/// Print problem lines (stderr, always) and verbose detail lines (stdout, -v).
fn print_records(records: &[FileRecord], console: ConsoleCfg) {
    for r in records {
        match r.action {
            "error" => print_problem(format!(
                "error {} ({})",
                r.path,
                r.error.as_deref().unwrap_or("unspecified")
            )),
            "skipped_unknown" => print_problem(format!("unknown {}", r.path)),
            "failed" => {
                let reason = r
                    .error
                    .clone()
                    .unwrap_or_else(|| format!("detected={}", r.detected.unwrap_or("?")));
                print_problem(format!("failed {} ({reason})", r.path));
            }
            _ => {}
        }
        match r.action {
            "detected" => {
                print_verbose(console, format!("{} {}", r.detected.unwrap_or("?"), r.path))
            }
            "unchanged" => print_verbose(
                console,
                format!("unchanged {} ({})", r.path, r.detected.unwrap_or("?")),
            ),
            "converted" | "would_convert" => print_verbose(
                console,
                format!(
                    "{} {} ({} → {}, {} → {} bytes)",
                    r.action,
                    r.path,
                    r.detected.unwrap_or("?"),
                    "utf-8",
                    r.bytes_before.unwrap_or(0),
                    r.bytes_after.unwrap_or(0)
                ),
            ),
            "skipped_too_large" => print_verbose(
                console,
                format!(
                    "skipped_too_large {} ({} bytes)",
                    r.path,
                    r.bytes_before.unwrap_or(0)
                ),
            ),
            "passed" => print_verbose(console, format!("passed {}", r.path)),
            _ => {}
        }
    }
}

/// Final duration (+ report path) line.
fn print_duration(report: Option<&Path>, elapsed: std::time::Duration, console: ConsoleCfg) {
    if console.quiet {
        return;
    }
    match report {
        Some(p) => println!(
            "[utf8-forge] duration={:.1}s  report={}",
            elapsed.as_secs_f64(),
            p.display()
        ),
        None => println!("[utf8-forge] duration={:.1}s", elapsed.as_secs_f64()),
    }
}

/// `convert` / `fetch` console summary, mirroring `EXECUTION.md §3.2.2`.
fn print_convert_summary(
    s: &ConvertSummary,
    report: Option<&Path>,
    elapsed: std::time::Duration,
    console: ConsoleCfg,
) {
    if !console.quiet {
        println!(
            "[utf8-forge] scanned={}  candidates={}",
            s.total_files, s.candidates
        );
        let errors = s.decode_errors + s.io_errors;
        println!(
            "[utf8-forge] already_utf8={}  converted={}  unknown={}  errors={}",
            s.already_utf8, s.converted, s.unknown, errors
        );
        if s.too_large > 0 {
            println!("[utf8-forge] too_large={}", s.too_large);
        }
        if s.fetch_error > 0 {
            println!("[utf8-forge] fetch_error={}", s.fetch_error);
        }
    }
    print_duration(report, elapsed, console);
}

/// `scan` console summary (encoding distribution).
fn print_scan_summary(
    s: &ScanSummary,
    report: Option<&Path>,
    elapsed: std::time::Duration,
    console: ConsoleCfg,
) {
    if !console.quiet {
        println!(
            "[utf8-forge] scanned={}  candidates={}",
            s.total_files, s.candidates
        );
        println!(
            "[utf8-forge] utf8={}  utf8_bom={}  utf16le={}  utf16be={}  gb18030={}  unknown={}",
            s.utf8, s.utf8_bom, s.utf16le, s.utf16be, s.gb18030, s.unknown
        );
        if s.too_large > 0 {
            println!("[utf8-forge] too_large={}", s.too_large);
        }
    }
    print_duration(report, elapsed, console);
}

// ---------------------------------------------------------------------------
// Shared helpers
// ---------------------------------------------------------------------------

/// Build the effective filter; conflicting flags / bad globs are fatal.
fn build_filter(args: &TreeArgs) -> anyhow::Result<FilterConfig> {
    let opts = FilterOptions {
        ext_override: args.ext.clone(),
        exclude_ext: args.exclude_ext.clone(),
        exclude_dirs: args.exclude.clone(),
        exclude_globs: args.exclude_glob.clone(),
        include_rc: args.include_rc,
        include_msbuild: args.include_msbuild,
        include_hidden: args.include_hidden,
        max_file_size: args.max_file_size,
    };
    FilterConfig::build(&opts).map_err(anyhow::Error::msg)
}

/// Root must be an existing directory, else exit code 2.
fn ensure_root(root: &Path) -> anyhow::Result<()> {
    if !root.is_dir() {
        bail!("root `{}` is not an existing directory", root.display());
    }
    Ok(())
}

/// Prepare the backup directory up front so a broken backup path aborts
/// before any source file is touched.
fn ensure_backup_dir(args: &TreeArgs) -> anyhow::Result<()> {
    if args.dry_run {
        return Ok(());
    }
    if let Some(dir) = &args.backup_dir {
        fs::create_dir_all(dir)
            .with_context(|| format!("cannot create backup dir {}", dir.display()))?;
    }
    Ok(())
}

/// Run `f` on the configured rayon pool (default pool when `--threads` unset).
fn with_pool<R: Send>(threads: Option<usize>, f: impl FnOnce() -> R + Send) -> anyhow::Result<R> {
    match threads {
        Some(n) => {
            let pool = rayon::ThreadPoolBuilder::new()
                .num_threads(n.max(1))
                .build()
                .context("failed to build rayon thread pool")?;
            Ok(pool.install(f))
        }
        None => Ok(f()),
    }
}

fn console_cfg(args: &TreeArgs) -> ConsoleCfg {
    ConsoleCfg {
        quiet: args.quiet,
        verbose: args.verbose,
    }
}

/// Print non-fatal traversal warnings (suppressed by `--quiet`).
fn print_warnings(warnings: &[String], console: ConsoleCfg) {
    if !console.quiet {
        for w in warnings {
            print_problem(w.clone());
        }
    }
}

// ---------------------------------------------------------------------------
// Subcommands
// ---------------------------------------------------------------------------

/// `scan`: detect only, no writes. Exit 1 when `unknown > 0`.
fn cmd_scan(args: &TreeArgs) -> anyhow::Result<i32> {
    ensure_root(&args.root)?;
    let filter = build_filter(args)?;
    let console = console_cfg(args);
    print_header(console, format!("mode=scan root={}", args.root.display()));

    let walk = collect_files(&args.root, &filter);
    print_warnings(&walk.warnings, console);
    let started = Instant::now();
    let records = with_pool(args.threads, || {
        walk.files
            .par_iter()
            .map(|p| scan_file(p, args.max_file_size))
            .collect::<Vec<_>>()
    })?;
    print_records(&records, console);
    let elapsed = started.elapsed();

    let report = finalize_report(
        "scan",
        Some(&args.root),
        None,
        options_block(args, &filter),
        records,
        elapsed,
    );
    let unknown = match &report.summary {
        Summary::Scan(s) => s.unknown,
        _ => 0,
    };
    if let Some(path) = &args.report {
        write_report(&report, path)?;
    }
    if let Summary::Scan(s) = &report.summary {
        print_scan_summary(s, args.report.as_deref(), elapsed, console);
    }
    Ok(if unknown > 0 { 1 } else { 0 })
}

/// `convert`: tree mode or remote fetch.
fn cmd_convert(args: &ConvertArgs) -> anyhow::Result<i32> {
    #[cfg(feature = "remote")]
    {
        if let Some(url) = &args.url {
            return cmd_convert_url(args, url);
        }
    }
    #[cfg(not(feature = "remote"))]
    {
        if args.url.is_some() {
            bail!("--url requires the `remote` feature; rebuild with default features");
        }
    }
    cmd_convert_tree(&args.common)
}

/// `convert` tree mode: detect + transcode + atomic write. Exit 1 when any
/// per-file issue (`unknown` / decode / io) remains.
fn cmd_convert_tree(args: &TreeArgs) -> anyhow::Result<i32> {
    ensure_root(&args.root)?;
    let filter = build_filter(args)?;
    ensure_backup_dir(args)?;
    let console = console_cfg(args);
    let dry_tag = if args.dry_run { " dry_run=true" } else { "" };
    print_header(
        console,
        format!(
            "mode=convert target={} root={}{}",
            args.target,
            args.root.display(),
            dry_tag
        ),
    );

    let walk = collect_files(&args.root, &filter);
    print_warnings(&walk.warnings, console);
    let ctx = ConvertCtx {
        root: args.root.clone(),
        target: args.target,
        dry_run: args.dry_run,
        backup_dir: args.backup_dir.clone(),
        max_file_size: args.max_file_size,
    };
    let started = Instant::now();
    let records = with_pool(args.threads, || {
        walk.files
            .par_iter()
            .map(|p| convert_file(p, &ctx))
            .collect::<Vec<_>>()
    })?;
    print_records(&records, console);
    let elapsed = started.elapsed();

    let report = finalize_report(
        "convert",
        Some(&args.root),
        None,
        options_block(args, &filter),
        records,
        elapsed,
    );
    let summary = match &report.summary {
        Summary::Convert(s) => s.clone(),
        _ => ConvertSummary::default(),
    };
    if let Some(path) = &args.report {
        write_report(&report, path)?;
    }
    print_convert_summary(&summary, args.report.as_deref(), elapsed, console);
    Ok(
        if summary.unknown > 0 || summary.decode_errors > 0 || summary.io_errors > 0 {
            1
        } else {
            0
        },
    )
}

/// `verify`: assert all whitelisted files are UTF-8 without BOM.
/// Exit 0 on success, 3 on any failure.
fn cmd_verify(args: &TreeArgs) -> anyhow::Result<i32> {
    ensure_root(&args.root)?;
    let filter = build_filter(args)?;
    let console = console_cfg(args);
    print_header(console, format!("mode=verify root={}", args.root.display()));

    let walk = collect_files(&args.root, &filter);
    print_warnings(&walk.warnings, console);
    let started = Instant::now();
    let records = with_pool(args.threads, || {
        walk.files
            .par_iter()
            .map(|p| verify_file(p, args.max_file_size))
            .collect::<Vec<_>>()
    })?;
    print_records(&records, console);
    let elapsed = started.elapsed();

    let report = finalize_report(
        "verify",
        Some(&args.root),
        None,
        options_block(args, &filter),
        records,
        elapsed,
    );
    let summary = match &report.summary {
        Summary::Verify(s) => s.clone(),
        _ => VerifySummary::default(),
    };
    if let Some(path) = &args.report {
        write_report(&report, path)?;
    }
    if !console.quiet {
        println!(
            "[utf8-forge] checked={}  passed={}  failed={}",
            summary.total_files, summary.passed, summary.failed
        );
    }
    print_duration(args.report.as_deref(), elapsed, console);
    Ok(if summary.failed > 0 { 3 } else { 0 })
}

/// `convert --url`: fetch → detect → transcode → save (`DESIGN.md §8`).
///
/// The result is always materialized (unless `--dry-run`), even when the
/// payload is already at the target encoding — unlike tree mode there is no
/// existing file for `unchanged` to protect. Exit 1 on fetch/decode/unknown
/// issues; the report is still written for post-mortem.
#[cfg(feature = "remote")]
fn cmd_convert_url(args: &ConvertArgs, url: &str) -> anyhow::Result<i32> {
    let common = &args.common;
    if common.backup_dir.is_some() {
        bail!("--backup-dir is not supported with --url");
    }
    let console = console_cfg(common);
    print_header(
        console,
        format!("mode=fetch target={} url={url}", common.target),
    );
    let started = Instant::now();
    let out_path = args
        .output
        .clone()
        .unwrap_or_else(|| fetcher::derive_output_path(url));

    let record = match fetcher::fetch_bytes(url, common.max_file_size) {
        Err(e) => {
            print_problem(format!("error {url} ({}: {e})", e.category()));
            RecBuilder::new(&out_path).done(
                None,
                "error",
                None,
                None,
                Some(format!("{}: {e}", e.category())),
            )
        }
        Ok(bytes) => {
            let raw_len = bytes.len() as u64;
            let det = detect(&bytes);
            let tag = det.tag();
            match transcode_detected(&bytes, det, common.target) {
                Err(e) => {
                    print_problem(format!("error {url} ({}: {e})", e.category()));
                    RecBuilder::new(&out_path).done(
                        Some(tag),
                        "error",
                        Some(raw_len),
                        None,
                        Some(format!("{}: {e}", e.category())),
                    )
                }
                Ok(outcome) => {
                    let new_bytes = match outcome {
                        TranscodeOutcome::Unchanged => bytes,
                        TranscodeOutcome::Changed(v) => v,
                    };
                    if common.dry_run {
                        RecBuilder::new(&out_path).done(
                            Some(tag),
                            "would_convert",
                            Some(raw_len),
                            Some(new_bytes.len() as u64),
                            None,
                        )
                    } else {
                        if let Some(parent) = out_path.parent() {
                            if !parent.as_os_str().is_empty() {
                                fs::create_dir_all(parent).with_context(|| {
                                    format!("cannot create output dir {}", parent.display())
                                })?;
                            }
                        }
                        match writer::atomic_write(&out_path, &new_bytes) {
                            Ok(()) => RecBuilder::new(&out_path).done(
                                Some(tag),
                                "converted",
                                Some(raw_len),
                                Some(new_bytes.len() as u64),
                                None,
                            ),
                            Err(e) => RecBuilder::new(&out_path).done(
                                Some(tag),
                                "error",
                                Some(raw_len),
                                None,
                                Some(format!("{}: write failed: {e}", e.category())),
                            ),
                        }
                    }
                }
            }
        }
    };
    let elapsed = started.elapsed();

    let options = OptionsBlock {
        target: common.target.tag(),
        dry_run: common.dry_run,
        extensions: Vec::new(),
        exclude_dirs: Vec::new(),
        exclude_ext: Vec::new(),
        exclude_globs: Vec::new(),
        backup_dir: None,
    };
    let report = finalize_report(
        "fetch",
        None,
        Some(url.to_string()),
        options,
        vec![record],
        elapsed,
    );
    let summary = match &report.summary {
        Summary::Convert(s) => s.clone(),
        _ => ConvertSummary::default(),
    };
    if let Some(path) = &common.report {
        write_report(&report, path)?;
    }
    print_convert_summary(&summary, common.report.as_deref(), elapsed, console);
    Ok(
        if summary.unknown > 0
            || summary.decode_errors > 0
            || summary.io_errors > 0
            || summary.fetch_error > 0
        {
            1
        } else {
            0
        },
    )
}