codetree 0.1.2

AI-native version control system for autonomous agents
Documentation
//! Lightweight error handling — no external crate needed.

use std::error::Error;

/// Shorthand for our fallible return type.
pub type Result<T> = std::result::Result<T, Box<dyn Error + Send + Sync>>;

/// Adds contextual messages to errors, mimicking `anyhow::Context`.
pub trait Context<T> {
    fn context(self, msg: impl std::fmt::Display) -> Result<T>;
    fn with_context<F, M>(self, f: F) -> Result<T>
    where
        F: FnOnce() -> M,
        M: std::fmt::Display;
}

impl<T, E: std::fmt::Display> Context<T> for std::result::Result<T, E> {
    fn context(self, msg: impl std::fmt::Display) -> Result<T> {
        self.map_err(|e| format!("{msg}: {e}").into())
    }

    fn with_context<F, M>(self, f: F) -> Result<T>
    where
        F: FnOnce() -> M,
        M: std::fmt::Display,
    {
        self.map_err(|e| format!("{}: {e}", f()).into())
    }
}

impl<T> Context<T> for Option<T> {
    fn context(self, msg: impl std::fmt::Display) -> Result<T> {
        self.ok_or_else(|| format!("{msg}").into())
    }

    fn with_context<F, M>(self, f: F) -> Result<T>
    where
        F: FnOnce() -> M,
        M: std::fmt::Display,
    {
        self.ok_or_else(|| format!("{}", f()).into())
    }
}