envigil 0.3.0

Keep vigil over your environment — load, parse, and validate env vars with zero dependencies.
Documentation
//! [`miette::Diagnostic`] integration for envigil errors.
//!
//! This module is only available when the `miette` feature is enabled.
//! It implements [`miette::Diagnostic`] on [`Error`] and
//! [`ValidationError`] so that users can render rich diagnostic output
//! via miette's reporters.
//!
//! # Examples
//!
//! ```no_run
//! use envigil::{EnvSource, VarBuilder};
//! use miette::IntoDiagnostic;
//!
//! # fn main() -> miette::Result<()> {
//! let result = EnvSource::new()
//!     .declare(VarBuilder::new("PORT", |v| v.parse::<u16>().map_err(|e| e.to_string()))
//!         .required())
//!     .load();
//!
//! // Convert to a miette Report for pretty printing:
//! if let Err(err) = result {
//!     let report: miette::Report = err.into();
//!     println!("{report:?}");
//! }
//! # Ok(())
//! # }
//! ```

use crate::error::{Error, ErrorKind, ValidationError};
use miette::{Diagnostic, LabeledSpan, Severity, SourceCode};
use std::fmt;

impl Diagnostic for Error {
    fn code<'a>(&'a self) -> Option<Box<dyn fmt::Display + 'a>> {
        let code = match &self.kind() {
            ErrorKind::Missing { .. } => "envigil::missing",
            ErrorKind::Parse { .. } => "envigil::parse",
            ErrorKind::Validation { .. } => "envigil::validation",
            ErrorKind::NotFound { .. } => "envigil::not_found",
            ErrorKind::Multiple { .. } => "envigil::multiple",
        };
        Some(Box::new(code))
    }

    fn severity(&self) -> Option<Severity> {
        Some(Severity::Error)
    }

    fn help<'a>(&'a self) -> Option<Box<dyn fmt::Display + 'a>> {
        match &self.kind() {
            ErrorKind::Missing { name } => Some(Box::new(format!(
                "set the environment variable '{name}', add it to a .env file, \
                 or provide a default value"
            ))),
            ErrorKind::Parse { name, raw, message } => Some(Box::new(format!(
                "'{name}' received value {raw:?} which failed to parse: {message}"
            ))),
            ErrorKind::Validation { errors } => {
                // Aggregate hints from all validation errors.
                let hints: Vec<&str> = errors.iter().filter_map(|ve| ve.hint.as_deref()).collect();
                if hints.is_empty() {
                    None
                } else {
                    Some(Box::new(hints.join("; ")))
                }
            }
            ErrorKind::NotFound { name } => Some(Box::new(format!(
                "declare '{name}' with EnvSource::declare() before calling get()"
            ))),
            ErrorKind::Multiple { errors } => {
                // Collect help from sub-errors.
                let helps: Vec<String> = errors
                    .iter()
                    .filter_map(|e| e.help().map(|h| h.to_string()))
                    .collect();
                if helps.is_empty() {
                    None
                } else {
                    Some(Box::new(helps.join("\n")))
                }
            }
        }
    }

    fn source_code(&self) -> Option<&dyn SourceCode> {
        match self.kind() {
            ErrorKind::Parse { raw, .. } => Some(raw as &dyn SourceCode),
            _ => None,
        }
    }

    fn labels(&self) -> Option<Box<dyn Iterator<Item = LabeledSpan> + '_>> {
        match &self.kind() {
            ErrorKind::Parse { raw, message, .. } => {
                let label = LabeledSpan::new_with_span(
                    Some(message.clone()),
                    miette::SourceSpan::new(0.into(), raw.len()),
                );
                Some(Box::new(std::iter::once(label)))
            }
            _ => None,
        }
    }

    fn related<'a>(&'a self) -> Option<Box<dyn Iterator<Item = &'a dyn Diagnostic> + 'a>> {
        match &self.kind() {
            ErrorKind::Validation { errors } => {
                Some(Box::new(errors.iter().map(|ve| ve as &dyn Diagnostic)))
            }
            ErrorKind::Multiple { errors } => {
                Some(Box::new(errors.iter().map(|e| e as &dyn Diagnostic)))
            }
            _ => None,
        }
    }
}

impl Diagnostic for ValidationError {
    fn code<'a>(&'a self) -> Option<Box<dyn fmt::Display + 'a>> {
        Some(Box::new("envigil::validation"))
    }

    fn severity(&self) -> Option<Severity> {
        Some(Severity::Error)
    }

    fn help<'a>(&'a self) -> Option<Box<dyn fmt::Display + 'a>> {
        self.hint
            .as_ref()
            .map(|h| Box::new(h.clone()) as Box<dyn fmt::Display>)
    }
}

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

    #[test]
    fn missing_error_diagnostic() {
        let err = Error::missing("APP_PORT");
        assert_eq!(err.code().unwrap().to_string(), "envigil::missing");
        assert_eq!(err.severity(), Some(Severity::Error));
        assert!(err.help().is_some());
        assert!(err.source_code().is_none());
        assert!(err.labels().is_none());
        assert!(err.related().is_none());
    }

    #[test]
    fn parse_error_has_source_and_label() {
        let err = Error::parse("APP_PORT", "abc", "invalid digit");
        assert_eq!(err.code().unwrap().to_string(), "envigil::parse");
        assert!(err.source_code().is_some());
        let labels: Vec<_> = err.labels().unwrap().collect();
        assert_eq!(labels.len(), 1);
        assert_eq!(labels[0].offset(), 0);
        assert_eq!(labels[0].len(), 3); // "abc".len()
        assert_eq!(labels[0].label(), Some("invalid digit"));
    }

    #[test]
    fn validation_error_related() {
        let err = Error::validation(vec![
            ValidationError::new("APP_PORT", "out of range").with_hint("use 1-65535"),
            ValidationError::new("APP_HOST", "must not be empty"),
        ]);
        assert_eq!(err.code().unwrap().to_string(), "envigil::validation");
        let related: Vec<_> = err.related().unwrap().collect();
        assert_eq!(related.len(), 2);
        // Help aggregates hints.
        let help = err.help().unwrap().to_string();
        assert!(help.contains("use 1-65535"));
    }

    #[test]
    fn multiple_error_related() {
        let err = Error::multiple(vec![
            Error::missing("APP_PORT"),
            Error::parse("APP_TIMEOUT", "abc", "invalid digit"),
        ]);
        assert_eq!(err.code().unwrap().to_string(), "envigil::multiple");
        let related: Vec<_> = err.related().unwrap().collect();
        assert_eq!(related.len(), 2);
    }

    #[test]
    fn not_found_error_diagnostic() {
        let err = Error::not_found("APP_MISSING");
        assert_eq!(err.code().unwrap().to_string(), "envigil::not_found");
        assert!(err.help().is_some());
    }

    #[test]
    fn validation_error_diagnostic() {
        let ve = ValidationError::new("APP_PORT", "out of range").with_hint("use 1-65535");
        assert_eq!(ve.code().unwrap().to_string(), "envigil::validation");
        assert_eq!(ve.severity(), Some(Severity::Error));
        assert_eq!(ve.help().unwrap().to_string(), "use 1-65535");
    }

    #[test]
    fn validation_error_without_hint() {
        let ve = ValidationError::new("APP_PORT", "out of range");
        assert!(ve.help().is_none());
    }
}