envigil 0.3.0

Keep vigil over your environment — load, parse, and validate env vars with zero dependencies.
Documentation
//! Validation — built-in and custom validators. No features required.
//!
//! Demonstrates every built-in validator, including the ones added in
//! 0.2.0: `length`, `ip`, and `file_exists`.
//!
//! Run: cargo run --example validation
//!
//! Or override values:
//!   APP_EMAIL=user@example.com APP_BIND_IP=10.0.0.5 \
//!     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://")),
        )
        // New in 0.2.0: length, ip, file_exists.
        .declare(
            VarBuilder::new("API_KEY", |v| Ok(v.to_owned()))
                .default("abcd-1234-efgh".to_owned())
                .validate(validate::length(8..=64)),
        )
        .declare(
            VarBuilder::new("BIND_IP", |v| Ok(v.to_owned()))
                .default("127.0.0.1".to_owned())
                .validate(validate::ip()),
        )
        .declare(
            // Assumes the example is run from the crate root (cargo run).
            VarBuilder::new("CONFIG_FILE", |v| Ok(v.to_owned()))
                .default("Cargo.toml".to_owned())
                .validate(validate::file_exists()),
        )
        .load()?;

    println!("workers:     {}", cfg.get::<u32>("APP_WORKERS")?);
    println!("email:       {}", cfg.get::<String>("APP_EMAIL")?);
    println!("dsn:         {}", cfg.get::<String>("APP_DSN")?);
    println!("api_key:     {}", cfg.get::<String>("APP_API_KEY")?);
    println!("bind_ip:     {}", cfg.get::<String>("APP_BIND_IP")?);
    println!("config_file: {}", cfg.get::<String>("APP_CONFIG_FILE")?);
    Ok(())
}