use std::cell::Cell;
use std::panic::{self, AssertUnwindSafe};
use std::path::PathBuf;
use std::sync::Once;
thread_local! {
static HOSTED: Cell<bool> = const { Cell::new(false) };
}
struct HostedExit(i32);
pub fn is_hosted() -> bool {
HOSTED.with(Cell::get)
}
pub fn exit(code: i32) -> ! {
if is_hosted() {
panic::panic_any(HostedExit(code));
}
std::process::exit(code)
}
fn install_quiet_hook() {
static ONCE: Once = Once::new();
ONCE.call_once(|| {
let previous = panic::take_hook();
panic::set_hook(Box::new(move |info| {
if info.payload().is::<HostedExit>() {
return;
}
previous(info);
}));
});
}
pub fn run<F>(f: F) -> i32
where
F: FnOnce() -> i32,
{
install_quiet_hook();
let cwd: Option<PathBuf> = std::env::current_dir().ok();
let previously = HOSTED.replace(true);
let outcome = panic::catch_unwind(AssertUnwindSafe(f));
HOSTED.set(previously);
if let Some(dir) = cwd {
let _ = std::env::set_current_dir(dir);
}
match outcome {
Ok(code) => code,
Err(payload) => match payload.downcast::<HostedExit>() {
Ok(exit) => exit.0,
Err(_) => 1,
},
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn exit_from_inside_becomes_a_return_value() {
assert_eq!(run(|| exit(2)), 2);
}
#[test]
fn a_normal_return_is_untouched() {
assert_eq!(run(|| 0), 0);
}
#[test]
fn a_panic_becomes_a_failed_run() {
assert_eq!(run(|| panic!("boom")), 1);
}
#[test]
fn the_flag_is_off_again_afterwards() {
assert!(!is_hosted());
assert_eq!(run(|| if is_hosted() { 1 } else { 0 }), 1);
assert!(!is_hosted());
}
#[test]
fn the_working_directory_is_restored() {
let before = std::env::current_dir().unwrap();
assert_eq!(
run(|| {
std::env::set_current_dir(std::env::temp_dir()).unwrap();
0
}),
0
);
assert_eq!(std::env::current_dir().unwrap(), before);
}
}