1use std::fs;
41use std::path::Path;
42use std::time::{SystemTime, UNIX_EPOCH};
43
44use anyhow::Context;
45use serde::{Deserialize, Serialize};
46
47pub 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#[derive(Debug, Clone, Serialize, Deserialize)]
64pub struct FileRecord {
65 pub path: String,
66 #[serde(default, skip_serializing_if = "Option::is_none")]
68 pub detected: Option<String>,
69 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#[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 #[serde(default, skip_serializing_if = "Option::is_none")]
95 pub config_file: Option<String>,
96 #[serde(default, skip_serializing_if = "Option::is_none")]
99 pub ignore_file: Option<String>,
100}
101
102#[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 pub errors: u64,
119 pub too_large: u64,
120}
121
122#[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 pub encode_errors: u64,
139 pub io_errors: u64,
140 pub too_large: u64,
141 pub fetch_error: u64,
142}
143
144#[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#[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 pub encode_errors: u64,
165 pub io_errors: u64,
166 pub too_large: u64,
167 pub passed: u64,
169 pub failed: u64,
171}
172
173#[derive(Debug, Serialize)]
180#[serde(untagged)]
181pub enum Summary {
182 Scan(ScanSummary),
183 Convert(ConvertSummary),
184 Verify(VerifySummary),
185 Fix(FixSummary),
186}
187
188#[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 #[serde(skip_serializing_if = "Vec::is_empty")]
213 pub verify_failed_files: Vec<String>,
214 #[serde(skip_serializing_if = "Vec::is_empty")]
218 pub warnings: Vec<String>,
219}
220
221impl<'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 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 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 _ => 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
298pub 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
313pub 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
322fn 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#[derive(Debug, Clone, Copy, Default)]
338pub struct ConsoleCfg {
339 pub quiet: bool,
341 pub verbose: bool,
343}
344
345pub fn print_header(cfg: ConsoleCfg, line: String) {
347 if !cfg.quiet {
348 println!("[utf8-forge] {line}");
349 }
350}
351
352pub fn print_verbose(cfg: ConsoleCfg, line: String) {
354 if cfg.verbose && !cfg.quiet {
355 println!("[utf8-forge] {line}");
356 }
357}
358
359pub fn print_problem(line: String) {
361 eprintln!("[utf8-forge] {line}");
362}
363
364impl<'de> Deserialize<'de> for Summary {
365 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
377pub 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 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 assert_eq!(rfc3339_from_secs(19_782 * 86_400), "2024-02-29T00:00:00Z");
404 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 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 "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 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 let s = rfc3339_now();
535 assert!(s.starts_with("202"), "unexpected timestamp {s}");
536 }
537}