Skip to main content

utf8_forge/
lib.rs

1//! utf8-forge orchestration: per-file pipelines, report assembly, and the
2//! `run()` entry point with exit-code mapping.
3//!
4//! Exit codes (`docs/USAGE.md §7`):
5//! - `0` success
6//! - `1` non-fatal per-file issues (`unknown`, `decode_error`, `io_error`,
7//!   `fetch_error`)
8//! - `2` fatal (bad args, missing root, I/O setup failure) — also emitted by
9//!   clap on parse errors
10//! - `3` `verify` found non-UTF-8 whitelisted files
11
12// Public modules (lib target so integration tests can exercise the
13// pipeline directly; the binary in `main.rs` stays a thin wrapper).
14pub mod cli;
15pub mod detector;
16pub mod error;
17#[cfg(feature = "remote")]
18pub mod fetcher;
19pub mod filter;
20pub mod reporter;
21pub mod transcoder;
22pub mod walker;
23pub mod writer;
24
25use std::fs;
26use std::path::Path;
27use std::time::Instant;
28
29use anyhow::{Context, bail};
30use rayon::prelude::*;
31
32use crate::cli::{Cli, Commands, ConvertArgs, TreeArgs};
33use crate::detector::{DetectedEncoding, detect};
34use crate::error::ForgeError;
35use crate::filter::{FilterConfig, FilterOptions};
36use crate::reporter::{
37    ConsoleCfg, ConvertSummary, FileRecord, OptionsBlock, Report, ScanSummary, Summary,
38    VerifySummary, print_header, print_problem, print_verbose, write_report,
39};
40use crate::transcoder::{TargetEncoding, TranscodeOutcome, transcode_detected};
41use crate::walker::collect_files;
42
43/// Dispatch a parsed CLI and map the outcome to a process exit code.
44/// Fatal setup errors print to stderr and yield exit code 2.
45pub fn run(cli: Cli) -> i32 {
46    let outcome = match cli.command {
47        Commands::Scan(args) => cmd_scan(&args),
48        Commands::Convert(args) => cmd_convert(&args),
49        Commands::Verify(args) => cmd_verify(&args),
50    };
51    outcome.unwrap_or_else(|err| {
52        eprintln!("[utf8-forge] fatal: {err:#}");
53        2
54    })
55}
56
57// ---------------------------------------------------------------------------
58// Per-file processors
59// ---------------------------------------------------------------------------
60
61/// Deferred `FileRecord` builder that stamps per-file duration at completion.
62struct RecBuilder<'a> {
63    path: &'a Path,
64    started: Instant,
65}
66
67impl<'a> RecBuilder<'a> {
68    fn new(path: &'a Path) -> RecBuilder<'a> {
69        RecBuilder {
70            path,
71            started: Instant::now(),
72        }
73    }
74
75    fn done(
76        self,
77        detected: Option<&'static str>,
78        action: &'static str,
79        bytes_before: Option<u64>,
80        bytes_after: Option<u64>,
81        error: Option<String>,
82    ) -> FileRecord {
83        FileRecord {
84            path: self.path.to_string_lossy().into_owned(),
85            detected,
86            action,
87            bytes_before,
88            bytes_after,
89            duration_us: self.started.elapsed().as_micros() as u64,
90            error,
91        }
92    }
93}
94
95/// Detect only. Oversized files are never read.
96pub fn scan_file(path: &Path, max_file_size: u64) -> FileRecord {
97    let b = RecBuilder::new(path);
98    let size = fs::metadata(path).map(|m| m.len()).ok();
99    if let Some(sz) = size {
100        if sz > max_file_size {
101            return b.done(None, "skipped_too_large", Some(sz), None, None);
102        }
103    }
104    let bytes = match fs::read(path) {
105        Ok(bytes) => bytes,
106        Err(e) => return b.done(None, "error", size, None, Some(format!("io_error: {e}"))),
107    };
108    let sz = bytes.len() as u64;
109    if sz > max_file_size {
110        return b.done(None, "skipped_too_large", Some(sz), None, None);
111    }
112    let det = detect(&bytes);
113    b.done(Some(det.tag()), "detected", Some(sz), None, None)
114}
115
116/// Shared context for tree-mode conversion.
117#[derive(Debug, Clone)]
118pub struct ConvertCtx {
119    pub root: std::path::PathBuf,
120    pub target: TargetEncoding,
121    pub dry_run: bool,
122    pub backup_dir: Option<std::path::PathBuf>,
123    pub max_file_size: u64,
124}
125
126/// Detect + transcode + (unless dry-run) backup + atomic write.
127///
128/// Byte-identical outcomes are recorded as `unchanged` and never touch the
129/// filesystem (invariant #5). Every failure is contained in this one record
130/// (per-file error isolation).
131pub fn convert_file(path: &Path, ctx: &ConvertCtx) -> FileRecord {
132    let b = RecBuilder::new(path);
133    let size = fs::metadata(path).map(|m| m.len()).ok();
134    if let Some(sz) = size {
135        if sz > ctx.max_file_size {
136            return b.done(None, "skipped_too_large", Some(sz), None, None);
137        }
138    }
139    let bytes = match fs::read(path) {
140        Ok(bytes) => bytes,
141        Err(e) => return b.done(None, "error", size, None, Some(format!("io_error: {e}"))),
142    };
143    let sz = bytes.len() as u64;
144    if sz > ctx.max_file_size {
145        return b.done(None, "skipped_too_large", Some(sz), None, None);
146    }
147    let det = detect(&bytes);
148    let tag = det.tag();
149
150    match transcode_detected(&bytes, det, ctx.target) {
151        Err(ForgeError::UnknownEncoding) => {
152            b.done(Some(tag), "skipped_unknown", Some(sz), None, None)
153        }
154        Err(e) => b.done(
155            Some(tag),
156            "error",
157            Some(sz),
158            None,
159            Some(format!("{}: {e}", e.category())),
160        ),
161        Ok(TranscodeOutcome::Unchanged) => b.done(Some(tag), "unchanged", Some(sz), Some(sz), None),
162        Ok(TranscodeOutcome::Changed(new_bytes)) => {
163            if ctx.dry_run {
164                return b.done(
165                    Some(tag),
166                    "would_convert",
167                    Some(sz),
168                    Some(new_bytes.len() as u64),
169                    None,
170                );
171            }
172            // Backup the original bytes before the rename (EXECUTION.md §3.2.2).
173            if let Some(backup_dir) = &ctx.backup_dir {
174                if let Err(e) = writer::backup_original(&ctx.root, path, backup_dir, &bytes) {
175                    return b.done(
176                        Some(tag),
177                        "error",
178                        Some(sz),
179                        None,
180                        Some(format!("{}: backup failed: {e}", e.category())),
181                    );
182                }
183            }
184            match writer::atomic_write(path, &new_bytes) {
185                Ok(()) => b.done(
186                    Some(tag),
187                    "converted",
188                    Some(sz),
189                    Some(new_bytes.len() as u64),
190                    None,
191                ),
192                Err(e) => b.done(
193                    Some(tag),
194                    "error",
195                    Some(sz),
196                    None,
197                    Some(format!("{}: write failed: {e}", e.category())),
198                ),
199            }
200        }
201    }
202}
203
204/// Verify a file is UTF-8 without BOM. Unreadable / oversized files fail
205/// closed (a gate must not wave through what it cannot inspect).
206pub fn verify_file(path: &Path, max_file_size: u64) -> FileRecord {
207    let b = RecBuilder::new(path);
208    let size = fs::metadata(path).map(|m| m.len()).ok();
209    if let Some(sz) = size {
210        if sz > max_file_size {
211            return b.done(
212                None,
213                "failed",
214                Some(sz),
215                None,
216                Some("too_large: exceeds --max-file-size".to_string()),
217            );
218        }
219    }
220    let bytes = match fs::read(path) {
221        Ok(bytes) => bytes,
222        Err(e) => return b.done(None, "failed", size, None, Some(format!("io_error: {e}"))),
223    };
224    let sz = bytes.len() as u64;
225    let det = detect(&bytes);
226    let tag = det.tag();
227    if det == DetectedEncoding::Utf8 {
228        b.done(Some(tag), "passed", Some(sz), None, None)
229    } else {
230        b.done(Some(tag), "failed", Some(sz), None, None)
231    }
232}
233
234// ---------------------------------------------------------------------------
235// Report assembly
236// ---------------------------------------------------------------------------
237
238/// Sort records by path (invariant #8), compute the mode-specific summary,
239/// and assemble the final report document.
240fn finalize_report(
241    mode: &'static str,
242    root: Option<&Path>,
243    url: Option<String>,
244    options: OptionsBlock,
245    mut records: Vec<FileRecord>,
246    elapsed: std::time::Duration,
247) -> Report {
248    records.sort_by(|a, b| a.path.cmp(&b.path));
249    let total = records.len() as u64;
250
251    let summary = match mode {
252        "scan" => {
253            let mut s = ScanSummary {
254                total_files: total,
255                ..ScanSummary::default()
256            };
257            for r in &records {
258                if r.action == "skipped_too_large" {
259                    s.too_large += 1;
260                }
261                match r.detected {
262                    Some("utf-8") => s.utf8 += 1,
263                    Some("utf-8-bom") => s.utf8_bom += 1,
264                    Some("utf-16le") => s.utf16le += 1,
265                    Some("utf-16be") => s.utf16be += 1,
266                    Some("gb18030") => s.gb18030 += 1,
267                    Some("unknown") => s.unknown += 1,
268                    _ => {}
269                }
270            }
271            s.candidates = total - s.too_large;
272            Summary::Scan(s)
273        }
274        "verify" => {
275            let passed = records.iter().filter(|r| r.action == "passed").count() as u64;
276            let failed = records.iter().filter(|r| r.action == "failed").count() as u64;
277            Summary::Verify(VerifySummary {
278                total_files: total,
279                candidates: total,
280                passed,
281                failed,
282            })
283        }
284        _ => {
285            let mut s = ConvertSummary {
286                total_files: total,
287                ..ConvertSummary::default()
288            };
289            for r in &records {
290                match r.action {
291                    "unchanged" => s.already_utf8 += 1,
292                    "converted" | "would_convert" => s.converted += 1,
293                    "skipped_unknown" => s.unknown += 1,
294                    "skipped_too_large" => s.too_large += 1,
295                    "error" => {
296                        let msg = r.error.as_deref().unwrap_or("");
297                        if msg.starts_with("decode_error") {
298                            s.decode_errors += 1;
299                        } else if msg.starts_with("fetch_error") {
300                            s.fetch_error += 1;
301                        } else {
302                            s.io_errors += 1;
303                        }
304                    }
305                    _ => {}
306                }
307            }
308            s.candidates = total - s.too_large;
309            Summary::Convert(s)
310        }
311    };
312
313    let unknown_files: Vec<String> = records
314        .iter()
315        .filter(|r| r.action == "skipped_unknown" || r.detected == Some("unknown"))
316        .map(|r| r.path.clone())
317        .collect();
318    let error_files: Vec<String> = records
319        .iter()
320        .filter(|r| r.action == "error" || r.action == "failed")
321        .map(|r| r.path.clone())
322        .collect();
323
324    Report {
325        tool: "utf8-forge",
326        version: env!("CARGO_PKG_VERSION"),
327        mode,
328        root: root.map(|p| p.to_string_lossy().into_owned()),
329        url,
330        started_at: reporter::rfc3339_now(),
331        duration_ms: elapsed.as_millis() as u64,
332        options,
333        summary,
334        files: records,
335        unknown_files,
336        error_files,
337    }
338}
339
340/// Snapshot of effective options for the report's `options` block.
341fn options_block(args: &TreeArgs, filter: &FilterConfig) -> OptionsBlock {
342    let mut extensions: Vec<String> = filter.extensions.iter().cloned().collect();
343    extensions.sort();
344    let mut exclude_dirs: Vec<String> = filter.exclude_dirs.iter().cloned().collect();
345    exclude_dirs.sort();
346    let mut exclude_ext: Vec<String> = args.exclude_ext.clone();
347    exclude_ext.sort();
348    OptionsBlock {
349        target: args.target.tag(),
350        dry_run: args.dry_run,
351        extensions,
352        exclude_dirs,
353        exclude_ext,
354        exclude_globs: args.exclude_glob.clone(),
355        backup_dir: args
356            .backup_dir
357            .as_ref()
358            .map(|p| p.to_string_lossy().into_owned()),
359    }
360}
361
362// ---------------------------------------------------------------------------
363// Console output
364// ---------------------------------------------------------------------------
365
366/// Print problem lines (stderr, always) and verbose detail lines (stdout, -v).
367fn print_records(records: &[FileRecord], console: ConsoleCfg) {
368    for r in records {
369        match r.action {
370            "error" => print_problem(format!(
371                "error {} ({})",
372                r.path,
373                r.error.as_deref().unwrap_or("unspecified")
374            )),
375            "skipped_unknown" => print_problem(format!("unknown {}", r.path)),
376            "failed" => {
377                let reason = r
378                    .error
379                    .clone()
380                    .unwrap_or_else(|| format!("detected={}", r.detected.unwrap_or("?")));
381                print_problem(format!("failed {} ({reason})", r.path));
382            }
383            _ => {}
384        }
385        match r.action {
386            "detected" => {
387                print_verbose(console, format!("{} {}", r.detected.unwrap_or("?"), r.path))
388            }
389            "unchanged" => print_verbose(
390                console,
391                format!("unchanged {} ({})", r.path, r.detected.unwrap_or("?")),
392            ),
393            "converted" | "would_convert" => print_verbose(
394                console,
395                format!(
396                    "{} {} ({} → {}, {} → {} bytes)",
397                    r.action,
398                    r.path,
399                    r.detected.unwrap_or("?"),
400                    "utf-8",
401                    r.bytes_before.unwrap_or(0),
402                    r.bytes_after.unwrap_or(0)
403                ),
404            ),
405            "skipped_too_large" => print_verbose(
406                console,
407                format!(
408                    "skipped_too_large {} ({} bytes)",
409                    r.path,
410                    r.bytes_before.unwrap_or(0)
411                ),
412            ),
413            "passed" => print_verbose(console, format!("passed {}", r.path)),
414            _ => {}
415        }
416    }
417}
418
419/// Final duration (+ report path) line.
420fn print_duration(report: Option<&Path>, elapsed: std::time::Duration, console: ConsoleCfg) {
421    if console.quiet {
422        return;
423    }
424    match report {
425        Some(p) => println!(
426            "[utf8-forge] duration={:.1}s  report={}",
427            elapsed.as_secs_f64(),
428            p.display()
429        ),
430        None => println!("[utf8-forge] duration={:.1}s", elapsed.as_secs_f64()),
431    }
432}
433
434/// `convert` / `fetch` console summary, mirroring `EXECUTION.md §3.2.2`.
435fn print_convert_summary(
436    s: &ConvertSummary,
437    report: Option<&Path>,
438    elapsed: std::time::Duration,
439    console: ConsoleCfg,
440) {
441    if !console.quiet {
442        println!(
443            "[utf8-forge] scanned={}  candidates={}",
444            s.total_files, s.candidates
445        );
446        let errors = s.decode_errors + s.io_errors;
447        println!(
448            "[utf8-forge] already_utf8={}  converted={}  unknown={}  errors={}",
449            s.already_utf8, s.converted, s.unknown, errors
450        );
451        if s.too_large > 0 {
452            println!("[utf8-forge] too_large={}", s.too_large);
453        }
454        if s.fetch_error > 0 {
455            println!("[utf8-forge] fetch_error={}", s.fetch_error);
456        }
457    }
458    print_duration(report, elapsed, console);
459}
460
461/// `scan` console summary (encoding distribution).
462fn print_scan_summary(
463    s: &ScanSummary,
464    report: Option<&Path>,
465    elapsed: std::time::Duration,
466    console: ConsoleCfg,
467) {
468    if !console.quiet {
469        println!(
470            "[utf8-forge] scanned={}  candidates={}",
471            s.total_files, s.candidates
472        );
473        println!(
474            "[utf8-forge] utf8={}  utf8_bom={}  utf16le={}  utf16be={}  gb18030={}  unknown={}",
475            s.utf8, s.utf8_bom, s.utf16le, s.utf16be, s.gb18030, s.unknown
476        );
477        if s.too_large > 0 {
478            println!("[utf8-forge] too_large={}", s.too_large);
479        }
480    }
481    print_duration(report, elapsed, console);
482}
483
484// ---------------------------------------------------------------------------
485// Shared helpers
486// ---------------------------------------------------------------------------
487
488/// Build the effective filter; conflicting flags / bad globs are fatal.
489fn build_filter(args: &TreeArgs) -> anyhow::Result<FilterConfig> {
490    let opts = FilterOptions {
491        ext_override: args.ext.clone(),
492        exclude_ext: args.exclude_ext.clone(),
493        exclude_dirs: args.exclude.clone(),
494        exclude_globs: args.exclude_glob.clone(),
495        include_rc: args.include_rc,
496        include_msbuild: args.include_msbuild,
497        include_hidden: args.include_hidden,
498        max_file_size: args.max_file_size,
499    };
500    FilterConfig::build(&opts).map_err(anyhow::Error::msg)
501}
502
503/// Root must be an existing directory, else exit code 2.
504fn ensure_root(root: &Path) -> anyhow::Result<()> {
505    if !root.is_dir() {
506        bail!("root `{}` is not an existing directory", root.display());
507    }
508    Ok(())
509}
510
511/// Prepare the backup directory up front so a broken backup path aborts
512/// before any source file is touched.
513fn ensure_backup_dir(args: &TreeArgs) -> anyhow::Result<()> {
514    if args.dry_run {
515        return Ok(());
516    }
517    if let Some(dir) = &args.backup_dir {
518        fs::create_dir_all(dir)
519            .with_context(|| format!("cannot create backup dir {}", dir.display()))?;
520    }
521    Ok(())
522}
523
524/// Run `f` on the configured rayon pool (default pool when `--threads` unset).
525fn with_pool<R: Send>(threads: Option<usize>, f: impl FnOnce() -> R + Send) -> anyhow::Result<R> {
526    match threads {
527        Some(n) => {
528            let pool = rayon::ThreadPoolBuilder::new()
529                .num_threads(n.max(1))
530                .build()
531                .context("failed to build rayon thread pool")?;
532            Ok(pool.install(f))
533        }
534        None => Ok(f()),
535    }
536}
537
538fn console_cfg(args: &TreeArgs) -> ConsoleCfg {
539    ConsoleCfg {
540        quiet: args.quiet,
541        verbose: args.verbose,
542    }
543}
544
545/// Print non-fatal traversal warnings (suppressed by `--quiet`).
546fn print_warnings(warnings: &[String], console: ConsoleCfg) {
547    if !console.quiet {
548        for w in warnings {
549            print_problem(w.clone());
550        }
551    }
552}
553
554// ---------------------------------------------------------------------------
555// Subcommands
556// ---------------------------------------------------------------------------
557
558/// `scan`: detect only, no writes. Exit 1 when `unknown > 0`.
559fn cmd_scan(args: &TreeArgs) -> anyhow::Result<i32> {
560    ensure_root(&args.root)?;
561    let filter = build_filter(args)?;
562    let console = console_cfg(args);
563    print_header(console, format!("mode=scan root={}", args.root.display()));
564
565    let walk = collect_files(&args.root, &filter);
566    print_warnings(&walk.warnings, console);
567    let started = Instant::now();
568    let records = with_pool(args.threads, || {
569        walk.files
570            .par_iter()
571            .map(|p| scan_file(p, args.max_file_size))
572            .collect::<Vec<_>>()
573    })?;
574    print_records(&records, console);
575    let elapsed = started.elapsed();
576
577    let report = finalize_report(
578        "scan",
579        Some(&args.root),
580        None,
581        options_block(args, &filter),
582        records,
583        elapsed,
584    );
585    let unknown = match &report.summary {
586        Summary::Scan(s) => s.unknown,
587        _ => 0,
588    };
589    if let Some(path) = &args.report {
590        write_report(&report, path)?;
591    }
592    if let Summary::Scan(s) = &report.summary {
593        print_scan_summary(s, args.report.as_deref(), elapsed, console);
594    }
595    Ok(if unknown > 0 { 1 } else { 0 })
596}
597
598/// `convert`: tree mode or remote fetch.
599fn cmd_convert(args: &ConvertArgs) -> anyhow::Result<i32> {
600    #[cfg(feature = "remote")]
601    {
602        if let Some(url) = &args.url {
603            return cmd_convert_url(args, url);
604        }
605    }
606    #[cfg(not(feature = "remote"))]
607    {
608        if args.url.is_some() {
609            bail!("--url requires the `remote` feature; rebuild with default features");
610        }
611    }
612    cmd_convert_tree(&args.common)
613}
614
615/// `convert` tree mode: detect + transcode + atomic write. Exit 1 when any
616/// per-file issue (`unknown` / decode / io) remains.
617fn cmd_convert_tree(args: &TreeArgs) -> anyhow::Result<i32> {
618    ensure_root(&args.root)?;
619    let filter = build_filter(args)?;
620    ensure_backup_dir(args)?;
621    let console = console_cfg(args);
622    let dry_tag = if args.dry_run { " dry_run=true" } else { "" };
623    print_header(
624        console,
625        format!(
626            "mode=convert target={} root={}{}",
627            args.target,
628            args.root.display(),
629            dry_tag
630        ),
631    );
632
633    let walk = collect_files(&args.root, &filter);
634    print_warnings(&walk.warnings, console);
635    let ctx = ConvertCtx {
636        root: args.root.clone(),
637        target: args.target,
638        dry_run: args.dry_run,
639        backup_dir: args.backup_dir.clone(),
640        max_file_size: args.max_file_size,
641    };
642    let started = Instant::now();
643    let records = with_pool(args.threads, || {
644        walk.files
645            .par_iter()
646            .map(|p| convert_file(p, &ctx))
647            .collect::<Vec<_>>()
648    })?;
649    print_records(&records, console);
650    let elapsed = started.elapsed();
651
652    let report = finalize_report(
653        "convert",
654        Some(&args.root),
655        None,
656        options_block(args, &filter),
657        records,
658        elapsed,
659    );
660    let summary = match &report.summary {
661        Summary::Convert(s) => s.clone(),
662        _ => ConvertSummary::default(),
663    };
664    if let Some(path) = &args.report {
665        write_report(&report, path)?;
666    }
667    print_convert_summary(&summary, args.report.as_deref(), elapsed, console);
668    Ok(
669        if summary.unknown > 0 || summary.decode_errors > 0 || summary.io_errors > 0 {
670            1
671        } else {
672            0
673        },
674    )
675}
676
677/// `verify`: assert all whitelisted files are UTF-8 without BOM.
678/// Exit 0 on success, 3 on any failure.
679fn cmd_verify(args: &TreeArgs) -> anyhow::Result<i32> {
680    ensure_root(&args.root)?;
681    let filter = build_filter(args)?;
682    let console = console_cfg(args);
683    print_header(console, format!("mode=verify root={}", args.root.display()));
684
685    let walk = collect_files(&args.root, &filter);
686    print_warnings(&walk.warnings, console);
687    let started = Instant::now();
688    let records = with_pool(args.threads, || {
689        walk.files
690            .par_iter()
691            .map(|p| verify_file(p, args.max_file_size))
692            .collect::<Vec<_>>()
693    })?;
694    print_records(&records, console);
695    let elapsed = started.elapsed();
696
697    let report = finalize_report(
698        "verify",
699        Some(&args.root),
700        None,
701        options_block(args, &filter),
702        records,
703        elapsed,
704    );
705    let summary = match &report.summary {
706        Summary::Verify(s) => s.clone(),
707        _ => VerifySummary::default(),
708    };
709    if let Some(path) = &args.report {
710        write_report(&report, path)?;
711    }
712    if !console.quiet {
713        println!(
714            "[utf8-forge] checked={}  passed={}  failed={}",
715            summary.total_files, summary.passed, summary.failed
716        );
717    }
718    print_duration(args.report.as_deref(), elapsed, console);
719    Ok(if summary.failed > 0 { 3 } else { 0 })
720}
721
722/// `convert --url`: fetch → detect → transcode → save (`DESIGN.md §8`).
723///
724/// The result is always materialized (unless `--dry-run`), even when the
725/// payload is already at the target encoding — unlike tree mode there is no
726/// existing file for `unchanged` to protect. Exit 1 on fetch/decode/unknown
727/// issues; the report is still written for post-mortem.
728#[cfg(feature = "remote")]
729fn cmd_convert_url(args: &ConvertArgs, url: &str) -> anyhow::Result<i32> {
730    let common = &args.common;
731    if common.backup_dir.is_some() {
732        bail!("--backup-dir is not supported with --url");
733    }
734    let console = console_cfg(common);
735    print_header(
736        console,
737        format!("mode=fetch target={} url={url}", common.target),
738    );
739    let started = Instant::now();
740    let out_path = args
741        .output
742        .clone()
743        .unwrap_or_else(|| fetcher::derive_output_path(url));
744
745    let record = match fetcher::fetch_bytes(url, common.max_file_size) {
746        Err(e) => {
747            print_problem(format!("error {url} ({}: {e})", e.category()));
748            RecBuilder::new(&out_path).done(
749                None,
750                "error",
751                None,
752                None,
753                Some(format!("{}: {e}", e.category())),
754            )
755        }
756        Ok(bytes) => {
757            let raw_len = bytes.len() as u64;
758            let det = detect(&bytes);
759            let tag = det.tag();
760            match transcode_detected(&bytes, det, common.target) {
761                Err(e) => {
762                    print_problem(format!("error {url} ({}: {e})", e.category()));
763                    RecBuilder::new(&out_path).done(
764                        Some(tag),
765                        "error",
766                        Some(raw_len),
767                        None,
768                        Some(format!("{}: {e}", e.category())),
769                    )
770                }
771                Ok(outcome) => {
772                    let new_bytes = match outcome {
773                        TranscodeOutcome::Unchanged => bytes,
774                        TranscodeOutcome::Changed(v) => v,
775                    };
776                    if common.dry_run {
777                        RecBuilder::new(&out_path).done(
778                            Some(tag),
779                            "would_convert",
780                            Some(raw_len),
781                            Some(new_bytes.len() as u64),
782                            None,
783                        )
784                    } else {
785                        if let Some(parent) = out_path.parent() {
786                            if !parent.as_os_str().is_empty() {
787                                fs::create_dir_all(parent).with_context(|| {
788                                    format!("cannot create output dir {}", parent.display())
789                                })?;
790                            }
791                        }
792                        match writer::atomic_write(&out_path, &new_bytes) {
793                            Ok(()) => RecBuilder::new(&out_path).done(
794                                Some(tag),
795                                "converted",
796                                Some(raw_len),
797                                Some(new_bytes.len() as u64),
798                                None,
799                            ),
800                            Err(e) => RecBuilder::new(&out_path).done(
801                                Some(tag),
802                                "error",
803                                Some(raw_len),
804                                None,
805                                Some(format!("{}: write failed: {e}", e.category())),
806                            ),
807                        }
808                    }
809                }
810            }
811        }
812    };
813    let elapsed = started.elapsed();
814
815    let options = OptionsBlock {
816        target: common.target.tag(),
817        dry_run: common.dry_run,
818        extensions: Vec::new(),
819        exclude_dirs: Vec::new(),
820        exclude_ext: Vec::new(),
821        exclude_globs: Vec::new(),
822        backup_dir: None,
823    };
824    let report = finalize_report(
825        "fetch",
826        None,
827        Some(url.to_string()),
828        options,
829        vec![record],
830        elapsed,
831    );
832    let summary = match &report.summary {
833        Summary::Convert(s) => s.clone(),
834        _ => ConvertSummary::default(),
835    };
836    if let Some(path) = &common.report {
837        write_report(&report, path)?;
838    }
839    print_convert_summary(&summary, common.report.as_deref(), elapsed, console);
840    Ok(
841        if summary.unknown > 0
842            || summary.decode_errors > 0
843            || summary.io_errors > 0
844            || summary.fetch_error > 0
845        {
846            1
847        } else {
848            0
849        },
850    )
851}