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//!
22//! # JSON report schema (summary)
23//!
24//! Top level: `tool`, `version`, `mode`, `root` (tree modes) or `url`
25//! (fetch), `started_at`, `duration_ms`, `options`, `summary`, `files[]`,
26//! `unknown_files`, `error_files`, and the omit-when-empty `warnings`,
27//! `verify_failed_files`. The `summary` shape depends on `mode` (scan:
28//! encoding buckets; convert/fetch and fix: outcome counters; verify: gate
29//! counts). Every field of [`FileRecord`], [`OptionsBlock`], the four
30//! summary structs, and [`Report`] itself documents its JSON name; all of
31//! them implement both `Serialize` and `Deserialize`, so downstream tools can
32//! read reports
33//! back without hand-written mirrors. [`Report`]'s `Deserialize` dispatches
34//! on `mode` — the per-mode summaries share field names, so parsing a report
35//! requires knowing its mode.
36//!
37//! Per-file `action` vocabulary (open set across versions — new actions may
38//! appear): [`FILE_ACTIONS`].
39
40use std::fs;
41use std::path::Path;
42use std::time::{SystemTime, UNIX_EPOCH};
43
44use anyhow::Context;
45use serde::{Deserialize, Serialize};
46
47/// Every per-file action the tool currently emits. New actions may appear in
48/// future versions (treat the list as an open set); unknown actions in a
49/// parsed report are not an error.
50pub const FILE_ACTIONS: &[&str] = &[
51    "would_convert",
52    "converted",
53    "unchanged",
54    "skipped_unknown",
55    "skipped_too_large",
56    "error",
57    "detected",
58    "passed",
59    "failed",
60];
61
62/// A single processed file in the report.
63#[derive(Debug, Clone, Serialize, Deserialize)]
64pub struct FileRecord {
65    pub path: String,
66    /// Detection tag (`utf-8`, `gb18030`, ...); `None` when unreadable.
67    #[serde(default, skip_serializing_if = "Option::is_none")]
68    pub detected: Option<String>,
69    /// One of [`FILE_ACTIONS`].
70    pub action: String,
71    #[serde(skip_serializing_if = "Option::is_none")]
72    pub bytes_before: Option<u64>,
73    #[serde(skip_serializing_if = "Option::is_none")]
74    pub bytes_after: Option<u64>,
75    pub duration_us: u64,
76    #[serde(skip_serializing_if = "Option::is_none")]
77    pub error: Option<String>,
78}
79
80/// Effective CLI options snapshot, embedded in every JSON report.
81#[derive(Debug, Clone, Serialize, Deserialize)]
82pub struct OptionsBlock {
83    pub target: String,
84    pub dry_run: bool,
85    pub extensions: Vec<String>,
86    pub exclude_dirs: Vec<String>,
87    #[serde(default, skip_serializing_if = "Vec::is_empty")]
88    pub exclude_ext: Vec<String>,
89    #[serde(default, skip_serializing_if = "Vec::is_empty")]
90    pub exclude_globs: Vec<String>,
91    #[serde(default, skip_serializing_if = "Option::is_none")]
92    pub backup_dir: Option<String>,
93    /// Config file in effect (`--config` value verbatim); omitted when absent.
94    #[serde(default, skip_serializing_if = "Option::is_none")]
95    pub config_file: Option<String>,
96    /// Ignore rules in effect (explicit path or auto-discovered
97    /// `<root>/.utf8forgeignore`); omitted when none are active.
98    #[serde(default, skip_serializing_if = "Option::is_none")]
99    pub ignore_file: Option<String>,
100}
101
102/// `scan` summary: per-encoding distribution counts.
103#[derive(Debug, Clone, Serialize, Deserialize, Default)]
104pub struct ScanSummary {
105    pub total_files: u64,
106    pub candidates: u64,
107    pub utf8: u64,
108    pub utf8_bom: u64,
109    pub utf16le: u64,
110    pub utf16be: u64,
111    pub utf32le: u64,
112    pub utf32be: u64,
113    pub gb18030: u64,
114    pub unknown: u64,
115    /// Files that could not be read (I/O errors); they carry no encoding
116    /// bucket, so `buckets + errors == candidates` (equivalently
117    /// `buckets + errors + too_large == total_files`).
118    pub errors: u64,
119    pub too_large: u64,
120}
121
122/// `convert` / `fetch` summary.
123///
124/// `already_utf8` counts files whose bytes were already byte-identical at the
125/// selected target encoding (`action == "unchanged"`) — the name is
126/// historical and matches the default UTF-8 target.
127#[derive(Debug, Clone, Serialize, Deserialize, Default)]
128pub struct ConvertSummary {
129    pub total_files: u64,
130    pub candidates: u64,
131    pub already_utf8: u64,
132    pub converted: u64,
133    pub unknown: u64,
134    pub decode_errors: u64,
135    /// Content that decodes cleanly but cannot be encoded into the requested
136    /// target without producing unreadable bytes (e.g. the UTF-16LE NUL
137    /// guard); tracked separately from decode and I/O failures.
138    pub encode_errors: u64,
139    pub io_errors: u64,
140    pub too_large: u64,
141    pub fetch_error: u64,
142}
143
144/// `verify` summary.
145#[derive(Debug, Clone, Serialize, Deserialize, Default)]
146pub struct VerifySummary {
147    pub total_files: u64,
148    pub candidates: u64,
149    pub passed: u64,
150    pub failed: u64,
151}
152
153/// `fix` summary: convert counters plus the verify gate result on the same
154/// tree. `fetch_error` is impossible in fix mode and is omitted.
155#[derive(Debug, Clone, Serialize, Deserialize, Default)]
156pub struct FixSummary {
157    pub total_files: u64,
158    pub candidates: u64,
159    pub already_utf8: u64,
160    pub converted: u64,
161    pub unknown: u64,
162    pub decode_errors: u64,
163    /// Same meaning as the convert summary's `encode_errors`.
164    pub encode_errors: u64,
165    pub io_errors: u64,
166    pub too_large: u64,
167    /// Verify pass count on the same tree.
168    pub passed: u64,
169    /// Verify fail count on the same tree (the fix gate).
170    pub failed: u64,
171}
172
173/// Mode-specific summary, serialized inline (untagged).
174///
175/// Standalone deserialization is refused on purpose: the verify and fix
176/// shapes share field names and fix is a superset, so an untagged parse
177/// would silently coerce a fix report into the verify summary. Parse the
178/// full [`Report`] instead — its deserializer dispatches on `mode`.
179#[derive(Debug, Serialize)]
180#[serde(untagged)]
181pub enum Summary {
182    Scan(ScanSummary),
183    Convert(ConvertSummary),
184    Verify(VerifySummary),
185    Fix(FixSummary),
186}
187
188/// Full JSON report document.
189///
190/// Implements the full round trip: [`Deserialize`] dispatches on `mode` to
191/// pick the summary shape (the per-mode summaries share field names, so an
192/// untagged parse would silently coerce a fix report into the verify
193/// summary).
194#[derive(Debug, Serialize)]
195pub struct Report {
196    pub tool: String,
197    pub version: String,
198    pub mode: String,
199    #[serde(skip_serializing_if = "Option::is_none")]
200    pub root: Option<String>,
201    #[serde(skip_serializing_if = "Option::is_none")]
202    pub url: Option<String>,
203    pub started_at: String,
204    pub duration_ms: u64,
205    pub options: OptionsBlock,
206    pub summary: Summary,
207    pub files: Vec<FileRecord>,
208    pub unknown_files: Vec<String>,
209    pub error_files: Vec<String>,
210    /// Paths whose verify record is `failed` (fix mode only). Omitted when
211    /// the gate is clean, so other modes stay schema-compatible.
212    #[serde(skip_serializing_if = "Vec::is_empty")]
213    pub verify_failed_files: Vec<String>,
214    /// Non-fatal traversal/ignore warnings (unreadable directories etc.).
215    /// In `verify`/`fix` an unreadable subtree fails the gate, so a non-empty
216    /// list there always accompanies exit code 3. Omitted when empty.
217    #[serde(skip_serializing_if = "Vec::is_empty")]
218    pub warnings: Vec<String>,
219}
220
221/// Deserialization intermediate for [`Report`]: the `summary` stays a raw
222/// value until `mode` selects its shape. The per-mode summaries share field
223/// names (`passed`/`failed` exist in both verify and fix), so an untagged
224/// parse would silently coerce a fix report into the verify summary.
225impl<'de> Deserialize<'de> for Report {
226    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
227    where
228        D: serde::Deserializer<'de>,
229    {
230        #[derive(Deserialize)]
231        struct Raw {
232            // Everything here is required: the tool's own reports always
233            // emit these fields. (A `default` attribute would add a 'static
234            // bound this manually implemented trait cannot offer.)
235            tool: String,
236            version: String,
237            mode: String,
238            root: Option<String>,
239            url: Option<String>,
240            started_at: String,
241            duration_ms: u64,
242            options: Option<OptionsBlock>,
243            summary: serde_json::Value,
244            files: Vec<FileRecord>,
245            unknown_files: Vec<String>,
246            error_files: Vec<String>,
247            // Omitted-when-empty in the emitted JSON; Option gives the same
248            // leniency without the `default` attribute (which would add a
249            // 'static bound this manually implemented trait cannot offer).
250            verify_failed_files: Option<Vec<String>>,
251            warnings: Option<Vec<String>>,
252        }
253        let raw = Raw::deserialize(deserializer)?;
254        let summary = match raw.mode.as_str() {
255            "scan" => Summary::Scan(
256                serde_json::from_value(raw.summary).map_err(serde::de::Error::custom)?,
257            ),
258            "verify" => Summary::Verify(
259                serde_json::from_value(raw.summary).map_err(serde::de::Error::custom)?,
260            ),
261            "fix" => {
262                Summary::Fix(serde_json::from_value(raw.summary).map_err(serde::de::Error::custom)?)
263            }
264            // convert and fetch share the outcome-counter shape.
265            _ => Summary::Convert(
266                serde_json::from_value(raw.summary).map_err(serde::de::Error::custom)?,
267            ),
268        };
269        Ok(Report {
270            tool: raw.tool,
271            version: raw.version,
272            mode: raw.mode,
273            root: raw.root,
274            url: raw.url,
275            started_at: raw.started_at,
276            duration_ms: raw.duration_ms,
277            options: raw.options.unwrap_or(OptionsBlock {
278                target: String::new(),
279                dry_run: false,
280                extensions: Vec::new(),
281                exclude_dirs: Vec::new(),
282                exclude_ext: Vec::new(),
283                exclude_globs: Vec::new(),
284                backup_dir: None,
285                config_file: None,
286                ignore_file: None,
287            }),
288            summary,
289            files: raw.files,
290            unknown_files: raw.unknown_files,
291            error_files: raw.error_files,
292            verify_failed_files: raw.verify_failed_files.unwrap_or_default(),
293            warnings: raw.warnings.unwrap_or_default(),
294        })
295    }
296}
297
298/// Format a unix timestamp as RFC 3339 UTC (`1970-01-01T00:00:00Z` style).
299/// `chrono` is deliberately not a dependency; the civil-from-days algorithm
300/// is well-known and unit-tested.
301pub fn rfc3339_from_secs(secs: u64) -> String {
302    let days = (secs / 86_400) as i64;
303    let rem = secs % 86_400;
304    let (y, m, d) = civil_from_days(days);
305    format!(
306        "{y:04}-{m:02}-{d:02}T{:02}:{:02}:{:02}Z",
307        rem / 3_600,
308        (rem % 3_600) / 60,
309        rem % 60
310    )
311}
312
313/// Current wall-clock time as RFC 3339 UTC.
314pub fn rfc3339_now() -> String {
315    let secs = SystemTime::now()
316        .duration_since(UNIX_EPOCH)
317        .map(|d| d.as_secs())
318        .unwrap_or(0);
319    rfc3339_from_secs(secs)
320}
321
322/// Howard Hinnant's `civil_from_days`: days since 1970-01-01 → (y, m, d).
323fn civil_from_days(z: i64) -> (i64, u32, u32) {
324    let z = z + 719_468;
325    let era = z.div_euclid(146_097);
326    let doe = z.rem_euclid(146_097);
327    let yoe = (doe - doe / 1_460 + doe / 36_524 - doe / 146_096) / 365;
328    let y = yoe + era * 400;
329    let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
330    let mp = (5 * doy + 2) / 153;
331    let d = (doy - (153 * mp + 2) / 5 + 1) as u32;
332    let m = if mp < 10 { mp + 3 } else { mp - 9 } as u32;
333    (if m <= 2 { y + 1 } else { y }, m, d)
334}
335
336/// Console verbosity settings.
337#[derive(Debug, Clone, Copy, Default)]
338pub struct ConsoleCfg {
339    /// Errors only.
340    pub quiet: bool,
341    /// Per-file detail lines on stdout.
342    pub verbose: bool,
343}
344
345/// Print the mode header line.
346pub fn print_header(cfg: ConsoleCfg, line: String) {
347    if !cfg.quiet {
348        println!("[utf8-forge] {line}");
349    }
350}
351
352/// Print a per-file verbose line (stdout, `-v` only).
353pub fn print_verbose(cfg: ConsoleCfg, line: String) {
354    if cfg.verbose && !cfg.quiet {
355        println!("[utf8-forge] {line}");
356    }
357}
358
359/// Print a per-file problem line (stderr, always shown).
360pub fn print_problem(line: String) {
361    eprintln!("[utf8-forge] {line}");
362}
363
364impl<'de> Deserialize<'de> for Summary {
365    // See the type-level docs: without the report's `mode`, verify and fix
366    // summaries cannot be told apart (fix is a field superset).
367    fn deserialize<D>(_deserializer: D) -> Result<Self, D::Error>
368    where
369        D: serde::Deserializer<'de>,
370    {
371        Err(serde::de::Error::custom(
372            "summary cannot be parsed standalone; deserialize the full Report",
373        ))
374    }
375}
376
377/// Serialize the report and write it next to a trailing newline.
378pub fn write_report(report: &Report, path: &Path) -> anyhow::Result<()> {
379    if let Some(parent) = path.parent()
380        && !parent.as_os_str().is_empty()
381    {
382        fs::create_dir_all(parent)
383            .with_context(|| format!("cannot create report directory {}", parent.display()))?;
384    }
385    // Same crash-safety contract as source writes: temp file + rename, so a
386    // crash mid-write leaves the previous report intact.
387    let json = serde_json::to_string_pretty(report).context("report serialization failed")?;
388    crate::writer::atomic_write(path, (json + "\n").as_bytes())
389        .with_context(|| format!("cannot write report {}", path.display()))?;
390    Ok(())
391}
392
393#[cfg(test)]
394mod tests {
395    use super::*;
396
397    #[test]
398    fn rfc3339_known_timestamps() {
399        assert_eq!(rfc3339_from_secs(0), "1970-01-01T00:00:00Z");
400        assert_eq!(rfc3339_from_secs(86_399), "1970-01-01T23:59:59Z");
401        assert_eq!(rfc3339_from_secs(86_400), "1970-01-02T00:00:00Z");
402        // 2024-02-29 leap day: 2024-01-01 is day 19723.
403        assert_eq!(rfc3339_from_secs(19_782 * 86_400), "2024-02-29T00:00:00Z");
404        // Epoch day 20_000 = 2024-10-04.
405        assert_eq!(rfc3339_from_secs(20_000 * 86_400), "2024-10-04T00:00:00Z");
406    }
407
408    #[test]
409    fn report_round_trips_for_every_mode() {
410        // Serialize → deserialize must reproduce each mode's report exactly:
411        // the mode-dispatched summary parse is the acceptance test for the
412        // untagged-summary hazard (a naive untagged parse would coerce fix
413        // into verify).
414        let files = vec![FileRecord {
415            path: "a.cpp".into(),
416            detected: Some("gb18030".into()),
417            action: "converted".into(),
418            bytes_before: Some(10),
419            bytes_after: Some(12),
420            duration_us: 42,
421            error: None,
422        }];
423        let options = OptionsBlock {
424            target: "utf-8".into(),
425            dry_run: false,
426            extensions: vec!["cpp".into()],
427            exclude_dirs: Vec::new(),
428            exclude_ext: Vec::new(),
429            exclude_globs: Vec::new(),
430            backup_dir: None,
431            config_file: None,
432            ignore_file: None,
433        };
434        let cases: Vec<(&str, Summary)> = vec![
435            (
436                "scan",
437                Summary::Scan(ScanSummary {
438                    total_files: 1,
439                    candidates: 1,
440                    gb18030: 1,
441                    ..ScanSummary::default()
442                }),
443            ),
444            (
445                "convert",
446                Summary::Convert(ConvertSummary {
447                    total_files: 1,
448                    candidates: 1,
449                    converted: 1,
450                    ..ConvertSummary::default()
451                }),
452            ),
453            (
454                "verify",
455                Summary::Verify(VerifySummary {
456                    total_files: 1,
457                    candidates: 1,
458                    passed: 1,
459                    failed: 0,
460                }),
461            ),
462            (
463                // The superset shape: must NOT deserialize as the verify
464                // variant when the mode says fix.
465                "fix",
466                Summary::Fix(FixSummary {
467                    total_files: 1,
468                    candidates: 1,
469                    already_utf8: 0,
470                    converted: 1,
471                    passed: 0,
472                    failed: 1,
473                    ..FixSummary::default()
474                }),
475            ),
476        ];
477        for (mode, summary) in cases {
478            let report = Report {
479                tool: "utf8-forge".into(),
480                version: "0.2.5".into(),
481                mode: mode.into(),
482                root: Some("tree".into()),
483                url: None,
484                started_at: "2026-01-01T00:00:00Z".into(),
485                duration_ms: 5,
486                options: options.clone(),
487                summary,
488                files: files.clone(),
489                unknown_files: Vec::new(),
490                error_files: Vec::new(),
491                verify_failed_files: Vec::new(),
492                warnings: vec!["walk warning".into()],
493            };
494            let json = serde_json::to_string(&report).unwrap();
495            let back: Report = serde_json::from_str(&json).unwrap();
496            let json2 = serde_json::to_string(&back).unwrap();
497            assert_eq!(json, json2, "round trip must be stable for {mode}");
498        }
499    }
500
501    #[test]
502    fn summary_refuses_standalone_deserialize() {
503        let json = serde_json::to_string(&Summary::Verify(VerifySummary {
504            total_files: 1,
505            candidates: 1,
506            passed: 1,
507            failed: 0,
508        }))
509        .unwrap();
510        assert!(serde_json::from_str::<Summary>(&json).is_err());
511    }
512
513    #[test]
514    fn file_actions_vocabulary_is_complete() {
515        for action in FILE_ACTIONS {
516            let record = FileRecord {
517                path: "p".into(),
518                detected: None,
519                action: (*action).to_string(),
520                bytes_before: None,
521                bytes_after: None,
522                duration_us: 0,
523                error: None,
524            };
525            // Each vocabulary entry must serialize to itself.
526            let json = serde_json::to_value(&record).unwrap();
527            assert_eq!(json["action"].as_str().unwrap(), *action);
528        }
529    }
530
531    #[test]
532    fn rfc3339_now_is_recent() {
533        // Sanity: current date must be after 2026-01-01 (this tool's era).
534        let s = rfc3339_now();
535        assert!(s.starts_with("202"), "unexpected timestamp {s}");
536    }
537}