1pub mod cli;
30pub mod config;
31pub mod detector;
32pub mod differ;
33pub mod error;
34#[cfg(feature = "remote")]
35pub mod fetcher;
36pub mod filter;
37pub mod ignorefile;
38pub mod reporter;
39pub mod transcoder;
40pub mod walker;
41pub mod writer;
42
43use std::fs;
44use std::path::{Path, PathBuf};
45use std::time::Instant;
46
47use anyhow::{Context, bail};
48use rayon::prelude::*;
49
50use crate::cli::{Cli, Commands, ConvertArgs, DiffArgs, FixArgs, TreeArgs};
51use crate::detector::{DetectedEncoding, detect};
52use crate::differ::DiffInput;
53use crate::error::ForgeError;
54use crate::filter::{FilterConfig, FilterOptions};
55use crate::reporter::{
56 ConsoleCfg, ConvertSummary, FileRecord, FixSummary, OptionsBlock, Report, ScanSummary, Summary,
57 VerifySummary, print_header, print_problem, print_verbose, write_report,
58};
59use crate::transcoder::{TargetEncoding, TranscodeOutcome, transcode_detected};
60use crate::walker::collect_files;
61
62pub fn run(cli: Cli) -> i32 {
65 let outcome = match cli.command {
66 Commands::Scan(args) => cmd_scan(&args),
67 Commands::Convert(args) => cmd_convert(&args),
68 Commands::Verify(args) => cmd_verify(&args),
69 Commands::Fix(args) => cmd_fix(&args),
70 Commands::Diff(args) => cmd_diff(&args),
71 };
72 outcome.unwrap_or_else(|err| {
73 eprintln!("[utf8-forge] fatal: {err:#}");
74 2
75 })
76}
77
78struct RecBuilder<'a> {
84 path: &'a Path,
85 started: Instant,
86}
87
88impl<'a> RecBuilder<'a> {
89 fn new(path: &'a Path) -> RecBuilder<'a> {
90 RecBuilder {
91 path,
92 started: Instant::now(),
93 }
94 }
95
96 fn done(
97 self,
98 detected: Option<&'static str>,
99 action: &'static str,
100 bytes_before: Option<u64>,
101 bytes_after: Option<u64>,
102 error: Option<String>,
103 ) -> FileRecord {
104 FileRecord {
105 path: self.path.to_string_lossy().into_owned(),
106 detected,
107 action,
108 bytes_before,
109 bytes_after,
110 duration_us: self.started.elapsed().as_micros() as u64,
111 error,
112 }
113 }
114}
115
116pub fn scan_file(path: &Path, max_file_size: u64) -> FileRecord {
118 let b = RecBuilder::new(path);
119 let size = fs::metadata(path).map(|m| m.len()).ok();
120 if let Some(sz) = size
121 && sz > max_file_size
122 {
123 return b.done(None, "skipped_too_large", Some(sz), None, None);
124 }
125 let bytes = match fs::read(path) {
126 Ok(bytes) => bytes,
127 Err(e) => return b.done(None, "error", size, None, Some(format!("io_error: {e}"))),
128 };
129 let sz = bytes.len() as u64;
130 if sz > max_file_size {
131 return b.done(None, "skipped_too_large", Some(sz), None, None);
132 }
133 let det = detect(&bytes);
134 b.done(Some(det.tag()), "detected", Some(sz), None, None)
135}
136
137#[derive(Debug, Clone)]
139pub struct ConvertCtx {
140 pub root: std::path::PathBuf,
141 pub target: TargetEncoding,
142 pub dry_run: bool,
143 pub backup_dir: Option<std::path::PathBuf>,
144 pub max_file_size: u64,
145}
146
147pub fn convert_file(path: &Path, ctx: &ConvertCtx) -> 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 > ctx.max_file_size
157 {
158 return b.done(None, "skipped_too_large", Some(sz), None, None);
159 }
160 let bytes = match fs::read(path) {
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 > ctx.max_file_size {
166 return b.done(None, "skipped_too_large", Some(sz), None, None);
167 }
168 let det = detect(&bytes);
169 let tag = det.tag();
170
171 match transcode_detected(&bytes, det, ctx.target) {
172 Err(ForgeError::UnknownEncoding) => {
173 b.done(Some(tag), "skipped_unknown", Some(sz), None, None)
174 }
175 Err(e) => b.done(
176 Some(tag),
177 "error",
178 Some(sz),
179 None,
180 Some(format!("{}: {e}", e.category())),
181 ),
182 Ok(TranscodeOutcome::Unchanged) => b.done(Some(tag), "unchanged", Some(sz), Some(sz), None),
183 Ok(TranscodeOutcome::Changed(new_bytes)) => {
184 if ctx.dry_run {
185 return b.done(
186 Some(tag),
187 "would_convert",
188 Some(sz),
189 Some(new_bytes.len() as u64),
190 None,
191 );
192 }
193 let write_protected = fs::metadata(path)
197 .map(|m| m.permissions().readonly())
198 .unwrap_or(false);
199 if write_protected {
200 return b.done(
201 Some(tag),
202 "error",
203 Some(sz),
204 None,
205 Some(
206 "io_error: file is write-protected (read-only); chmod +w to convert".into(),
207 ),
208 );
209 }
210 if let Some(backup_dir) = &ctx.backup_dir
213 && let Err(e) = writer::backup_original(&ctx.root, path, backup_dir, &bytes)
214 {
215 return b.done(
216 Some(tag),
217 "error",
218 Some(sz),
219 None,
220 Some(format!("{}: backup failed: {e}", e.category())),
221 );
222 }
223 match writer::atomic_write(path, &new_bytes) {
224 Ok(()) => b.done(
225 Some(tag),
226 "converted",
227 Some(sz),
228 Some(new_bytes.len() as u64),
229 None,
230 ),
231 Err(e) => b.done(
232 Some(tag),
233 "error",
234 Some(sz),
235 None,
236 Some(format!("{}: write failed: {e}", e.category())),
237 ),
238 }
239 }
240 }
241}
242
243pub fn verify_file(path: &Path, max_file_size: u64) -> FileRecord {
246 let b = RecBuilder::new(path);
247 let size = fs::metadata(path).map(|m| m.len()).ok();
248 if let Some(sz) = size
249 && sz > max_file_size
250 {
251 return b.done(
252 None,
253 "failed",
254 Some(sz),
255 None,
256 Some("too_large: exceeds --max-file-size".to_string()),
257 );
258 }
259 let bytes = match fs::read(path) {
260 Ok(bytes) => bytes,
261 Err(e) => return b.done(None, "failed", size, None, Some(format!("io_error: {e}"))),
262 };
263 let sz = bytes.len() as u64;
264 let det = detect(&bytes);
265 let tag = det.tag();
266 if det == DetectedEncoding::Utf8 {
267 b.done(Some(tag), "passed", Some(sz), None, None)
268 } else {
269 b.done(Some(tag), "failed", Some(sz), None, None)
270 }
271}
272
273struct RunFacts {
281 root: Option<std::path::PathBuf>,
282 url: Option<String>,
283 options: OptionsBlock,
284 started_at: String,
285 verify_failed: Option<Vec<String>>,
286}
287
288fn finalize_report(
289 mode: &'static str,
290 facts: RunFacts,
291 mut records: Vec<FileRecord>,
292 elapsed: std::time::Duration,
293) -> Report {
294 records.sort_by(|a, b| a.path.cmp(&b.path));
295 let total = records.len() as u64;
296
297 let summary = match mode {
298 "scan" => {
299 let mut s = ScanSummary {
300 total_files: total,
301 ..ScanSummary::default()
302 };
303 for r in &records {
304 if r.action == "skipped_too_large" {
305 s.too_large += 1;
306 }
307 if r.action == "error" {
308 s.errors += 1;
309 }
310 match r.detected {
311 Some("utf-8") => s.utf8 += 1,
312 Some("utf-8-bom") => s.utf8_bom += 1,
313 Some("utf-16le") => s.utf16le += 1,
314 Some("utf-16be") => s.utf16be += 1,
315 Some("utf-32le") => s.utf32le += 1,
316 Some("utf-32be") => s.utf32be += 1,
317 Some("gb18030") => s.gb18030 += 1,
318 Some("unknown") => s.unknown += 1,
319 _ => {}
320 }
321 }
322 s.candidates = total - s.too_large;
323 Summary::Scan(s)
324 }
325 "verify" => {
326 let passed = records.iter().filter(|r| r.action == "passed").count() as u64;
327 let failed = records.iter().filter(|r| r.action == "failed").count() as u64;
328 Summary::Verify(VerifySummary {
329 total_files: total,
330 candidates: total,
331 passed,
332 failed,
333 })
334 }
335 "fix" => {
336 let mut s = FixSummary {
337 total_files: total,
338 ..FixSummary::default()
339 };
340 for r in &records {
341 if r.action == "skipped_too_large" {
342 s.too_large += 1;
343 }
344 match r.action {
345 "unchanged" => s.already_utf8 += 1,
346 "converted" | "would_convert" => s.converted += 1,
347 "skipped_unknown" => s.unknown += 1,
348 "error" => {
349 let msg = r.error.as_deref().unwrap_or("");
350 if msg.starts_with("decode_error") {
351 s.decode_errors += 1;
352 } else {
353 s.io_errors += 1;
354 }
355 }
356 _ => {}
357 }
358 }
359 s.candidates = total - s.too_large;
360 Summary::Fix(s)
361 }
362 _ => {
363 let mut s = ConvertSummary {
364 total_files: total,
365 ..ConvertSummary::default()
366 };
367 for r in &records {
368 match r.action {
369 "unchanged" => s.already_utf8 += 1,
370 "converted" | "would_convert" => s.converted += 1,
371 "skipped_unknown" => s.unknown += 1,
372 "skipped_too_large" => s.too_large += 1,
373 "error" => {
374 let msg = r.error.as_deref().unwrap_or("");
375 if msg.starts_with("decode_error") {
376 s.decode_errors += 1;
377 } else if msg.starts_with("fetch_error") {
378 s.fetch_error += 1;
379 } else {
380 s.io_errors += 1;
381 }
382 }
383 _ => {}
384 }
385 }
386 s.candidates = total - s.too_large;
387 Summary::Convert(s)
388 }
389 };
390
391 let unknown_files: Vec<String> = records
392 .iter()
393 .filter(|r| r.action == "skipped_unknown" || r.detected == Some("unknown"))
394 .map(|r| r.path.clone())
395 .collect();
396 let error_files: Vec<String> = records
397 .iter()
398 .filter(|r| r.action == "error" || r.action == "failed")
399 .map(|r| r.path.clone())
400 .collect();
401 Report {
404 tool: "utf8-forge",
405 version: env!("CARGO_PKG_VERSION"),
406 mode,
407 root: facts.root.map(|p| p.to_string_lossy().into_owned()),
408 url: facts.url,
409 started_at: facts.started_at,
410 duration_ms: elapsed.as_millis() as u64,
411 options: facts.options,
412 summary,
413 files: records,
414 unknown_files,
415 error_files,
416 verify_failed_files: facts.verify_failed.unwrap_or_default(),
417 }
418}
419
420fn options_block(
423 args: &TreeArgs,
424 conv: Option<&dyn ConvertOptions>,
425 filter: &FilterConfig,
426 config_file: Option<&str>,
427 ignore_file: Option<&str>,
428) -> OptionsBlock {
429 let mut extensions: Vec<String> = filter.extensions.iter().cloned().collect();
430 extensions.sort();
431 let mut exclude_dirs: Vec<String> = filter.exclude_dirs.iter().cloned().collect();
432 exclude_dirs.sort();
433 let mut exclude_ext: Vec<String> = args.exclude_ext.clone();
434 exclude_ext.sort();
435 OptionsBlock {
436 target: conv.map(|c| c.effective_target()).unwrap_or("utf-8"),
437 dry_run: conv.is_some_and(|c| c.is_dry_run()),
438 extensions,
439 exclude_dirs,
440 exclude_ext,
441 exclude_globs: args.exclude_glob.clone(),
442 backup_dir: conv.and_then(|c| c.backup_dir().map(|p| p.to_string_lossy().into_owned())),
443 config_file: config_file.map(str::to_string),
444 ignore_file: ignore_file.map(str::to_string),
445 }
446}
447
448fn print_records(records: &[FileRecord], console: ConsoleCfg, target_tag: Option<&'static str>) {
458 for r in records {
459 match r.action {
460 "error" => print_problem(format!(
461 "error {} ({})",
462 r.path,
463 r.error.as_deref().unwrap_or("unspecified")
464 )),
465 "skipped_unknown" => print_problem(format!("unknown {}", r.path)),
466 "failed" => {
467 let reason = r
468 .error
469 .clone()
470 .unwrap_or_else(|| format!("detected={}", r.detected.unwrap_or("?")));
471 print_problem(format!("failed {} ({reason})", r.path));
472 }
473 _ => {}
474 }
475 match r.action {
476 "detected" => {
477 print_verbose(console, format!("{} {}", r.detected.unwrap_or("?"), r.path))
478 }
479 "unchanged" => print_verbose(
480 console,
481 format!("unchanged {} ({})", r.path, r.detected.unwrap_or("?")),
482 ),
483 "converted" | "would_convert" => print_verbose(
484 console,
485 format!(
486 "{} {} ({} → {}, {} → {} bytes)",
487 r.action,
488 r.path,
489 r.detected.unwrap_or("?"),
490 target_tag.unwrap_or("?"),
491 r.bytes_before.unwrap_or(0),
492 r.bytes_after.unwrap_or(0)
493 ),
494 ),
495 "skipped_too_large" => print_verbose(
496 console,
497 format!(
498 "skipped_too_large {} ({} bytes)",
499 r.path,
500 r.bytes_before.unwrap_or(0)
501 ),
502 ),
503 "passed" => print_verbose(console, format!("passed {}", r.path)),
504 _ => {}
505 }
506 }
507}
508
509fn print_duration(report: Option<&Path>, elapsed: std::time::Duration, console: ConsoleCfg) {
511 if console.quiet {
512 return;
513 }
514 match report {
515 Some(p) => println!(
516 "[utf8-forge] duration={:.1}s report={}",
517 elapsed.as_secs_f64(),
518 p.display()
519 ),
520 None => println!("[utf8-forge] duration={:.1}s", elapsed.as_secs_f64()),
521 }
522}
523
524fn print_convert_summary(
526 s: &ConvertSummary,
527 report: Option<&Path>,
528 elapsed: std::time::Duration,
529 console: ConsoleCfg,
530) {
531 if !console.quiet {
532 println!(
533 "[utf8-forge] scanned={} candidates={}",
534 s.total_files, s.candidates
535 );
536 let errors = s.decode_errors + s.io_errors;
537 println!(
538 "[utf8-forge] already_utf8={} converted={} unknown={} errors={}",
539 s.already_utf8, s.converted, s.unknown, errors
540 );
541 if s.too_large > 0 {
542 println!("[utf8-forge] too_large={}", s.too_large);
543 }
544 if s.fetch_error > 0 {
545 println!("[utf8-forge] fetch_error={}", s.fetch_error);
546 }
547 }
548 print_duration(report, elapsed, console);
549}
550
551fn print_scan_summary(
553 s: &ScanSummary,
554 report: Option<&Path>,
555 elapsed: std::time::Duration,
556 console: ConsoleCfg,
557) {
558 if !console.quiet {
559 println!(
560 "[utf8-forge] scanned={} candidates={}",
561 s.total_files, s.candidates
562 );
563 println!(
564 "[utf8-forge] utf8={} utf8_bom={} utf16le={} utf16be={} utf32le={} utf32be={} gb18030={} unknown={}",
565 s.utf8, s.utf8_bom, s.utf16le, s.utf16be, s.utf32le, s.utf32be, s.gb18030, s.unknown
566 );
567 if s.errors > 0 {
568 println!("[utf8-forge] errors={}", s.errors);
569 }
570 if s.too_large > 0 {
571 println!("[utf8-forge] too_large={}", s.too_large);
572 }
573 }
574 print_duration(report, elapsed, console);
575}
576
577fn build_filter(args: &TreeArgs) -> anyhow::Result<FilterConfig> {
583 let opts = FilterOptions {
584 ext_override: args.ext.clone(),
585 exclude_ext: args.exclude_ext.clone(),
586 exclude_dirs: args.exclude.clone(),
587 exclude_globs: args.exclude_glob.clone(),
588 include_rc: args.include_rc,
589 include_msbuild: args.include_msbuild,
590 include_hidden: args.include_hidden,
591 };
592 FilterConfig::build(&opts).map_err(anyhow::Error::msg)
593}
594
595fn merge_tree_config(common: &mut TreeArgs) -> anyhow::Result<Option<String>> {
601 let Some(path) = common.config.clone() else {
602 return Ok(None);
603 };
604 let cfg = crate::config::load(&path)?;
605 if common.ext.is_empty() {
606 common.ext = cfg.filter.extensions.clone();
607 }
608 if common.exclude.is_empty() {
609 common.exclude = cfg.filter.exclude_dirs.clone();
610 }
611 if common.exclude_ext.is_empty() {
612 common.exclude_ext = cfg.filter.exclude_ext.clone();
613 }
614 if common.exclude_glob.is_empty() {
615 common.exclude_glob = cfg.filter.exclude_globs.clone();
616 }
617 common.include_rc |= cfg.filter.include_rc;
618 common.include_msbuild |= cfg.filter.include_msbuild;
619 common.include_hidden |= cfg.filter.include_hidden;
620 if common.max_file_size.is_none() {
621 common.max_file_size = cfg.options.max_file_size;
622 }
623 if common.threads.is_none() {
624 common.threads = cfg.options.threads;
625 }
626 Ok(Some(path.to_string_lossy().into_owned()))
627}
628
629trait ConvertOptions {
632 fn common(&self) -> &TreeArgs;
633 fn common_mut(&mut self) -> &mut TreeArgs;
634 fn set_target(&mut self, t: Option<crate::transcoder::TargetEncoding>);
635 fn set_backup_dir(&mut self, p: Option<std::path::PathBuf>);
636 fn target(&self) -> Option<crate::transcoder::TargetEncoding>;
637 fn backup_dir(&self) -> Option<&std::path::PathBuf>;
638 fn is_dry_run(&self) -> bool;
639
640 fn effective_target(&self) -> &'static str {
642 self.target()
643 .unwrap_or(crate::transcoder::TargetEncoding::Utf8)
644 .tag()
645 }
646}
647
648impl ConvertOptions for ConvertArgs {
649 fn common(&self) -> &TreeArgs {
650 &self.common
651 }
652 fn target(&self) -> Option<crate::transcoder::TargetEncoding> {
653 self.target
654 }
655 fn common_mut(&mut self) -> &mut TreeArgs {
656 &mut self.common
657 }
658 fn set_target(&mut self, t: Option<crate::transcoder::TargetEncoding>) {
659 self.target = t;
660 }
661 fn set_backup_dir(&mut self, p: Option<std::path::PathBuf>) {
662 self.backup_dir = p;
663 }
664 fn backup_dir(&self) -> Option<&std::path::PathBuf> {
665 self.backup_dir.as_ref()
666 }
667 fn is_dry_run(&self) -> bool {
668 self.dry_run
669 }
670}
671
672impl ConvertOptions for FixArgs {
673 fn common(&self) -> &TreeArgs {
674 &self.common
675 }
676 fn target(&self) -> Option<crate::transcoder::TargetEncoding> {
677 self.target
678 }
679 fn common_mut(&mut self) -> &mut TreeArgs {
680 &mut self.common
681 }
682 fn set_target(&mut self, t: Option<crate::transcoder::TargetEncoding>) {
683 self.target = t;
684 }
685 fn set_backup_dir(&mut self, p: Option<std::path::PathBuf>) {
686 self.backup_dir = p;
687 }
688 fn backup_dir(&self) -> Option<&std::path::PathBuf> {
689 self.backup_dir.as_ref()
690 }
691 fn is_dry_run(&self) -> bool {
692 self.dry_run
693 }
694}
695
696impl FixArgs {
697 pub fn target_or_default(&self) -> crate::transcoder::TargetEncoding {
699 self.target
700 .unwrap_or(crate::transcoder::TargetEncoding::Utf8)
701 }
702}
703
704fn merge_convert_config<C: ConvertOptions + ConvertPeek>(
707 conv: &mut C,
708) -> anyhow::Result<Option<String>> {
709 let recorded = merge_tree_config(conv.common_mut())?;
710 let Some(path) = conv.common_mut().config.clone() else {
711 return Ok(recorded);
712 };
713 let cfg = crate::config::load(&path)?;
714 if conv.target_is_none()
715 && let Some(t) = cfg.target()?
716 {
717 conv.set_target(Some(t));
718 }
719 if conv.backup_is_none()
720 && let Some(dir) = &cfg.convert.backup_dir
721 {
722 conv.set_backup_dir(Some(std::path::PathBuf::from(dir)));
723 }
724 Ok(recorded)
725}
726
727trait ConvertPeek {
730 fn target_is_none(&self) -> bool;
731 fn backup_is_none(&self) -> bool;
732}
733
734impl ConvertPeek for ConvertArgs {
735 fn target_is_none(&self) -> bool {
736 self.target.is_none()
737 }
738 fn backup_is_none(&self) -> bool {
739 self.backup_dir.is_none()
740 }
741}
742
743impl ConvertPeek for FixArgs {
744 fn target_is_none(&self) -> bool {
745 self.target.is_none()
746 }
747 fn backup_is_none(&self) -> bool {
748 self.backup_dir.is_none()
749 }
750}
751
752fn ensure_root(root: &Path) -> anyhow::Result<()> {
754 if !root.is_dir() {
755 bail!("root `{}` is not an existing directory", root.display());
756 }
757 Ok(())
758}
759
760fn ensure_backup_dir(args: &impl ConvertOptions) -> anyhow::Result<()> {
769 let Some(dir) = args.backup_dir() else {
770 return Ok(());
771 };
772 let root_canonical = fs::canonicalize(&args.common().root)?;
773 check_backup_placement(dir, &root_canonical)?;
774 if args.is_dry_run() {
775 return Ok(());
776 }
777 fs::create_dir_all(dir)
778 .with_context(|| format!("cannot create backup dir {}", dir.display()))?;
779 ensure_writable_dir(dir)?;
780 Ok(())
781}
782
783fn check_backup_placement(dir: &Path, root_canonical: &Path) -> anyhow::Result<()> {
787 let dir = if dir.is_absolute() {
791 dir.to_path_buf()
792 } else {
793 std::env::current_dir()
794 .with_context(|| format!("cannot resolve relative --backup-dir `{}`", dir.display()))?
795 .join(dir)
796 };
797 let mut tail: Vec<std::ffi::OsString> = Vec::new();
798 let mut ancestor = dir.to_path_buf();
799 let base = loop {
800 match fs::canonicalize(&ancestor) {
801 Ok(c) => break c,
802 Err(_) => {
803 let Some(name) = ancestor.file_name() else {
804 bail!("--backup-dir `{}` has no existing ancestor", dir.display());
805 };
806 let Some(parent) = ancestor.parent() else {
807 bail!("--backup-dir `{}` has no existing ancestor", dir.display());
808 };
809 tail.push(name.to_os_string());
810 ancestor = parent.to_path_buf();
811 }
812 }
813 };
814 let projected = tail.iter().rev().fold(base, |p, c| p.join(c));
815 if projected.starts_with(root_canonical) {
816 bail!(
817 "--backup-dir `{}` is inside `--root` `{}`; backups would be re-processed on the next run. Keep the backup directory outside the scanned tree.",
818 dir.display(),
819 root_canonical.display()
820 );
821 }
822 Ok(())
823}
824
825fn ensure_report_dir(report: &Path) -> anyhow::Result<()> {
831 if report.is_dir() {
832 bail!("--report `{}` is an existing directory", report.display());
833 }
834 let parent = match report.parent() {
835 Some(p) if !p.as_os_str().is_empty() => p.to_path_buf(),
836 _ => std::path::PathBuf::from("."),
837 };
838 fs::create_dir_all(&parent)
839 .with_context(|| format!("cannot create report directory {}", parent.display()))?;
840 ensure_writable_dir(&parent)?;
844 Ok(())
845}
846
847fn ensure_writable_dir(dir: &Path) -> anyhow::Result<()> {
851 let nanos = std::time::SystemTime::now()
852 .duration_since(std::time::UNIX_EPOCH)
853 .map(|d| d.as_nanos())
854 .unwrap_or(0);
855 let probe = dir.join(format!(
856 ".utf8-forge-probe-{}-{}",
857 std::process::id(),
858 nanos
859 ));
860 match fs::File::create(&probe) {
861 Ok(_) => {
862 let _ = fs::remove_file(&probe);
863 Ok(())
864 }
865 Err(e) => bail!("directory `{}` is not writable: {e}", dir.display()),
866 }
867}
868
869fn skip_paths(report: Option<&Path>, ignore: Option<&Path>) -> Vec<PathBuf> {
872 let mut v = Vec::new();
873 if let Some(p) = report {
874 v.push(p.to_path_buf());
875 }
876 if let Some(p) = ignore {
877 v.push(p.to_path_buf());
878 }
879 v
880}
881
882fn load_ignore(
888 args: &TreeArgs,
889) -> anyhow::Result<(Option<ignorefile::IgnoreFile>, Option<String>, Vec<String>)> {
890 if args.no_ignore_file {
891 return Ok((None, None, Vec::new()));
892 }
893 match &args.ignore_file {
894 Some(path) => {
895 if !path.is_file() {
896 bail!("ignore file `{}` not found", path.display());
897 }
898 let rules = ignorefile::IgnoreFile::load(path).map_err(anyhow::Error::msg)?;
899 let recorded = path.to_string_lossy().into_owned();
900 Ok((Some(rules), Some(recorded), Vec::new()))
901 }
902 None => {
903 let path = args.root.join(".utf8forgeignore");
904 if !path.is_file() {
905 return Ok((None, None, Vec::new()));
906 }
907 match ignorefile::IgnoreFile::load(&path) {
908 Ok(rules) => {
909 let recorded = path.to_string_lossy().into_owned();
910 Ok((Some(rules), Some(recorded), Vec::new()))
911 }
912 Err(e) => Ok((
913 None,
914 None,
915 vec![format!(
916 "warning: ignoring unreadable .utf8forgeignore: {e}"
917 )],
918 )),
919 }
920 }
921 }
922}
923
924fn wall_now() -> String {
927 crate::reporter::rfc3339_now()
928}
929
930fn with_pool<R: Send>(threads: Option<usize>, f: impl FnOnce() -> R + Send) -> anyhow::Result<R> {
932 match threads {
933 Some(n) => {
934 let pool = rayon::ThreadPoolBuilder::new()
935 .num_threads(n.max(1))
936 .build()
937 .context("failed to build rayon thread pool")?;
938 Ok(pool.install(f))
939 }
940 None => Ok(f()),
941 }
942}
943
944fn console_cfg(args: &TreeArgs) -> ConsoleCfg {
945 ConsoleCfg {
946 quiet: args.quiet,
947 verbose: args.verbose,
948 }
949}
950
951fn print_warnings(warnings: &[String], console: ConsoleCfg) {
953 if !console.quiet {
954 for w in warnings {
955 print_problem(w.clone());
956 }
957 }
958}
959
960fn cmd_scan(args: &TreeArgs) -> anyhow::Result<i32> {
967 let mut args = args.clone();
968 let config_file = merge_tree_config(&mut args)?;
969 ensure_root(&args.root)?;
970 let filter = build_filter(&args)?;
971 if let Some(path) = &args.report {
972 ensure_report_dir(path)?;
973 }
974 let console = console_cfg(&args);
975 print_header(console, format!("mode=scan root={}", args.root.display()));
976
977 let (ignore, ignore_recorded, ignore_warnings) = load_ignore(&args)?;
978 let mut warnings = Vec::new();
979 let walk = {
980 let skip = skip_paths(
981 args.report.as_deref(),
982 ignore_recorded
983 .as_deref()
984 .map(std::path::PathBuf::from)
985 .as_deref(),
986 );
987 let walk = collect_files(&args.root, &filter, &skip, ignore.as_ref());
988 warnings.extend(ignore_warnings);
989 walk
990 };
991 warnings.extend(walk.warnings);
992 print_warnings(&warnings, console);
993 let started_at = wall_now();
994 let started = Instant::now();
995 let records = with_pool(args.threads, || {
996 walk.files
997 .par_iter()
998 .map(|p| scan_file(p, args.effective_max_file_size()))
999 .collect::<Vec<_>>()
1000 })?;
1001 print_records(&records, console, None);
1002 let elapsed = started.elapsed();
1003
1004 let report = finalize_report(
1005 "scan",
1006 RunFacts {
1007 root: Some(args.root.clone()),
1008 url: None,
1009 options: options_block(
1010 &args,
1011 None,
1012 &filter,
1013 config_file.as_deref(),
1014 ignore_recorded.as_deref(),
1015 ),
1016 started_at,
1017 verify_failed: None,
1018 },
1019 records,
1020 elapsed,
1021 );
1022 let unknown = match &report.summary {
1023 Summary::Scan(s) => s.unknown,
1024 _ => 0,
1025 };
1026 let file_errors = report.files.iter().filter(|r| r.action == "error").count() as u64;
1029 if let Some(path) = &args.report {
1030 write_report(&report, path)?;
1031 }
1032 if let Summary::Scan(s) = &report.summary {
1033 print_scan_summary(s, args.report.as_deref(), elapsed, console);
1034 }
1035 Ok(if unknown > 0 || file_errors > 0 { 1 } else { 0 })
1036}
1037
1038fn cmd_convert(args: &ConvertArgs) -> anyhow::Result<i32> {
1040 #[cfg(feature = "remote")]
1041 {
1042 if let Some(url) = &args.url {
1043 return cmd_convert_url(args, url);
1044 }
1045 }
1046 #[cfg(not(feature = "remote"))]
1047 {
1048 if args.url.is_some() {
1049 bail!("--url requires the `remote` feature; rebuild with default features");
1050 }
1051 }
1052 cmd_convert_tree(args)
1053}
1054
1055fn cmd_convert_tree(args: &ConvertArgs) -> anyhow::Result<i32> {
1058 let mut args = args.clone();
1059 let config_file = merge_convert_config(&mut args)?;
1060 let common = &args.common;
1061 let target = args.target_or_default();
1062 ensure_root(&common.root)?;
1063 let filter = build_filter(common)?;
1064 ensure_backup_dir(&args)?;
1065 if let Some(path) = &common.report {
1066 ensure_report_dir(path)?;
1067 }
1068 let console = console_cfg(common);
1069 let dry_tag = if args.dry_run { " dry_run=true" } else { "" };
1070 print_header(
1071 console,
1072 format!(
1073 "mode=convert target={} root={}{}",
1074 target,
1075 common.root.display(),
1076 dry_tag
1077 ),
1078 );
1079
1080 let (ignore, ignore_recorded, ignore_warnings) = load_ignore(common)?;
1081 let mut warnings = ignore_warnings;
1082 let walk = {
1083 let skip = skip_paths(
1084 common.report.as_deref(),
1085 ignore_recorded
1086 .as_deref()
1087 .map(std::path::PathBuf::from)
1088 .as_deref(),
1089 );
1090 collect_files(&common.root, &filter, &skip, ignore.as_ref())
1091 };
1092 warnings.extend(walk.warnings);
1093 print_warnings(&warnings, console);
1094 let ctx = ConvertCtx {
1095 root: common.root.clone(),
1096 target,
1097 dry_run: args.dry_run,
1098 backup_dir: args.backup_dir.clone(),
1099 max_file_size: common.effective_max_file_size(),
1100 };
1101 let started_at = wall_now();
1102 let started = Instant::now();
1103 let records = with_pool(common.threads, || {
1104 walk.files
1105 .par_iter()
1106 .map(|p| convert_file(p, &ctx))
1107 .collect::<Vec<_>>()
1108 })?;
1109 print_records(&records, console, Some(target.tag()));
1110 let elapsed = started.elapsed();
1111
1112 let report = finalize_report(
1113 "convert",
1114 RunFacts {
1115 root: Some(common.root.clone()),
1116 url: None,
1117 options: options_block(
1118 common,
1119 Some(&args as &dyn ConvertOptions),
1120 &filter,
1121 config_file.as_deref(),
1122 ignore_recorded.as_deref(),
1123 ),
1124 started_at,
1125 verify_failed: None,
1126 },
1127 records,
1128 elapsed,
1129 );
1130 let summary = match &report.summary {
1131 Summary::Convert(s) => s.clone(),
1132 _ => ConvertSummary::default(),
1133 };
1134 if let Some(path) = &common.report {
1135 write_report(&report, path)?;
1136 }
1137 print_convert_summary(&summary, common.report.as_deref(), elapsed, console);
1138 Ok(
1139 if summary.unknown > 0 || summary.decode_errors > 0 || summary.io_errors > 0 {
1140 1
1141 } else {
1142 0
1143 },
1144 )
1145}
1146
1147fn cmd_verify(args: &TreeArgs) -> anyhow::Result<i32> {
1150 let mut args = args.clone();
1151 let config_file = merge_tree_config(&mut args)?;
1152 ensure_root(&args.root)?;
1153 let filter = build_filter(&args)?;
1154 if let Some(path) = &args.report {
1155 ensure_report_dir(path)?;
1156 }
1157 let console = console_cfg(&args);
1158 print_header(console, format!("mode=verify root={}", args.root.display()));
1159
1160 let (ignore, ignore_recorded, ignore_warnings) = load_ignore(&args)?;
1161 let mut warnings = Vec::new();
1162 let walk = {
1163 let skip = skip_paths(
1164 args.report.as_deref(),
1165 ignore_recorded
1166 .as_deref()
1167 .map(std::path::PathBuf::from)
1168 .as_deref(),
1169 );
1170 let walk = collect_files(&args.root, &filter, &skip, ignore.as_ref());
1171 warnings.extend(ignore_warnings);
1172 walk
1173 };
1174 print_warnings(&walk.warnings, console);
1175 let started_at = wall_now();
1176 let started = Instant::now();
1177 let records = with_pool(args.threads, || {
1178 walk.files
1179 .par_iter()
1180 .map(|p| verify_file(p, args.effective_max_file_size()))
1181 .collect::<Vec<_>>()
1182 })?;
1183 print_records(&records, console, None);
1184 let elapsed = started.elapsed();
1185
1186 let report = finalize_report(
1187 "verify",
1188 RunFacts {
1189 root: Some(args.root.clone()),
1190 url: None,
1191 options: options_block(
1192 &args,
1193 None,
1194 &filter,
1195 config_file.as_deref(),
1196 ignore_recorded.as_deref(),
1197 ),
1198 started_at,
1199 verify_failed: None,
1200 },
1201 records,
1202 elapsed,
1203 );
1204 let summary = match &report.summary {
1205 Summary::Verify(s) => s.clone(),
1206 _ => VerifySummary::default(),
1207 };
1208 if let Some(path) = &args.report {
1209 write_report(&report, path)?;
1210 }
1211 if !console.quiet {
1212 println!(
1213 "[utf8-forge] checked={} passed={} failed={}",
1214 summary.total_files, summary.passed, summary.failed
1215 );
1216 }
1217 print_duration(args.report.as_deref(), elapsed, console);
1218 Ok(if summary.failed > 0 { 3 } else { 0 })
1219}
1220
1221#[cfg(feature = "remote")]
1230fn cmd_convert_url(args: &ConvertArgs, url: &str) -> anyhow::Result<i32> {
1231 let common = &args.common;
1232 if args.backup_dir.is_some() {
1233 bail!("--backup-dir is not supported with --url");
1234 }
1235 let console = console_cfg(common);
1236 print_header(
1237 console,
1238 format!("mode=fetch target={} url={url}", args.target_or_default()),
1239 );
1240 let started_at = wall_now();
1241 let started = Instant::now();
1242 let out_path = args
1243 .output
1244 .clone()
1245 .unwrap_or_else(|| fetcher::derive_output_path(url));
1246
1247 let record = match fetcher::fetch_bytes(url, common.effective_max_file_size()) {
1250 Err(e) => {
1251 let action = match e {
1255 ForgeError::TooLarge { .. } => "skipped_too_large",
1256 _ => "error",
1257 };
1258 if action == "skipped_too_large" {
1262 print_problem(format!("skipped_too_large {url} ({}: {e})", e.category()));
1263 }
1264 RecBuilder::new(&out_path).done(
1265 None,
1266 action,
1267 None,
1268 None,
1269 Some(format!("{}: {e}", e.category())),
1270 )
1271 }
1272 Ok(bytes) => {
1273 let raw_len = bytes.len() as u64;
1274 let det = detect(&bytes);
1275 let tag = det.tag();
1276 match transcode_detected(&bytes, det, args.target_or_default()) {
1277 Err(e) => {
1278 print_problem(format!("error {url} ({}: {e})", e.category()));
1279 RecBuilder::new(&out_path).done(
1280 Some(tag),
1281 "error",
1282 Some(raw_len),
1283 None,
1284 Some(format!("{}: {e}", e.category())),
1285 )
1286 }
1287 Ok(outcome) => {
1288 let new_bytes = match outcome {
1289 TranscodeOutcome::Unchanged => bytes,
1290 TranscodeOutcome::Changed(v) => v,
1291 };
1292 if fs::read(&out_path).is_ok_and(|existing| existing == new_bytes) {
1295 RecBuilder::new(&out_path).done(
1296 Some(tag),
1297 "unchanged",
1298 Some(raw_len),
1299 Some(new_bytes.len() as u64),
1300 None,
1301 )
1302 } else if args.dry_run {
1303 RecBuilder::new(&out_path).done(
1304 Some(tag),
1305 "would_convert",
1306 Some(raw_len),
1307 Some(new_bytes.len() as u64),
1308 None,
1309 )
1310 } else {
1311 if let Some(parent) = out_path.parent()
1312 && !parent.as_os_str().is_empty()
1313 {
1314 fs::create_dir_all(parent).with_context(|| {
1315 format!("cannot create output dir {}", parent.display())
1316 })?;
1317 }
1318 match writer::atomic_write(&out_path, &new_bytes) {
1319 Ok(()) => RecBuilder::new(&out_path).done(
1320 Some(tag),
1321 "converted",
1322 Some(raw_len),
1323 Some(new_bytes.len() as u64),
1324 None,
1325 ),
1326 Err(e) => RecBuilder::new(&out_path).done(
1327 Some(tag),
1328 "error",
1329 Some(raw_len),
1330 None,
1331 Some(format!("{}: write failed: {e}", e.category())),
1332 ),
1333 }
1334 }
1335 }
1336 }
1337 }
1338 };
1339 let elapsed = started.elapsed();
1340
1341 let options = OptionsBlock {
1342 target: args.target_or_default().tag(),
1343 dry_run: args.dry_run,
1344 extensions: Vec::new(),
1345 exclude_dirs: Vec::new(),
1346 exclude_ext: Vec::new(),
1347 exclude_globs: Vec::new(),
1348 backup_dir: None,
1349 config_file: None,
1350 ignore_file: None,
1351 };
1352 let report = finalize_report(
1353 "fetch",
1354 RunFacts {
1355 root: None,
1356 url: Some(url.to_string()),
1357 options,
1358 started_at,
1359 verify_failed: None,
1360 },
1361 vec![record],
1362 elapsed,
1363 );
1364 let summary = match &report.summary {
1365 Summary::Convert(s) => s.clone(),
1366 _ => ConvertSummary::default(),
1367 };
1368 print_records(
1369 std::slice::from_ref(&report.files[0]),
1370 console,
1371 Some(args.target_or_default().tag()),
1372 );
1373 if let Some(path) = &common.report {
1374 write_report(&report, path)?;
1375 }
1376 print_convert_summary(&summary, common.report.as_deref(), elapsed, console);
1377 Ok(
1380 if summary.unknown > 0
1381 || summary.decode_errors > 0
1382 || summary.io_errors > 0
1383 || summary.fetch_error > 0
1384 || summary.too_large > 0
1385 {
1386 1
1387 } else {
1388 0
1389 },
1390 )
1391}
1392
1393fn cmd_fix(args: &FixArgs) -> anyhow::Result<i32> {
1405 let mut args = args.clone();
1406 let config_file = merge_convert_config(&mut args)?;
1407 let common = &args.common;
1408 let target = args.target_or_default();
1409 ensure_root(&common.root)?;
1410 let filter = build_filter(common)?;
1411 ensure_backup_dir(&args)?;
1412 if let Some(path) = &common.report {
1413 ensure_report_dir(path)?;
1414 }
1415 let console = console_cfg(common);
1416 let dry_tag = if args.dry_run { " dry_run=true" } else { "" };
1417 print_header(
1418 console,
1419 format!(
1420 "mode=fix target={} root={}{}",
1421 target,
1422 common.root.display(),
1423 dry_tag
1424 ),
1425 );
1426
1427 let (ignore, ignore_recorded, ignore_warnings) = load_ignore(common)?;
1428 let mut warnings = ignore_warnings;
1429 let walk = {
1430 let skip = skip_paths(
1431 common.report.as_deref(),
1432 ignore_recorded.as_deref().map(PathBuf::from).as_deref(),
1433 );
1434 collect_files(&common.root, &filter, &skip, ignore.as_ref())
1435 };
1436 warnings.extend(walk.warnings);
1437 print_warnings(&warnings, console);
1438
1439 let started_at = wall_now();
1440 let started = Instant::now();
1441 let ctx = ConvertCtx {
1442 root: common.root.clone(),
1443 target,
1444 dry_run: args.dry_run,
1445 backup_dir: args.backup_dir.clone(),
1446 max_file_size: common.effective_max_file_size(),
1447 };
1448 let convert_records = with_pool(common.threads, || {
1449 walk.files
1450 .par_iter()
1451 .map(|p| convert_file(p, &ctx))
1452 .collect::<Vec<_>>()
1453 })?;
1454 print_records(&convert_records, console, Some(target.tag()));
1455
1456 let verify_records = with_pool(common.threads, || {
1459 walk.files
1460 .par_iter()
1461 .map(|p| verify_file(p, common.effective_max_file_size()))
1462 .collect::<Vec<_>>()
1463 })?;
1464 let mut verify_failed: Vec<String> = verify_records
1465 .iter()
1466 .filter(|r| r.action == "failed")
1467 .map(|r| r.path.clone())
1468 .collect();
1469 verify_failed.sort();
1470 for r in &verify_records {
1471 if r.action == "failed" {
1472 let reason = r
1473 .error
1474 .clone()
1475 .unwrap_or_else(|| format!("detected={}", r.detected.unwrap_or("?")));
1476 print_problem(format!("failed {} ({reason})", r.path));
1477 }
1478 }
1479 let elapsed = started.elapsed();
1480
1481 let mut report = finalize_report(
1482 "fix",
1483 RunFacts {
1484 root: Some(common.root.clone()),
1485 url: None,
1486 options: options_block(
1487 common,
1488 Some(&args as &dyn ConvertOptions),
1489 &filter,
1490 config_file.as_deref(),
1491 ignore_recorded.as_deref(),
1492 ),
1493 started_at,
1494 verify_failed: Some(verify_failed.clone()),
1495 },
1496 convert_records,
1497 elapsed,
1498 );
1499 let verify_failed_count = verify_failed.len() as u64;
1502 if let Summary::Fix(f) = &mut report.summary {
1503 f.passed = verify_records
1504 .iter()
1505 .filter(|r| r.action == "passed")
1506 .count() as u64;
1507 f.failed = verify_failed_count;
1508 }
1509 let convert_issues = match &report.summary {
1510 Summary::Fix(f) => f.unknown + f.decode_errors + f.io_errors,
1511 _ => 0,
1512 };
1513 if let Some(path) = &common.report {
1514 write_report(&report, path)?;
1515 }
1516 if let Summary::Fix(f) = &report.summary
1517 && !console.quiet
1518 {
1519 println!(
1520 "[utf8-forge] scanned={} candidates={}",
1521 f.total_files, f.candidates
1522 );
1523 println!(
1524 "[utf8-forge] already_utf8={} converted={} unknown={} errors={}",
1525 f.already_utf8,
1526 f.converted,
1527 f.unknown,
1528 f.decode_errors + f.io_errors
1529 );
1530 if f.too_large > 0 {
1531 println!("[utf8-forge] too_large={}", f.too_large);
1532 }
1533 println!(
1534 "[utf8-forge] verify: checked={} passed={} failed={}",
1535 f.passed + f.failed,
1536 f.passed,
1537 f.failed
1538 );
1539 }
1540 print_duration(common.report.as_deref(), elapsed, console);
1541 Ok(if verify_failed_count > 0 {
1543 3
1544 } else if convert_issues > 0 {
1545 1
1546 } else {
1547 0
1548 })
1549}
1550
1551fn cmd_diff(args: &DiffArgs) -> anyhow::Result<i32> {
1555 let load = |p: &Path, flag: &str| -> anyhow::Result<DiffInput> {
1556 let text = fs::read_to_string(p)
1557 .with_context(|| format!("cannot load {flag} report `{}`", p.display()))?;
1558 serde_json::from_str(&text)
1559 .with_context(|| format!("cannot load {flag} report `{}`", p.display()))
1560 };
1561 let before = load(&args.before, "--before")?;
1562 let after = load(&args.after, "--after")?;
1563 if let (Some(r1), Some(r2)) = (&before.root, &after.root)
1564 && r1 != r2
1565 {
1566 print_problem(format!(
1567 "warning: roots differ (`{r1}` vs `{r2}`); path comparison assumes identical roots"
1568 ));
1569 }
1570
1571 let mut doc = differ::compare(&before, &after);
1572 doc.before = args.before.to_string_lossy().into_owned();
1573 doc.after = args.after.to_string_lossy().into_owned();
1574 let summary = &doc.summary;
1575
1576 if let Some(path) = &args.report {
1577 ensure_report_dir(path)?;
1578 let json = serde_json::to_string_pretty(&doc).context("diff serialization failed")?;
1579 writer::atomic_write(path, (json + "\n").as_bytes())
1580 .with_context(|| format!("cannot write diff report {}", path.display()))?;
1581 println!(
1582 "[utf8-forge] diff: added={} removed={} changed={} unchanged={} report={}",
1583 summary.added,
1584 summary.removed,
1585 summary.action_changed,
1586 summary.unchanged,
1587 path.display()
1588 );
1589 } else {
1590 println!(
1591 "[utf8-forge] diff: added={} removed={} changed={} unchanged={}",
1592 summary.added, summary.removed, summary.action_changed, summary.unchanged
1593 );
1594 let json = serde_json::to_string_pretty(&doc).context("diff serialization failed")?;
1595 println!("{json}");
1596 }
1597 let drifted = summary.added + summary.removed + summary.action_changed;
1598 Ok(if args.fail_on_change && drifted > 0 {
1599 1
1600 } else {
1601 0
1602 })
1603}
1604
1605#[cfg(test)]
1606mod backup_placement_tests {
1607 use super::check_backup_placement;
1608 use std::path::Path;
1609
1610 #[test]
1611 fn relative_backup_dir_resolves_against_cwd() {
1612 let cwd = std::fs::canonicalize(std::env::current_dir().unwrap()).unwrap();
1617 check_backup_placement(Path::new("backup"), &cwd.join("elsewhere-root")).unwrap();
1620 check_backup_placement(Path::new("a/b/c"), &cwd.join("elsewhere-root")).unwrap();
1622 let err = check_backup_placement(Path::new("backup"), &cwd).unwrap_err();
1624 assert!(err.to_string().contains("inside"), "{err}");
1625 }
1626}