Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
47 changes: 37 additions & 10 deletions src/subprocess.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,31 +4,58 @@
/// When this error is encountered the cli will exit with the status code
/// instead of printing an error,
#[derive(Debug)]
pub struct ExitStatusError {
status: Option<i32>,
pub enum ExitStatusError {
/// The subprocess exited with a specific exit code.
ExitCode(i32),
/// The subprocess was exited by a signal. Only available for `Unix` based systems.
Signal(i32),
/// Catchall for general errors. Error code `1`
Unknown,
}

impl ExitStatusError {
#[cfg(unix)]
pub(crate) fn new(status: std::process::ExitStatus) -> Self {
Self {
status: status.code(),
use std::os::unix::process::ExitStatusExt as _;

if let Some(code) = status.code() {
Self::ExitCode(code)
} else if let Some(signal) = status.signal() {
Self::Signal(signal)
} else {
Self::Unknown
}
}

#[cfg(not(unix))]
pub(crate) fn new(status: std::process::ExitStatus) -> Self {
if let Some(code) = status.code() {
Self::ExitCode(code)
} else {
Self::Unknown
}
}

pub fn code(&self) -> i32 {
self.status.unwrap_or(1)
match self {
Self::ExitCode(code) => *code,
Self::Signal(signal) => 128 + *signal,
Self::Unknown => 1,
}
.min(255)
}
}

impl std::error::Error for ExitStatusError {}

impl std::fmt::Display for ExitStatusError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let _ = write!(f, "subprocess exited with status: ");
if let Some(status) = self.status {
writeln!(f, "{status}")
} else {
writeln!(f, "unknown")
let _ = write!(f, "subprocess exited with ");

match self {
Self::ExitCode(code) => write!(f, "exit code: {code}"),
Self::Signal(signal) => write!(f, "signal: {signal}"),
Self::Unknown => write!(f, "unknown status"),
}
}
}