use std::io::Write;
use std::panic::PanicHookInfo;
use crate::message::Report;
use crate::style::paint;
use crate::style::palette::MUTED;
pub fn install_panic_hook() {
std::panic::set_hook(Box::new(hook));
}
fn hook(info: &PanicHookInfo<'_>) {
let interrupted = crate::live::abandon_all() | crate::region::abandon_all();
cfg!(panic = "abort").then(crate::term::restore_saved_terminal);
let message = info
.payload()
.downcast_ref::<&str>()
.map(|s| s.to_string())
.or_else(|| info.payload().downcast_ref::<String>().cloned())
.unwrap_or_else(|| "panicked with a value that isn't text".into());
let program = crate::history::History::default_app();
let thread = std::thread::current();
let title = match thread.name() {
Some("main") | None => format!("{program} panicked"),
Some(name) => format!("{program} panicked in thread '{name}'"),
};
let at = info
.location()
.map(|at| format!("at {}:{}:{}", at.file(), at.line(), at.column()));
let mut report = at.into_iter().fold(Report::new(title).cause(message), Report::cause);
let backtrace = std::backtrace::Backtrace::capture();
let captured = backtrace.status() == std::backtrace::BacktraceStatus::Captured;
if !captured {
report = report.hint("run with RUST_BACKTRACE=1 to see where it came from");
}
let _ = std::io::stdout().flush();
let _ = std::io::stderr().flush();
if interrupted {
eprintln!();
}
report.eprint();
if captured && !crate::output::json() {
for line in backtrace.to_string().lines() {
eprintln!(" {}", paint(MUTED, line));
}
}
}