use std::io::Write;
fn panic_hook_i18n() -> &'static calnexus::I18n {
static HOOK_I18N: std::sync::OnceLock<calnexus::I18n> = std::sync::OnceLock::new();
HOOK_I18N.get_or_init(calnexus::I18n::from_detected)
}
fn setup_panic_hook() {
use std::sync::Once;
static ONCE: Once = Once::new();
ONCE.call_once(|| {
let i18n: &'static calnexus::I18n = panic_hook_i18n();
let default_hook = std::panic::take_hook();
std::panic::set_hook(Box::new(move |info| {
if is_stdio_print_panic(info.payload()) {
std::process::exit(141);
}
let _ = writeln!(std::io::stderr(), "{}", i18n.t("panic.internal_error"));
default_hook(info);
let _ = writeln!(std::io::stderr(), "{}", i18n.t("panic.report_bug"));
}));
});
}
fn is_stdio_print_panic(payload: &(dyn std::any::Any + Send)) -> bool {
let msg = payload
.downcast_ref::<String>()
.map(String::as_str)
.or_else(|| payload.downcast_ref::<&str>().copied());
msg.is_some_and(|m| {
m.starts_with("failed printing to stdout:") || m.starts_with("failed printing to stderr:")
})
}
#[cfg(unix)]
fn reset_sigpipe() {
unsafe { libc::signal(libc::SIGPIPE, libc::SIG_DFL) };
}
#[cfg(not(unix))]
fn reset_sigpipe() {}
#[cfg(feature = "cli")]
fn main() {
reset_sigpipe();
setup_panic_hook();
let exit_code = calnexus::run();
std::process::exit(exit_code);
}
#[cfg(not(feature = "cli"))]
fn main() {
reset_sigpipe();
setup_panic_hook();
let i18n = calnexus::I18n::default();
eprintln!("{}", i18n.t("main.feature_missing"));
std::process::exit(2);
}
#[cfg(test)]
mod tests {
use super::*;
use std::any::Any;
#[test]
fn test_setup_panic_hook_does_not_panic() {
setup_panic_hook();
}
#[test]
fn test_setup_panic_hook_idempotent() {
setup_panic_hook();
setup_panic_hook();
setup_panic_hook();
}
#[test]
fn test_is_stdio_print_panic_matches_std_payload() {
fn boxed(p: impl Any + Send) -> Box<dyn Any + Send> {
Box::new(p)
}
assert!(is_stdio_print_panic(
boxed("failed printing to stdout: Broken pipe (os error 32)".to_string()).as_ref()
));
assert!(is_stdio_print_panic(
boxed("failed printing to stderr: Broken pipe (os error 32)".to_string()).as_ref()
));
assert!(is_stdio_print_panic(
boxed("failed printing to stdout: no more data",).as_ref()
));
assert!(!is_stdio_print_panic(
boxed("probe: intentional panic for panic-hook i18n verification".to_string()).as_ref()
));
assert!(!is_stdio_print_panic(boxed(42_u32).as_ref()));
}
#[test]
fn test_panic_hook_messages_come_from_catalog() {
let en = calnexus::I18n::new(calnexus::Lang::En);
let zh = calnexus::I18n::new(calnexus::Lang::Zh);
assert_eq!(
en.t("panic.internal_error"),
"calnexus: internal error (panic)"
);
assert_eq!(
en.t("panic.report_bug"),
"calnexus: please report this bug with the backtrace above"
);
assert_eq!(zh.t("panic.internal_error"), "calnexus: 内部错误(panic)");
assert_eq!(
zh.t("panic.report_bug"),
"calnexus: 请携带上方 backtrace 报告此问题"
);
for key in ["panic.internal_error", "panic.report_bug"] {
assert_ne!(en.t(key), key, "en catalog missing key: {key}");
assert_ne!(zh.t(key), key, "zh catalog missing key: {key}");
}
assert_ne!(en.t("panic.internal_error"), zh.t("panic.internal_error"));
}
#[test]
#[ignore = "由 test_panic_hook_outputs_localized_message 以子进程方式调用"]
fn panic_hook_probe_child() {
if std::env::var_os("CALNEXUS_PANIC_PROBE").is_none() {
return;
}
setup_panic_hook();
panic!("probe: intentional panic for panic-hook i18n verification");
}
#[test]
fn test_panic_hook_outputs_localized_message() {
let exe = std::env::current_exe().expect("current_exe");
let run_probe = |lang_key: &str, lang: &str| -> String {
let out = std::process::Command::new(&exe)
.args([
"--exact",
"tests::panic_hook_probe_child",
"--ignored",
"--nocapture",
])
.env("CALNEXUS_PANIC_PROBE", "1")
.env("CALNEXUS_LANG", "")
.env("LC_ALL", "")
.env("LC_MESSAGES", "")
.env("LANG", "")
.env(lang_key, lang)
.output()
.expect("spawn panic probe child");
String::from_utf8_lossy(&out.stderr).into_owned()
};
let zh = run_probe("LANG", "zh_CN.UTF-8");
assert!(
zh.contains("calnexus: 内部错误(panic)"),
"zh panic hook prefix missing, stderr:\n{zh}"
);
assert!(
zh.contains("calnexus: 请携带上方 backtrace 报告此问题"),
"zh panic hook report line missing, stderr:\n{zh}"
);
assert!(
!zh.contains("calnexus: internal error (panic)"),
"zh run must not emit hardcoded English, stderr:\n{zh}"
);
let en = run_probe("CALNEXUS_LANG", "en");
assert!(
en.contains("calnexus: internal error (panic)"),
"en panic hook prefix missing, stderr:\n{en}"
);
assert!(
en.contains("calnexus: please report this bug with the backtrace above"),
"en panic hook report line missing, stderr:\n{en}"
);
let c_locale = run_probe("LANG", "C");
assert!(
c_locale.contains("calnexus: internal error (panic)")
|| c_locale.contains("calnexus: 内部错误(panic)"),
"C locale must yield a localized panic prefix, stderr:\n{c_locale}"
);
assert!(
c_locale.contains("请携带上方 backtrace 报告此问题")
|| c_locale.contains("please report this bug with the backtrace above"),
"C locale must yield a localized report line, stderr:\n{c_locale}"
);
}
}