ezexec 0.4.1

A simple API to execute binaries or shell commands via `std::process::Command`
Documentation
//! Implements the crate's error types

use std::{
    backtrace::Backtrace,
    fmt::{self, Display, Formatter},
};

/// Creates a new error
#[macro_export]
macro_rules! error {
    ($kind:expr, with: $error:expr) => {{
        let error = $error.to_string();
        let source = Box::new($error);
        $crate::error::Error::new($kind, error, Some(source))
    }};
    ($kind:expr, with: $error:expr, $($arg:tt)*) => {{
        let error = format!($($arg)*);
        let source = Box::new($error);
        $crate::error::Error::new($kind, error, Some(source))
    }};
    ($kind:expr, $($arg:tt)*) => {{
        let error = format!($($arg)*);
        $crate::error::Error::new($kind, error, None)
    }};
}

/// The error kind
#[derive(Debug)]
pub enum ErrorKind {
    /// Failed to find the requested binary
    PathError,
    /// Failed to execute the child
    ExecError,
    /// The child exited with a non-zero error code
    ChildError,
}
impl Display for ErrorKind {
    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
        match self {
            Self::PathError => write!(f, "Failed to find the requested binary"),
            Self::ExecError => write!(f, "Failed to execute the child"),
            Self::ChildError => write!(f, "The child exited with a non-zero error code"),
        }
    }
}

/// The crates error type
#[derive(Debug)]
pub struct Error {
    /// The error description
    pub kind: ErrorKind,
    /// The error message
    pub message: String,
    /// The underlying error
    pub source: Option<Box<dyn std::error::Error + Send>>,
    /// The backtrace
    pub backtrace: Backtrace,
}
impl Error {
    /// Creates a new error
    #[doc(hidden)]
    pub fn new(kind: ErrorKind, message: String, source: Option<Box<dyn std::error::Error + Send>>) -> Self {
        let backtrace = Backtrace::capture();
        Self { kind, message, source, backtrace }
    }
}
impl Display for Error {
    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
        // Print the error
        writeln!(f, "{}: {}", self.kind, self.message)?;

        // Print the source
        if let Some(source) = &self.source {
            writeln!(f, " caused by: {}", source)?;
        }
        Ok(())
    }
}
impl std::error::Error for Error {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        let source = self.source.as_ref()?;
        Some(source.as_ref())
    }
}