Skip to main content

utf8_forge/
reporter.rs

1//! Console output + JSON reports (`DESIGN.md §9`, `EXECUTION.md §12`).
2//!
3//! Report guarantees:
4//! - `files[]` is sorted by `path` (invariant #8).
5//! - Schema matches `EXECUTION.md §12`; mode-specific summaries are emitted
6//!   via an untagged enum so each mode serializes exactly its own fields.
7
8use std::fs;
9use std::path::Path;
10use std::time::{SystemTime, UNIX_EPOCH};
11
12use anyhow::Context;
13use serde::Serialize;
14
15/// A single processed file in the report.
16#[derive(Debug, Clone, Serialize)]
17pub struct FileRecord {
18    pub path: String,
19    /// Detection tag (`utf-8`, `gb18030`, ...); `None` when unreadable.
20    #[serde(skip_serializing_if = "Option::is_none")]
21    pub detected: Option<&'static str>,
22    /// `would_convert` | `converted` | `unchanged` | `skipped_unknown` |
23    /// `skipped_too_large` | `error` | `detected` | `passed` | `failed`.
24    pub action: &'static str,
25    #[serde(skip_serializing_if = "Option::is_none")]
26    pub bytes_before: Option<u64>,
27    #[serde(skip_serializing_if = "Option::is_none")]
28    pub bytes_after: Option<u64>,
29    pub duration_us: u64,
30    #[serde(skip_serializing_if = "Option::is_none")]
31    pub error: Option<String>,
32}
33
34impl FileRecord {
35    /// Start a record for `path`; remaining fields are filled by the
36    /// per-file processors.
37    pub fn new(path: &Path) -> FileRecord {
38        FileRecord {
39            path: path.to_string_lossy().into_owned(),
40            detected: None,
41            action: "error",
42            bytes_before: None,
43            bytes_after: None,
44            duration_us: 0,
45            error: None,
46        }
47    }
48}
49
50/// Effective CLI options snapshot (`EXECUTION.md §12 options`).
51#[derive(Debug, Serialize)]
52pub struct OptionsBlock {
53    pub target: &'static str,
54    pub dry_run: bool,
55    pub extensions: Vec<String>,
56    pub exclude_dirs: Vec<String>,
57    #[serde(skip_serializing_if = "Vec::is_empty")]
58    pub exclude_ext: Vec<String>,
59    #[serde(skip_serializing_if = "Vec::is_empty")]
60    pub exclude_globs: Vec<String>,
61    #[serde(skip_serializing_if = "Option::is_none")]
62    pub backup_dir: Option<String>,
63}
64
65/// `scan` summary: encoding distribution (`EXECUTION.md §3.1`).
66#[derive(Debug, Clone, Serialize, Default)]
67pub struct ScanSummary {
68    pub total_files: u64,
69    pub candidates: u64,
70    pub utf8: u64,
71    pub utf8_bom: u64,
72    pub utf16le: u64,
73    pub utf16be: u64,
74    pub gb18030: u64,
75    pub unknown: u64,
76    pub too_large: u64,
77}
78
79/// `convert` / `fetch` summary (`EXECUTION.md §12`).
80///
81/// `already_utf8` counts files whose bytes were already at the target
82/// encoding (`action == "unchanged"`) — the name is historical.
83#[derive(Debug, Clone, Serialize, Default)]
84pub struct ConvertSummary {
85    pub total_files: u64,
86    pub candidates: u64,
87    pub already_utf8: u64,
88    pub converted: u64,
89    pub unknown: u64,
90    pub decode_errors: u64,
91    pub io_errors: u64,
92    pub too_large: u64,
93    pub fetch_error: u64,
94}
95
96/// `verify` summary.
97#[derive(Debug, Clone, Serialize, Default)]
98pub struct VerifySummary {
99    pub total_files: u64,
100    pub candidates: u64,
101    pub passed: u64,
102    pub failed: u64,
103}
104
105/// Mode-specific summary, serialized inline (untagged).
106#[derive(Debug, Serialize)]
107#[serde(untagged)]
108pub enum Summary {
109    Scan(ScanSummary),
110    Convert(ConvertSummary),
111    Verify(VerifySummary),
112}
113
114/// Full JSON report document.
115#[derive(Debug, Serialize)]
116pub struct Report {
117    pub tool: &'static str,
118    pub version: &'static str,
119    pub mode: &'static str,
120    #[serde(skip_serializing_if = "Option::is_none")]
121    pub root: Option<String>,
122    #[serde(skip_serializing_if = "Option::is_none")]
123    pub url: Option<String>,
124    pub started_at: String,
125    pub duration_ms: u64,
126    pub options: OptionsBlock,
127    pub summary: Summary,
128    pub files: Vec<FileRecord>,
129    pub unknown_files: Vec<String>,
130    pub error_files: Vec<String>,
131}
132
133/// Format a unix timestamp as RFC 3339 UTC (`1970-01-01T00:00:00Z` style).
134/// `chrono` is deliberately not a dependency; the civil-from-days algorithm
135/// is well-known and unit-tested.
136pub fn rfc3339_from_secs(secs: u64) -> String {
137    let days = (secs / 86_400) as i64;
138    let rem = secs % 86_400;
139    let (y, m, d) = civil_from_days(days);
140    format!(
141        "{y:04}-{m:02}-{d:02}T{:02}:{:02}:{:02}Z",
142        rem / 3_600,
143        (rem % 3_600) / 60,
144        rem % 60
145    )
146}
147
148/// Current wall-clock time as RFC 3339 UTC.
149pub fn rfc3339_now() -> String {
150    let secs = SystemTime::now()
151        .duration_since(UNIX_EPOCH)
152        .map(|d| d.as_secs())
153        .unwrap_or(0);
154    rfc3339_from_secs(secs)
155}
156
157/// Howard Hinnant's `civil_from_days`: days since 1970-01-01 → (y, m, d).
158fn civil_from_days(z: i64) -> (i64, u32, u32) {
159    let z = z + 719_468;
160    let era = z.div_euclid(146_097);
161    let doe = z.rem_euclid(146_097);
162    let yoe = (doe - doe / 1_460 + doe / 36_524 - doe / 146_096) / 365;
163    let y = yoe + era * 400;
164    let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
165    let mp = (5 * doy + 2) / 153;
166    let d = (doy - (153 * mp + 2) / 5 + 1) as u32;
167    let m = if mp < 10 { mp + 3 } else { mp - 9 } as u32;
168    (if m <= 2 { y + 1 } else { y }, m, d)
169}
170
171/// Console verbosity settings.
172#[derive(Debug, Clone, Copy, Default)]
173pub struct ConsoleCfg {
174    /// Errors only.
175    pub quiet: bool,
176    /// Per-file detail lines on stdout.
177    pub verbose: bool,
178}
179
180/// Print the mode header line.
181pub fn print_header(cfg: ConsoleCfg, line: String) {
182    if !cfg.quiet {
183        println!("[utf8-forge] {line}");
184    }
185}
186
187/// Print a per-file verbose line (stdout, `-v` only).
188pub fn print_verbose(cfg: ConsoleCfg, line: String) {
189    if cfg.verbose && !cfg.quiet {
190        println!("[utf8-forge] {line}");
191    }
192}
193
194/// Print a per-file problem line (stderr, always shown).
195pub fn print_problem(line: String) {
196    eprintln!("[utf8-forge] {line}");
197}
198
199/// Serialize the report and write it next to a trailing newline.
200pub fn write_report(report: &Report, path: &Path) -> anyhow::Result<()> {
201    if let Some(parent) = path.parent() {
202        if !parent.as_os_str().is_empty() {
203            fs::create_dir_all(parent)
204                .with_context(|| format!("cannot create report directory {}", parent.display()))?;
205        }
206    }
207    let json = serde_json::to_string_pretty(report).context("report serialization failed")?;
208    fs::write(path, json + "\n")
209        .with_context(|| format!("cannot write report {}", path.display()))?;
210    Ok(())
211}
212
213#[cfg(test)]
214mod tests {
215    use super::*;
216
217    #[test]
218    fn rfc3339_known_timestamps() {
219        assert_eq!(rfc3339_from_secs(0), "1970-01-01T00:00:00Z");
220        assert_eq!(rfc3339_from_secs(86_399), "1970-01-01T23:59:59Z");
221        assert_eq!(rfc3339_from_secs(86_400), "1970-01-02T00:00:00Z");
222        // 2024-02-29 leap day: 2024-01-01 is day 19723.
223        assert_eq!(rfc3339_from_secs(19_782 * 86_400), "2024-02-29T00:00:00Z");
224        // Epoch day 20_000 = 2024-10-04.
225        assert_eq!(rfc3339_from_secs(20_000 * 86_400), "2024-10-04T00:00:00Z");
226    }
227
228    #[test]
229    fn rfc3339_now_is_recent() {
230        // Sanity: current date must be after 2026-01-01 (this tool's era).
231        let s = rfc3339_now();
232        assert!(s.starts_with("202"), "unexpected timestamp {s}");
233    }
234}