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 + too_large == candidates`.
85    pub errors: u64,
86    pub too_large: u64,
87}
88
89/// `convert` / `fetch` summary.
90///
91/// `already_utf8` counts files whose bytes were already byte-identical at the
92/// selected target encoding (`action == "unchanged"`) — the name is
93/// historical and matches the default UTF-8 target.
94#[derive(Debug, Clone, Serialize, Default)]
95pub struct ConvertSummary {
96    pub total_files: u64,
97    pub candidates: u64,
98    pub already_utf8: u64,
99    pub converted: u64,
100    pub unknown: u64,
101    pub decode_errors: u64,
102    pub io_errors: u64,
103    pub too_large: u64,
104    pub fetch_error: u64,
105}
106
107/// `verify` summary.
108#[derive(Debug, Clone, Serialize, Default)]
109pub struct VerifySummary {
110    pub total_files: u64,
111    pub candidates: u64,
112    pub passed: u64,
113    pub failed: u64,
114}
115
116/// `fix` summary: convert counters plus the verify gate result on the same
117/// tree. `fetch_error` is impossible in fix mode and is omitted.
118#[derive(Debug, Clone, Serialize, Default)]
119pub struct FixSummary {
120    pub total_files: u64,
121    pub candidates: u64,
122    pub already_utf8: u64,
123    pub converted: u64,
124    pub unknown: u64,
125    pub decode_errors: u64,
126    pub io_errors: u64,
127    pub too_large: u64,
128    /// Verify pass count on the same tree.
129    pub passed: u64,
130    /// Verify fail count on the same tree (the fix gate).
131    pub failed: u64,
132}
133
134/// Mode-specific summary, serialized inline (untagged).
135#[derive(Debug, Serialize)]
136#[serde(untagged)]
137pub enum Summary {
138    Scan(ScanSummary),
139    Convert(ConvertSummary),
140    Verify(VerifySummary),
141    Fix(FixSummary),
142}
143
144/// Full JSON report document.
145#[derive(Debug, Serialize)]
146pub struct Report {
147    pub tool: &'static str,
148    pub version: &'static str,
149    pub mode: &'static str,
150    #[serde(skip_serializing_if = "Option::is_none")]
151    pub root: Option<String>,
152    #[serde(skip_serializing_if = "Option::is_none")]
153    pub url: Option<String>,
154    pub started_at: String,
155    pub duration_ms: u64,
156    pub options: OptionsBlock,
157    pub summary: Summary,
158    pub files: Vec<FileRecord>,
159    pub unknown_files: Vec<String>,
160    pub error_files: Vec<String>,
161    /// Paths whose verify record is `failed` (fix mode only). Omitted when
162    /// the gate is clean, so other modes stay schema-compatible.
163    #[serde(skip_serializing_if = "Vec::is_empty")]
164    pub verify_failed_files: Vec<String>,
165}
166
167/// Format a unix timestamp as RFC 3339 UTC (`1970-01-01T00:00:00Z` style).
168/// `chrono` is deliberately not a dependency; the civil-from-days algorithm
169/// is well-known and unit-tested.
170pub fn rfc3339_from_secs(secs: u64) -> String {
171    let days = (secs / 86_400) as i64;
172    let rem = secs % 86_400;
173    let (y, m, d) = civil_from_days(days);
174    format!(
175        "{y:04}-{m:02}-{d:02}T{:02}:{:02}:{:02}Z",
176        rem / 3_600,
177        (rem % 3_600) / 60,
178        rem % 60
179    )
180}
181
182/// Current wall-clock time as RFC 3339 UTC.
183pub fn rfc3339_now() -> String {
184    let secs = SystemTime::now()
185        .duration_since(UNIX_EPOCH)
186        .map(|d| d.as_secs())
187        .unwrap_or(0);
188    rfc3339_from_secs(secs)
189}
190
191/// Howard Hinnant's `civil_from_days`: days since 1970-01-01 → (y, m, d).
192fn civil_from_days(z: i64) -> (i64, u32, u32) {
193    let z = z + 719_468;
194    let era = z.div_euclid(146_097);
195    let doe = z.rem_euclid(146_097);
196    let yoe = (doe - doe / 1_460 + doe / 36_524 - doe / 146_096) / 365;
197    let y = yoe + era * 400;
198    let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
199    let mp = (5 * doy + 2) / 153;
200    let d = (doy - (153 * mp + 2) / 5 + 1) as u32;
201    let m = if mp < 10 { mp + 3 } else { mp - 9 } as u32;
202    (if m <= 2 { y + 1 } else { y }, m, d)
203}
204
205/// Console verbosity settings.
206#[derive(Debug, Clone, Copy, Default)]
207pub struct ConsoleCfg {
208    /// Errors only.
209    pub quiet: bool,
210    /// Per-file detail lines on stdout.
211    pub verbose: bool,
212}
213
214/// Print the mode header line.
215pub fn print_header(cfg: ConsoleCfg, line: String) {
216    if !cfg.quiet {
217        println!("[utf8-forge] {line}");
218    }
219}
220
221/// Print a per-file verbose line (stdout, `-v` only).
222pub fn print_verbose(cfg: ConsoleCfg, line: String) {
223    if cfg.verbose && !cfg.quiet {
224        println!("[utf8-forge] {line}");
225    }
226}
227
228/// Print a per-file problem line (stderr, always shown).
229pub fn print_problem(line: String) {
230    eprintln!("[utf8-forge] {line}");
231}
232
233/// Serialize the report and write it next to a trailing newline.
234pub fn write_report(report: &Report, path: &Path) -> anyhow::Result<()> {
235    if let Some(parent) = path.parent()
236        && !parent.as_os_str().is_empty()
237    {
238        fs::create_dir_all(parent)
239            .with_context(|| format!("cannot create report directory {}", parent.display()))?;
240    }
241    // Same crash-safety contract as source writes: temp file + rename, so a
242    // crash mid-write leaves the previous report intact.
243    let json = serde_json::to_string_pretty(report).context("report serialization failed")?;
244    crate::writer::atomic_write(path, (json + "\n").as_bytes())
245        .with_context(|| format!("cannot write report {}", path.display()))?;
246    Ok(())
247}
248
249#[cfg(test)]
250mod tests {
251    use super::*;
252
253    #[test]
254    fn rfc3339_known_timestamps() {
255        assert_eq!(rfc3339_from_secs(0), "1970-01-01T00:00:00Z");
256        assert_eq!(rfc3339_from_secs(86_399), "1970-01-01T23:59:59Z");
257        assert_eq!(rfc3339_from_secs(86_400), "1970-01-02T00:00:00Z");
258        // 2024-02-29 leap day: 2024-01-01 is day 19723.
259        assert_eq!(rfc3339_from_secs(19_782 * 86_400), "2024-02-29T00:00:00Z");
260        // Epoch day 20_000 = 2024-10-04.
261        assert_eq!(rfc3339_from_secs(20_000 * 86_400), "2024-10-04T00:00:00Z");
262    }
263
264    #[test]
265    fn rfc3339_now_is_recent() {
266        // Sanity: current date must be after 2026-01-01 (this tool's era).
267        let s = rfc3339_now();
268        assert!(s.starts_with("202"), "unexpected timestamp {s}");
269    }
270}