1use std::fs;
9use std::path::Path;
10use std::time::{SystemTime, UNIX_EPOCH};
11
12use anyhow::Context;
13use serde::Serialize;
14
15#[derive(Debug, Clone, Serialize)]
17pub struct FileRecord {
18 pub path: String,
19 #[serde(skip_serializing_if = "Option::is_none")]
21 pub detected: Option<&'static str>,
22 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 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#[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#[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#[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#[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#[derive(Debug, Serialize)]
107#[serde(untagged)]
108pub enum Summary {
109 Scan(ScanSummary),
110 Convert(ConvertSummary),
111 Verify(VerifySummary),
112}
113
114#[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
133pub 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
148pub 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
157fn 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#[derive(Debug, Clone, Copy, Default)]
173pub struct ConsoleCfg {
174 pub quiet: bool,
176 pub verbose: bool,
178}
179
180pub fn print_header(cfg: ConsoleCfg, line: String) {
182 if !cfg.quiet {
183 println!("[utf8-forge] {line}");
184 }
185}
186
187pub fn print_verbose(cfg: ConsoleCfg, line: String) {
189 if cfg.verbose && !cfg.quiet {
190 println!("[utf8-forge] {line}");
191 }
192}
193
194pub fn print_problem(line: String) {
196 eprintln!("[utf8-forge] {line}");
197}
198
199pub 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 assert_eq!(rfc3339_from_secs(19_782 * 86_400), "2024-02-29T00:00:00Z");
224 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 let s = rfc3339_now();
232 assert!(s.starts_with("202"), "unexpected timestamp {s}");
233 }
234}