1use std::fs;
23use std::path::Path;
24use std::time::{SystemTime, UNIX_EPOCH};
25
26use anyhow::Context;
27use serde::Serialize;
28
29#[derive(Debug, Clone, Serialize)]
31pub struct FileRecord {
32 pub path: String,
33 #[serde(skip_serializing_if = "Option::is_none")]
35 pub detected: Option<&'static str>,
36 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#[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 #[serde(skip_serializing_if = "Option::is_none")]
63 pub config_file: Option<String>,
64 #[serde(skip_serializing_if = "Option::is_none")]
67 pub ignore_file: Option<String>,
68}
69
70#[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 pub errors: u64,
87 pub too_large: u64,
88}
89
90#[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 pub encode_errors: u64,
107 pub io_errors: u64,
108 pub too_large: u64,
109 pub fetch_error: u64,
110}
111
112#[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#[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 pub encode_errors: u64,
133 pub io_errors: u64,
134 pub too_large: u64,
135 pub passed: u64,
137 pub failed: u64,
139}
140
141#[derive(Debug, Serialize)]
143#[serde(untagged)]
144pub enum Summary {
145 Scan(ScanSummary),
146 Convert(ConvertSummary),
147 Verify(VerifySummary),
148 Fix(FixSummary),
149}
150
151#[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 #[serde(skip_serializing_if = "Vec::is_empty")]
171 pub verify_failed_files: Vec<String>,
172 #[serde(skip_serializing_if = "Vec::is_empty")]
176 pub warnings: Vec<String>,
177}
178
179pub 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
194pub 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
203fn 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#[derive(Debug, Clone, Copy, Default)]
219pub struct ConsoleCfg {
220 pub quiet: bool,
222 pub verbose: bool,
224}
225
226pub fn print_header(cfg: ConsoleCfg, line: String) {
228 if !cfg.quiet {
229 println!("[utf8-forge] {line}");
230 }
231}
232
233pub fn print_verbose(cfg: ConsoleCfg, line: String) {
235 if cfg.verbose && !cfg.quiet {
236 println!("[utf8-forge] {line}");
237 }
238}
239
240pub fn print_problem(line: String) {
242 eprintln!("[utf8-forge] {line}");
243}
244
245pub 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 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 assert_eq!(rfc3339_from_secs(19_782 * 86_400), "2024-02-29T00:00:00Z");
272 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 let s = rfc3339_now();
280 assert!(s.starts_with("202"), "unexpected timestamp {s}");
281 }
282}