envigil 0.4.0

Keep vigil over your environment — load, parse, and validate env vars with zero dependencies.
Documentation
//! Error types for environment configuration.
//!
//! All errors are collected into a single [`Error`] type. Validation
//! failures are accumulated so the user sees every problem at once,
//! not just the first one.

use std::fmt;

/// A specialized `Result` type for environment operations.
pub type Result<T> = std::result::Result<T, Error>;

/// The top-level error type for `envigil`.
///
/// # Examples
///
/// ```
/// use envigil::Error;
///
/// let err = Error::missing("APP_PORT");
/// assert_eq!(
///     err.to_string(),
///     "environment variable 'APP_PORT' is required but not set"
/// );
/// ```
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Error {
    kind: ErrorKind,
}

/// The category of failure.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ErrorKind {
    /// A required variable was not present in the environment.
    Missing {
        /// The full variable name (including prefix).
        name: String,
    },

    /// A parser closure returned an error.
    Parse {
        /// The full variable name.
        name: String,
        /// The raw string that failed to parse.
        raw: String,
        /// The parser's error message.
        message: String,
    },

    /// One or more validators rejected a value.
    Validation {
        /// All validation failures, in declaration order.
        errors: Vec<ValidationError>,
    },

    /// A variable was requested from a loaded config but was never
    /// declared.
    NotFound {
        /// The requested name.
        name: String,
    },

    /// Multiple independent errors occurred during loading.
    Multiple {
        /// All errors, in declaration order.
        errors: Vec<Error>,
    },
}

/// A single validation failure for one variable.
///
/// # Examples
///
/// ```
/// use envigil::error::ValidationError;
///
/// let ve = ValidationError::new("APP_PORT", "must be 1–65535")
///     .with_hint("check the PORT value in your .env file");
///
/// assert_eq!(ve.name, "APP_PORT");
/// assert_eq!(ve.message, "must be 1–65535");
/// assert_eq!(ve.hint.as_deref(), Some("check the PORT value in your .env file"));
/// ```
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ValidationError {
    /// The full variable name (including prefix).
    pub name: String,
    /// What went wrong, lowercase, no trailing period.
    pub message: String,
    /// Optional actionable suggestion.
    pub hint: Option<String>,
}

impl Error {
    /// A required variable is absent.
    pub fn missing(name: impl Into<String>) -> Self {
        Self {
            kind: ErrorKind::Missing { name: name.into() },
        }
    }

    /// A parser failed on a raw string.
    pub fn parse(
        name: impl Into<String>,
        raw: impl Into<String>,
        message: impl Into<String>,
    ) -> Self {
        Self {
            kind: ErrorKind::Parse {
                name: name.into(),
                raw: raw.into(),
                message: message.into(),
            },
        }
    }

    /// One or more validators failed.
    ///
    /// # Panics
    ///
    /// Panics if `errors` is empty. Use [`Error::validation_one`] for
    /// the single-error case.
    #[must_use]
    pub fn validation(errors: Vec<ValidationError>) -> Self {
        assert!(!errors.is_empty(), "validation errors must not be empty");
        Self {
            kind: ErrorKind::Validation { errors },
        }
    }

    /// A single validation failure.
    #[must_use]
    pub fn validation_one(error: ValidationError) -> Self {
        Self {
            kind: ErrorKind::Validation {
                errors: vec![error],
            },
        }
    }

    /// A variable was not declared in the loaded config.
    pub fn not_found(name: impl Into<String>) -> Self {
        Self {
            kind: ErrorKind::NotFound { name: name.into() },
        }
    }

    /// The underlying kind.
    #[must_use]
    pub const fn kind(&self) -> &ErrorKind {
        &self.kind
    }

    /// Consume the error and return the kind.
    #[must_use]
    pub fn into_kind(self) -> ErrorKind {
        self.kind
    }

    /// Multiple independent errors.
    ///
    /// # Panics
    ///
    /// Panics if `errors` is empty.
    #[must_use]
    pub fn multiple(errors: Vec<Self>) -> Self {
        assert!(!errors.is_empty(), "errors must not be empty");
        Self {
            kind: ErrorKind::Multiple { errors },
        }
    }
}

impl ValidationError {
    /// Create a validation error with no hint.
    pub fn new(name: impl Into<String>, message: impl Into<String>) -> Self {
        Self {
            name: name.into(),
            message: message.into(),
            hint: None,
        }
    }

    /// Attach an actionable hint.
    #[must_use]
    pub fn with_hint(mut self, hint: impl Into<String>) -> Self {
        self.hint = Some(hint.into());
        self
    }
}

impl fmt::Display for Error {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match &self.kind {
            ErrorKind::Missing { name } => {
                write!(f, "environment variable '{name}' is required but not set")
            }

            ErrorKind::Parse { name, raw, message } => {
                write!(f, "failed to parse '{name}': {message} (received: {raw:?})")
            }

