aboutsummaryrefslogtreecommitdiffstats
path: root/src/panic.rs
blob: 0df0a4eb51e89efc50038fcc0aa13aa12653d192 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
use std::backtrace::{Backtrace, BacktraceStatus};
use std::io::{self, Write};
use std::panic::{self, PanicHookInfo};
use std::sync::atomic::{AtomicBool, Ordering};

static EMIT_CARRIAGE_RETURN: AtomicBool = AtomicBool::new(false);

pub fn enable_cr() {
    EMIT_CARRIAGE_RETURN.store(true, Ordering::SeqCst);
}

pub fn disable_cr() {
    EMIT_CARRIAGE_RETURN.store(false, Ordering::SeqCst);
}

// thread 'main' panicked at src/main.rs:59:25:
// not yet implemented: homedir
// stack backtrace:
// 0: __rustc::rust_begin_unwind at /rustc/1159e78c4747b02ef996e55082b704c09b970588/library/std/src/panicking.rs:697:5
// 1: core::panicking::panic_fmt at /rustc/1159e78c4747b02ef996e55082b704c09b970588/library/core/src/panicking.rs:75:14
// 2: pish::run_command at ./src/main.rs:59:25
// note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace

fn panic_hook(info: &PanicHookInfo<'_>) {
    let mut msg = format!("{}\n", info);

    let bt = Backtrace::capture();
    match bt.status() {
        BacktraceStatus::Unsupported => msg += "backtrace unsupported\n",
        BacktraceStatus::Disabled => msg += "no backtrace",
        _ => {
            msg += &format!("{bt}\n");
        },
    }

    // TODO: add link to repo or sth
    msg += "\n -== this is a bug ==-\n";

    if EMIT_CARRIAGE_RETURN.load(Ordering::SeqCst) {
        msg = msg.replace("\n", "\r\n");
    }

    let _ = io::stderr().write_all(msg.as_bytes());
}

pub fn hook() {
    panic::set_hook(Box::new(panic_hook));
}