Skip to main content

utf8_forge/
reporter.rs

1// Copyright 2026 houseme
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15//! Console output + JSON reports.
16//!
17//! Report guarantees:
18//! - `files[]` is sorted by `path`, so audits are reproducible run to run.
19//! - Each mode serializes exactly its own summary fields via an untagged enum
20//!   (`scan` distribution, `convert`/`fetch` counters, `verify` gate).
21
22use std::fs;
23use std::path::Path;
24use std::time::{SystemTime, UNIX_EPOCH};
25
26use anyhow::Context;
27use serde::Serialize;
28
29/// A single processed file in the report.
30#[derive(Debug, Clone, Serialize)]
31pub struct FileRecord {
32    pub path: String,
33    /// Detection tag (`utf-8`, `gb18030`, ...); `None` when unreadable.
34    #[serde(skip_serializing_if = "Option::is_none")]
35    pub detected: Option<&'static str>,
36    /// `would_convert` | `converted` | `unchanged` | `skipped_unknown` |
37    /// `skipped_too_large` | `error` | `detected` | `passed` | `failed`.
38    pub action: &'static str,
39    #[serde(skip_serializing_if = "Option::is_none")]
40    pub bytes_before: Option<u64>,
41    #[serde(skip_serializing_if = "Option::is_none")]
42    pub bytes_after: Option<u64>,
43    pub duration_us: u64,
44    #[serde(skip_serializing_if = "Option::is_none")]
45    pub error: Option<String>,
46}
47
48/// Effective CLI options snapshot, embedded in every JSON report.
49#[derive(Debug, Serialize)]
50pub struct OptionsBlock {
51    pub target: &'static str,
52    pub dry_run: bool,
53    pub extensions: Vec<String>,
54    pub exclude_dirs: Vec<String>,
55    #[serde(skip_serializing_if = "Vec::is_empty")]
56    pub exclude_ext: Vec<String>,
57    #[serde(skip_serializing_if = "Vec::is_empty")]
58    pub exclude_globs: Vec<String>,
59    #[serde(skip_serializing_if = "Option::is_none")]
60    pub backup_dir: Option<String>,
61    /// Config file in effect (`--config` value verbatim); omitted when absent.
62    #[serde(skip_serializing_if = "Option::is_none")]
63    pub config_file: Option<String>,
64    /// Ignore rules in effect (explicit path or auto-discovered
65    /// `<root>/.utf8forgeignore`); omitted when none are active.
66    #[serde(skip_serializing_if = "Option::is_none")]
67    pub ignore_file: Option<String>,
68}
69
70/// `scan` summary: per-encoding distribution counts.
71#[derive(Debug, Clone, Serialize, Default)]
72pub struct ScanSummary {
73    pub total_files: u64,
74    pub candidates: u64,
75    pub utf8: u64,
76    pub utf8_bom: u64,
77    pub utf16le: u64,
78    pub utf16be: u64,
79    pub utf32le: u64,
80    pub utf32be: u64,
81    pub gb18030: u64,
82    pub unknown: u64,
83    /// Files that could not be read (I/O errors); they carry no encoding
84    /// bucket, so `buckets + errors == candidates` (equivalently
85    /// `buckets + errors + too_large == total_files`).
86    pub errors: u64,
87    pub too_large: u64,
88}
89
90/// `convert` / `fetch` summary.
91///
92/// `already_utf8` counts files whose bytes were already byte-identical at the
93/// selected target encoding (`action == "unchanged"`) — the name is
94/// historical and matches the default UTF-8 target.
95#[derive(Debug, Clone, Serialize, Default)]
96pub struct ConvertSummary {
97    pub total_files: u64,
98    pub candidates: u64,
99    pub already_utf8: u64,
100    pub converted: u64,
101    pub unknown: u64,
102    pub decode_errors: u64,
103    /// Content that decodes cleanly but cannot be encoded into the requested
104    /// target without producing unreadable bytes (e.g. the UTF-16LE NUL
105    /// guard); tracked separately from decode and I/O failures.
106    pub encode_errors: u64,
107    pub io_errors: u64,
108    pub too_large: u64,
109    pub fetch_error: u64,
110}
111
112/// `verify` summary.
113#[derive(Debug, Clone, Serialize, Default)]
114pub struct VerifySummary {
115    pub total_files: u64,
116    pub candidates: u64,
117    pub passed: u64,
118    pub failed: u64,
119}
120
121/// `fix` summary: convert counters plus the verify gate result on the same
122/// tree. `fetch_error` is impossible in fix mode and is omitted.
123#[derive(Debug, Clone, Serialize, Default)]
124pub struct FixSummary {
125    pub total_files: u64,
126    pub candidates: u64,
127    pub already_utf8: u64,
128    pub converted: u64,
129    pub unknown: u64,
130    pub decode_errors: u64,
131    /// Same meaning as the convert summary's `encode_errors`.
132    pub encode_errors: u64,
133    pub io_errors: u64,
134    pub too_large: u64,
135    /// Verify pass count on the same tree.
136    pub passed: u64,
137    /// Verify fail count on the same tree (the fix gate).
138    pub failed: u64,
139}
140
141/// Mode-specific summary, serialized inline (untagged).
142#[derive(Debug, Serialize)]
143#[serde(untagged)]
144pub enum Summary {
145    Scan(ScanSummary),
146    Convert(ConvertSummary),
147    Verify(VerifySummary),
148    Fix(FixSummary),
149}
150
151/// Full JSON report document.
152#[derive(Debug, Serialize)]
153pub struct Report {
154    pub tool: &'static str,
155    pub version: &'static str,
156    pub mode: &'static str,
157    #[serde(skip_serializing_if = "Option::is_none")]
158    pub root: Option<String>,
159    #[serde(skip_serializing_if = "Option::is_none")]
160    pub url: Option<String>,
161    pub started_at: String,
162    pub duration_ms: u64,
163    pub options: OptionsBlock,
164    pub summary: Summary,
165    pub files: Vec<FileRecord>,
166    pub unknown_files: Vec<String>,
167    pub error_files: Vec<String>,
168    /// Paths whose verify record is `failed` (fix mode only). Omitted when
169    /// the gate is clean, so other modes stay schema-compatible.
170    #[serde(skip_serializing_if = "Vec::is_empty")]
171    pub verify_failed_files: Vec<String>,
172    /// Non-fatal traversal/ignore warnings (unreadable directories etc.).
173    /// In `verify`/`fix` an unreadable subtree fails the gate, so a non-empty
174    /// list there always accompanies exit code 3. Omitted when empty.
175    #[serde(skip_serializing_if = "Vec::is_empty")]
176    pub warnings: Vec<String>,
177}
178
179/// Format a unix timestamp as RFC 3339 UTC (`1970-01-01T00:00:00Z` style).
180/// `chrono` is deliberately not a dependency; the civil-from-days algorithm
181/// is well-known and unit-tested.
182pub fn rfc3339_from_secs(secs: u64) -> String {
183    let days = (secs / 86_400) as i64;
184    let rem = secs % 86_400;
185    let (y, m, d) = civil_from_days(days);
186    format!(
187        "{y:04}-{m:02}-{d:02}T{:02}:{:02}:{:02}Z",
188        rem / 3_600,
189        (rem % 3_600) / 60,
190        rem % 60
191    )
192}
193
194/// Current wall-clock time as RFC 3339 UTC.
195pub fn rfc3339_now() -> String {
196    let secs = SystemTime::now()
197        .duration_since(UNIX_EPOCH)
198        .map(|d| d.as_secs())
199        .unwrap_or(0);
200    rfc3339_from_secs(secs)
201}
202
203/// Howard Hinnant's `civil_from_days`: days since 1970-01-01 → (y, m, d).
204fn civil_from_days(z: i64) -> (i64, u32, u32) {
205    let z = z + 719_468;
206    let era = z.div_euclid(146_097);
207    let doe = z.rem_euclid(146_097);
208    let yoe = (doe - doe / 1_460 + doe / 36_524 - doe / 146_096) / 365;
209    let y = yoe + era * 400;
210    let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
211    let mp = (5 * doy + 2) / 153;
212    let d = (doy - (153 * mp + 2) / 5 + 1) as u32;
213    let m = if mp < 10 { mp + 3 } else { mp - 9 } as u32;
214    (if m <= 2 { y + 1 } else { y }, m, d)
215}
216
217/// Console verbosity settings.
218#[derive(Debug, Clone, Copy, Default)]
219pub struct ConsoleCfg {
220    /// Errors only.
221    pub quiet: bool,
222    /// Per-file detail lines on stdout.
223    pub verbose: bool,
224}
225
226/// Print the mode header line.
227pub fn print_header(cfg: ConsoleCfg, line: String) {
228    if !cfg.quiet {
229        println!("[utf8-forge] {line}");
230    }
231}
232
233/// Print a per-file verbose line (stdout, `-v` only).
234pub fn print_verbose(cfg: ConsoleCfg, line: String) {
235    if cfg.verbose && !cfg.quiet {
236        println!("[utf8-forge] {line}");
237    }
238}
239
240/// Print a per-file problem line (stderr, always shown).
241pub fn print_problem(line: String) {
242    eprintln!("[utf8-forge] {line}");
243}
244
245/// Serialize the report and write it next to a trailing newline.
246pub fn write_report(report: &Report, path: &Path) -> anyhow::Result<()> {
247    if let Some(parent) = path.parent()
248        && !parent.as_os_str().is_empty()
249    {
250        fs::create_dir_all(parent)
251            .with_context(|| format!("cannot create report directory {}", parent.display()))?;
252    }
253    // Same crash-safety contract as source writes: temp file + rename, so a
254    // crash mid-write leaves the previous report intact.
255    let json = serde_json::to_string_pretty(report).context("report serialization failed")?;
256    crate::writer::atomic_write(path, (json + "\n").as_bytes())
257        .with_context(|| format!("cannot write report {}", path.display()))?;
258    Ok(())
259}
260
261#[cfg(test)]
262mod tests {
263    use super::*;
264
265    #[test]
266    fn rfc3339_known_timestamps() {
267        assert_eq!(rfc3339_from_secs(0), "1970-01-01T00:00:00Z");
268        assert_eq!(rfc3339_from_secs(86_399), "1970-01-01T23:59:59Z");
269        assert_eq!(rfc3339_from_secs(86_400), "1970-01-02T00:00:00Z");
270        // 2024-02-29 leap day: 2024-01-01 is day 19723.
271        assert_eq!(rfc3339_from_secs(19_782 * 86_400), "2024-02-29T00:00:00Z");
272        // Epoch day 20_000 = 2024-10-04.
273        assert_eq!(rfc3339_from_secs(20_000 * 86_400), "2024-10-04T00:00:00Z");
274    }
275
276    #[test]
277    fn rfc3339_now_is_recent() {
278        // Sanity: current date must be after 2026-01-01 (this tool's era).
279        let s = rfc3339_now();
280        assert!(s.starts_with("202"), "unexpected timestamp {s}");
281    }
282}