            ErrorKind::Validation { errors } => {
                let count = errors.len();
                writeln!(
                    f,
                    "environment configuration failed ({count} error{})",
                    if count == 1 { "" } else { "s" },
                )?;

                for (i, ve) in errors.iter().enumerate() {
                    if i > 0 {
                        writeln!(f)?;
                    }
                    writeln!(f, "  ┌─ {}", ve.name)?;
                    writeln!(f, "  │")?;
                    writeln!(f, "  │   {}", ve.message)?;
                    if let Some(hint) = &ve.hint {
                        writeln!(f, "  │   hint: {hint}")?;
                    }
                }

                Ok(())
            }

            ErrorKind::Multiple { errors } => {
                let count = errors.len();
                writeln!(
                    f,
                    "environment configuration failed ({count} error{})",
                    if count == 1 { "" } else { "s" },
                )?;

                for (i, e) in errors.iter().enumerate() {
                    if i > 0 {
                        writeln!(f)?;
                    }
                    for line in e.to_string().lines() {
                        writeln!(f, "  {line}")?;
                    }
                }

                Ok(())
            }

            ErrorKind::NotFound { name } => {
                write!(
                    f,
                    "variable '{name}' was not declared in this configuration"
                )
            }
        }
    }
}

impl fmt::Display for ValidationError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}: {}", self.name, self.message)?;
        if let Some(hint) = &self.hint {
            write!(f, " (hint: {hint})")?;
        }
        Ok(())
    }
}

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

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

impl From<ValidationError> for Error {
    fn from(ve: ValidationError) -> Self {
        Self::validation_one(ve)
    }
}

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

    #[test]
    fn missing_display() {
        let err = Error::missing("APP_PORT");
        assert_eq!(
            err.to_string(),
            "environment variable 'APP_PORT' is required but not set"
        );
    }

    #[test]
    fn parse_display() {
        let err = Error::parse("APP_PORT", "abc", "invalid digit");
        assert_eq!(
            err.to_string(),
            "failed to parse 'APP_PORT': invalid digit (received: \"abc\")"
        );
    }

    #[test]
    fn single_validation_display() {
        let err = Error::validation_one(
            ValidationError::new("APP_PORT", "must be 1–65535").with_hint("check your .env file"),
        );

        let text = err.to_string();
        assert!(text.contains("1 error"));
        assert!(text.contains("APP_PORT"));
        assert!(text.contains("must be 1–65535"));
        assert!(text.contains("hint: check your .env file"));
    }

    #[test]
    fn multi_validation_display() {
        let err = Error::validation(vec![
            ValidationError::new("APP_PORT", "must be 1–65535"),
            ValidationError::new("APP_DATABASE_URL", "required but not set")
                .with_hint("set APP_DATABASE_URL"),
        ]);

        let text = err.to_string();
        assert!(text.contains("2 errors"));
        assert!(text.contains("APP_PORT"));
        assert!(text.contains("APP_DATABASE_URL"));
        assert!(text.contains("hint: set APP_DATABASE_URL"));
    }

    #[test]
    fn not_found_display() {
        let err = Error::not_found("APP_MISSING");
        assert_eq!(
            err.to_string(),
            "variable 'APP_MISSING' was not declared in this configuration"
        );
    }

    #[test]
    fn kind_roundtrip() {
        let err = Error::missing("X");
        assert!(matches!(err.kind(), ErrorKind::Missing { name } if name == "X"));

        let kind = err.into_kind();
        assert!(matches!(kind, ErrorKind::Missing { .. }));
    }

    #[test]
    fn from_validation_error() {
        let ve = ValidationError::new("X", "bad");
        let err: Error = ve.into();
        assert!(matches!(err.kind(), ErrorKind::Validation { errors } if errors.len() == 1));
    }

    #[test]
    fn validation_error_display() {
        let ve = ValidationError::new("X", "bad").with_hint("fix it");
        assert_eq!(ve.to_string(), "X: bad (hint: fix it)");

        let ve2 = ValidationError::new("Y", "worse");
        assert_eq!(ve2.to_string(), "Y: worse");
    }

    #[test]
    #[should_panic(expected = "validation errors must not be empty")]
    fn empty_validation_panics() {
        let _ = Error::validation(vec![]);
    }

    #[test]
    fn error_is_send_sync() {
        fn assert_send_sync<T: Send + Sync>() {}
        assert_send_sync::<Error>();
        assert_send_sync::<ValidationError>();
    }

    #[test]
    fn multiple_display() {
        let err = Error::multiple(vec![
            Error::missing("APP_PORT"),
            Error::parse("APP_TIMEOUT", "abc", "invalid digit"),
        ]);
        let text = err.to_string();
        assert!(text.contains("2 errors"), "message: {text}");
        assert!(text.contains("APP_PORT"), "message: {text}");
        assert!(text.contains("APP_TIMEOUT"), "message: {text}");
    }
}