cornerlibstone 0.1.0

Lib Cornerstone — a zero-dependency foundation for building command-line tools in Rust: argument parsing, nested subcommands, themeable help in multiple presets, structured errors and exit codes, config loading, interactive prompts, shell-completion and man/markdown generation, logging, JSON output, and root/destructive-operation guards.
Documentation
//! Errors and exit codes.
//!
//! Two things live here:
//!
//! * [`Error`] — a plain, human-readable error with an associated exit code.
//! * [`ErrorSet`] — the "collect all errors, report at the end" accumulator the
//!   workflow standard calls for. A command can push many failures and still run
//!   to completion, then the app prints them all and exits non-zero.

use std::fmt;

/// Conventional exit codes. Small, memorable, and stable across every CLI so
/// scripts can rely on them.
pub mod codes {
    /// Everything succeeded.
    pub const OK: i32 = 0;
    /// A generic, unclassified failure.
    pub const FAILURE: i32 = 1;
    /// The user invoked the tool incorrectly (bad flag, missing arg, etc.).
    pub const USAGE: i32 = 2;
    /// A requested file or resource was not found.
    pub const NOT_FOUND: i32 = 3;
    /// Permission denied / not running as root when required.
    pub const PERMISSION: i32 = 4;
    /// The operation was cancelled or not confirmed.
    pub const CANCELLED: i32 = 5;
}

/// A single, user-facing error. Carries a message and the exit code the process
/// should return if this error is the one that ends the run.
#[derive(Debug, Clone)]
pub struct Error {
    pub message: String,
    pub code: i32,
    /// Optional extra lines printed under the message, indented, for context.
    pub notes: Vec<String>,
}

impl Error {
    /// A generic failure (exit code 1).
    pub fn msg<S: Into<String>>(message: S) -> Self {
        Error {
            message: message.into(),
            code: codes::FAILURE,
            notes: Vec::new(),
        }
    }

    /// A usage error (exit code 2) — bad flags, missing arguments.
    pub fn usage<S: Into<String>>(message: S) -> Self {
        Error {
            message: message.into(),
            code: codes::USAGE,
            notes: Vec::new(),
        }
    }

    /// A not-found error (exit code 3).
    pub fn not_found<S: Into<String>>(message: S) -> Self {
        Error {
            message: message.into(),
            code: codes::NOT_FOUND,
            notes: Vec::new(),
        }
    }

    /// A permission error (exit code 4).
    pub fn permission<S: Into<String>>(message: S) -> Self {
        Error {
            message: message.into(),
            code: codes::PERMISSION,
            notes: Vec::new(),
        }
    }

    /// A cancelled/unconfirmed error (exit code 5).
    pub fn cancelled<S: Into<String>>(message: S) -> Self {
        Error {
            message: message.into(),
            code: codes::CANCELLED,
            notes: Vec::new(),
        }
    }

    /// Set a specific exit code.
    pub fn with_code(mut self, code: i32) -> Self {
        self.code = code;
        self
    }

    /// Attach a contextual note line.
    pub fn note<S: Into<String>>(mut self, note: S) -> Self {
        self.notes.push(note.into());
        self
    }
}

impl fmt::Display for Error {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.message)
    }
}

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

/// Common standard errors convert into a generic [`Error`], so `?` works on
/// `io::Result` and friends inside command bodies. A blanket
/// `impl<E: std::error::Error>` would collide with the standard library's
/// reflexive `From<T> for T`, so we implement the ones that come up in practice
/// and offer [`Error::wrap`] for anything else.
macro_rules! from_std {
    ($($ty:path),* $(,)?) => {
        $(
            impl From<$ty> for Error {
                fn from(e: $ty) -> Self {
                    Error::msg(e.to_string())
                }
            }
        )*
    };
}

from_std!(
    std::io::Error,
    std::num::ParseIntError,
    std::num::ParseFloatError,
    std::str::Utf8Error,
    std::string::FromUtf8Error,
    std::num::TryFromIntError,
);

