use std::{
fs::OpenOptions,
io::{self, Write},
panic::{self, PanicHookInfo},
path::{Path, PathBuf},
sync::Once,
time::{SystemTime, UNIX_EPOCH},
};
use crate::App;
const MAX_FRAMES: usize = 120;
pub fn install_crash_hook(app: &App, version: &'static str) {
static INSTALL: Once = Once::new();
let app = app.clone();
INSTALL.call_once(|| {
let default = panic::take_hook();
panic::set_hook(Box::new(move |info| {
let _ = write_crash_log(&app, version, info);
default(info);
}));
});
}
pub fn crash_log_path(app: &App) -> PathBuf {
app.dir().join("crash.log")
}
fn write_crash_log(app: &App, version: &str, info: &PanicHookInfo) -> io::Result<PathBuf> {
let backtrace = std::backtrace::Backtrace::force_capture();
let frames = backtrace_to_text(&backtrace);
let payload = panic_payload(info);
let path = crash_log_path(app);
write_crash_entry(&path, app.display_name(), version, &payload, &frames)?;
Ok(path)
}
fn write_crash_entry(
path: &Path,
display_name: &str,
version: &str,
payload: &str,
frames: &str,
) -> io::Result<()> {
if let Some(parent) = path.parent() {
std::fs::create_dir_all(parent)?;
}
let mut file = OpenOptions::new().create(true).append(true).open(path)?;
let timestamp = fmt_timestamp(SystemTime::now());
writeln!(
file,
"===== {display_name} crash log =====\n\
time: {timestamp}\n\
version: {version}\n\
panic: {payload}\n\
--- backtrace ---\n\
{frames}\n\
=================================\n"
)?;
Ok(())
}
fn panic_payload(info: &PanicHookInfo) -> String {
let msg = if let Some(s) = info.payload().downcast_ref::<&str>() {
(*s).to_string()
} else if let Some(s) = info.payload().downcast_ref::<String>() {
s.clone()
} else {
"non-string panic payload".to_string()
};
match info.location() {
Some(loc) => format!("{loc} — {msg}"),
None => msg,
}
}
fn backtrace_to_text(bt: &std::backtrace::Backtrace) -> String {
let mut out = format!("{bt:?}");
if let Some(idx) = out.find("\nAt ") {
out.truncate(idx);
}
let lines = out.lines().take(MAX_FRAMES).collect::<Vec<_>>();
lines.join("\n")
}
fn fmt_timestamp(t: SystemTime) -> String {
let secs = t.duration_since(UNIX_EPOCH).unwrap_or_default().as_secs() as i64;
let days = secs.div_euclid(86_400);
let secs_of_day = secs.rem_euclid(86_400);
let (y, m, d) = civil_from_days(days);
let hh = secs_of_day / 3600;
let mm = (secs_of_day % 3600) / 60;
let ss = secs_of_day % 60;
format!("{y:04}-{m:02}-{d:02} {hh:02}:{mm:02}:{ss:02}")
}
fn civil_from_days(z: i64) -> (i64, u32, u32) {
let z = z + 719_468;
let era = z.div_euclid(146_097);
let doe = z.rem_euclid(146_097);
let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
let y = yoe + era * 400;
let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
let mp = (5 * doy + 2) / 153;
let d = (doy - (153 * mp + 2) / 5 + 1) as u32;
let m = if mp < 10 { mp + 3 } else { mp - 9 } as u32;
(if m <= 2 { y + 1 } else { y }, m, d)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn civil_from_days_known_dates() {
assert_eq!(civil_from_days(0), (1970, 1, 1));
assert_eq!(civil_from_days(20_689), (2026, 8, 24));
assert_eq!(civil_from_days(11_016), (2000, 2, 29));
}
#[test]
fn timestamp_format() {
let s = fmt_timestamp(SystemTime::UNIX_EPOCH);
assert_eq!(s, "1970-01-01 00:00:00");
}
#[test]
fn crash_entries_append() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("nested").join("crash.log");
write_crash_entry(&path, "optionTerm", "1.0.0", "first boom", "frame a").unwrap();
write_crash_entry(&path, "optionTerm", "1.0.0", "second boom", "frame b").unwrap();
let text = std::fs::read_to_string(&path).unwrap();
assert_eq!(text.matches("===== optionTerm crash log =====").count(), 2);
assert!(text.contains("version: 1.0.0"));
assert!(text.contains("panic: first boom"));
assert!(text.contains("panic: second boom"));
assert!(text.contains("frame a"));
assert!(path.parent().unwrap().is_dir());
}
}