use std::cell::Cell;
use std::path::{Path, PathBuf};
use std::time::SystemTime;
thread_local! {
static CATCHING: Cell<u32> = const { Cell::new(0) };
}
pub(crate) fn catching<R>(f: impl FnOnce() -> R) -> R {
struct Out;
impl Drop for Out {
fn drop(&mut self) {
let _ = CATCHING.try_with(|c| c.set(c.get().saturating_sub(1)));
}
}
CATCHING.with(|c| c.set(c.get() + 1));
let _out = Out;
f()
}
fn caught_here() -> bool {
CATCHING.try_with(Cell::get).unwrap_or(0) > 0
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct CrashReport {
pub path: PathBuf,
pub text: String,
pub when: Option<SystemTime>,
}
impl CrashReport {
pub fn mark_sent(&self) -> std::io::Result<()> {
let dir = self.path.parent().ok_or_else(|| std::io::Error::other("a report without a folder"))?.join("Sent");
std::fs::create_dir_all(&dir)?;
std::fs::rename(&self.path, dir.join(self.path.file_name().unwrap_or_default()))
}
}
pub(crate) fn folder(name: &str) -> PathBuf {
if let Some(dir) = std::env::var_os("FERROKIT_CRASH_DIR") {
return PathBuf::from(dir);
}
let home = std::env::var_os("HOME").map_or_else(std::env::temp_dir, PathBuf::from);
home.join("Library/Logs").join(name).join("Crashes")
}
pub(crate) fn install(name: &str) {
let dir = folder(name);
let header = header(name);
let previous = std::panic::take_hook();
std::panic::set_hook(Box::new(move |info| {
previous(info);
if caught_here() {
return;
}
let message = info.payload().downcast_ref::<&str>().map(|s| s.to_string()).or_else(|| info.payload().downcast_ref::<String>().cloned()).unwrap_or_else(|| "(no message)".into());
let place = info.location().map_or_else(String::new, |l| format!("{}:{}:{}", l.file(), l.line(), l.column()));
let thread = std::thread::current();
let thread = match thread.name() {
Some("main") => "the main thread".to_string(),
Some(n) => format!("thread {n}"),
None => "a background thread".to_string(),
};
let when = SystemTime::now().duration_since(SystemTime::UNIX_EPOCH).map_or(0, |d| d.as_secs());
let text = format!(
"{header}Crashed at: {when} (seconds since 1970)\nThread: {thread}\nPanic: {message}\nAt: {place}\n\nBacktrace:\n{}\n",
std::backtrace::Backtrace::force_capture()
);
let _ = std::fs::create_dir_all(&dir);
let _ = std::fs::write(dir.join(format!("{when}-{}.crash.txt", std::process::id())), text);
}));
}
fn header(name: &str) -> String {
use objc2_foundation::{NSBundle, NSProcessInfo, NSString};
let info = NSBundle::mainBundle().infoDictionary();
let get = |key: &str| {
info.as_ref().and_then(|i| i.objectForKey(&NSString::from_str(key))).and_then(|v| v.downcast::<NSString>().ok()).map(|s| s.to_string())
};
let version = match (get("CFBundleShortVersionString"), get("CFBundleVersion")) {
(Some(v), Some(b)) if v != b => format!("{v} ({b})"),
(Some(v), _) => v,
_ => "(not bundled)".to_string(),
};
let id = get("CFBundleIdentifier").map_or_else(String::new, |id| format!(" ({id})"));
let macos = NSProcessInfo::processInfo().operatingSystemVersionString().to_string();
format!("App: {name} {version}{id}\nmacOS: {macos}\nFerrokit: {}\n", env!("CARGO_PKG_VERSION"))
}
pub(crate) fn pending(dir: &Path) -> Vec<CrashReport> {
let Ok(entries) = std::fs::read_dir(dir) else { return Vec::new() };
let mut reports: Vec<CrashReport> = entries
.filter_map(Result::ok)
.map(|e| e.path())
.filter(|p| p.to_string_lossy().ends_with(".crash.txt"))
.filter_map(|path| {
let text = std::fs::read_to_string(&path).ok()?;
let when = path
.file_name()
.and_then(|n| n.to_str())
.and_then(|n| n.split('-').next())
.and_then(|s| s.parse::<u64>().ok())
.map(|s| SystemTime::UNIX_EPOCH + std::time::Duration::from_secs(s));
Some(CrashReport { path, text, when })
})
.collect();
reports.sort_by(|a, b| a.path.cmp(&b.path));
reports
}