impl Error {
    /// Wrap any error type into a Cornerstone [`Error`]. Use when a `?` target
    /// isn't covered by the built-in `From` impls: `something().map_err(Error::wrap)?`.
    pub fn wrap<E: std::fmt::Display>(e: E) -> Self {
        Error::msg(e.to_string())
    }
}

/// The result type command bodies return.
pub type Result<T> = std::result::Result<T, Error>;

/// Accumulates multiple errors so a command can process every item and report
/// all failures at once rather than stopping at the first.
#[derive(Debug, Default, Clone)]
pub struct ErrorSet {
    errors: Vec<Error>,
}

impl ErrorSet {
    pub fn new() -> Self {
        ErrorSet { errors: Vec::new() }
    }

    /// Record a failure and keep going.
    pub fn push(&mut self, e: Error) {
        self.errors.push(e);
    }

    /// Record the `Err` of a result, returning the `Ok` value as an option.
    /// Lets a loop body stay flat: `if let Some(v) = set.absorb(try_thing()) { ... }`
    pub fn absorb<T>(&mut self, r: Result<T>) -> Option<T> {
        match r {
            Ok(v) => Some(v),
            Err(e) => {
                self.errors.push(e);
                None
            }
        }
    }

    pub fn is_empty(&self) -> bool {
        self.errors.is_empty()
    }

    pub fn len(&self) -> usize {
        self.errors.len()
    }

    pub fn errors(&self) -> &[Error] {
        &self.errors
    }

    /// Collapse the set into a single `Result`: `Ok(())` if empty, otherwise an
    /// `Error` summarizing the count with each failure as a note, using the
    /// highest exit code seen.
    pub fn into_result(self) -> Result<()> {
        if self.errors.is_empty() {
            return Ok(());
        }
        let code = self.errors.iter().map(|e| e.code).max().unwrap_or(codes::FAILURE);
        let mut summary = Error::msg(format!("{} operation(s) failed", self.errors.len()))
            .with_code(code);
        for e in &self.errors {
            summary.notes.push(e.message.clone());
            for n in &e.notes {
                summary.notes.push(format!("  {}", n));
            }
        }
        Err(summary)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn constructors_set_codes() {
        assert_eq!(Error::msg("x").code, codes::FAILURE);
        assert_eq!(Error::usage("x").code, codes::USAGE);
        assert_eq!(Error::not_found("x").code, codes::NOT_FOUND);
        assert_eq!(Error::permission("x").code, codes::PERMISSION);
        assert_eq!(Error::cancelled("x").code, codes::CANCELLED);
    }

    #[test]
    fn error_set_collects_and_reports() {
        let mut s = ErrorSet::new();
        assert!(s.is_empty());
        s.push(Error::usage("first"));
        s.push(Error::not_found("second"));
        assert_eq!(s.len(), 2);
        let e = s.into_result().unwrap_err();
        // Highest code wins: NOT_FOUND (3) > USAGE (2)
        assert_eq!(e.code, codes::NOT_FOUND);
        assert_eq!(e.notes.len(), 2);
    }

    #[test]
    fn empty_error_set_is_ok() {
        assert!(ErrorSet::new().into_result().is_ok());
    }

    #[test]
    fn absorb_returns_ok_value() {
        let mut s = ErrorSet::new();
        let v = s.absorb(Ok::<i32, Error>(5));
        assert_eq!(v, Some(5));
        let n = s.absorb(Err::<i32, Error>(Error::msg("bad")));
        assert_eq!(n, None);
        assert_eq!(s.len(), 1);
    }

    #[test]
    fn io_error_converts() {
        let io = std::io::Error::new(std::io::ErrorKind::NotFound, "nope");
        let e: Error = io.into();
        assert_eq!(e.code, codes::FAILURE);
    }
}