conch_runtime_pshaw/
exit_status.rs

1use std::fmt;
2use std::process;
3
4/// Exit code for commands that exited successfully.
5pub const EXIT_SUCCESS: ExitStatus = ExitStatus::Code(0);
6/// Exit code for commands that did not exit successfully.
7pub const EXIT_ERROR: ExitStatus = ExitStatus::Code(1);
8/// Exit code for commands which are not executable.
9pub const EXIT_CMD_NOT_EXECUTABLE: ExitStatus = ExitStatus::Code(126);
10/// Exit code for missing commands.
11pub const EXIT_CMD_NOT_FOUND: ExitStatus = ExitStatus::Code(127);
12
13/// Describes the result of a process after it has terminated.
14#[derive(PartialEq, Eq, Clone, Copy, Debug)]
15pub enum ExitStatus {
16    /// Normal termination with an exit code.
17    Code(i32),
18
19    /// Termination by signal, with the signal number.
20    ///
21    /// Never generated on Windows.
22    Signal(i32),
23}
24
25impl ExitStatus {
26    /// Was termination successful? Signal termination not considered a success,
27    /// and success is defined as a zero exit status.
28    pub fn success(self) -> bool {
29        self == EXIT_SUCCESS
30    }
31}
32
33impl fmt::Display for ExitStatus {
34    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
35        match *self {
36            ExitStatus::Code(code) => write!(f, "exit code: {}", code),
37            ExitStatus::Signal(code) => write!(f, "signal: {}", code),
38        }
39    }
40}
41
42impl From<process::ExitStatus> for ExitStatus {
43    fn from(exit: process::ExitStatus) -> ExitStatus {
44        #[cfg(unix)]
45        fn get_signal(exit: process::ExitStatus) -> Option<i32> {
46            ::std::os::unix::process::ExitStatusExt::signal(&exit)
47        }
48
49        #[cfg(windows)]
50        fn get_signal(_exit: process::ExitStatus) -> Option<i32> {
51            None
52        }
53
54        match exit.code() {
55            Some(code) => ExitStatus::Code(code),
56            None => get_signal(exit).map_or(EXIT_ERROR, ExitStatus::Signal),
57        }
58    }
59}