kutil 0.0.6

Kutil utilities collection
Documentation
use super::super::error::*;

use std::{backtrace::*, env::*, fs::*, io::*, panic::*, path::*};

/// On panic write [PanicInfo] and [Backtrace] to a file with the same name as the current
/// executable with an added ".panic" extension.
#[track_caller]
pub fn panic_to_current_exe_file() -> Result<()> {
    panic_to_file(current_exe().expect("current_exe").with_added_extension("panic").file_name().expect("file_name"))
}

/// On panic write [PanicInfo] and [Backtrace] to a file.
#[track_caller]
pub fn panic_to_file<PathT>(path: PathT) -> Result<()>
where
    PathT: AsRef<Path>,
{
    let path = absolute(path.as_ref()).with_path(path)?;
    let hook = take_hook();

    set_hook(Box::new(move |panic_info| {
        hook(panic_info);
        if let Ok(mut file) = File::create(&path) {
            eprintln!("\nbacktrace written to file: {}", path.display());
            _ = write!(file, "{}\n\nbacktrace:\n{}", panic_info, Backtrace::force_capture());
        } else {
            eprintln!("\ncould not write backtrace to file: {}", path.display());
        }
    }));

    Ok(())
}