envigil 0.1.1

Keep vigil over your environment — load, parse, and validate env vars with zero dependencies.
Documentation
//! Custom validation — no features required.
//!
//! Run:
//!   APP_EMAIL=user@example.com APP_DSN=postgres://localhost/db \
//!     cargo run --example validation

use envigil::validate::{self, Validator};
use envigil::{EnvSource, VarBuilder};

struct EvenOnly;

impl Validator<u32> for EvenOnly {
    fn validate(&self, value: &u32) -> Result<(), String> {
        if value % 2 == 0 {
            Ok(())
        } else {
            Err(format!("{value} is odd"))
        }
    }
}

fn main() -> Result<(), envigil::Error> {
    let cfg = EnvSource::new()
        .prefix("APP_")
        .declare(
            VarBuilder::new("WORKERS", |v| v.parse::<u32>().map_err(|e| e.to_string()))
                .default(4)
                .validate(validate::range(1..=128))
                .validate(EvenOnly),
        )
        .declare(
            VarBuilder::new("EMAIL", |v| Ok(v.to_owned()))
                .default("dev@localhost".to_owned())
                .validate(validate::not_empty())
                .validate(validate::contains("@")),
        )
        .declare(
            VarBuilder::new("DSN", |v| Ok(v.to_owned()))
                .default("postgres://localhost/dev".to_owned())
                .validate(validate::starts_with("postgres://")),
        )
        .load()?;

    println!("workers: {}", cfg.get::<u32>("APP_WORKERS")?);
    println!("email:   {}", cfg.get::<String>("APP_EMAIL")?);
    println!("dsn:     {}", cfg.get::<String>("APP_DSN")?);

    Ok(())
}