envigil 0.4.0

Keep vigil over your environment — load, parse, and validate env vars with zero dependencies.
Documentation
# envigil

[![Crates.io](https://img.shields.io/crates/v/envigil?logo=rust)](https://crates.io/crates/envigil)
[![docs.rs](https://img.shields.io/docsrs/envigil?logo=docsdotrs)](https://docs.rs/envigil)
[![CI](https://github.com/jezman/envigil/actions/workflows/ci.yml/badge.svg)](https://github.com/jezman/envigil/actions/workflows/ci.yml)
[![License](https://img.shields.io/crates/l/envigil.svg)](#license)
[![MSRV](https://img.shields.io/badge/MSRV-1.85-blue)](#minimum-supported-rust-version)

Keep vigil over your environment.

Load, parse, and validate environment variables with zero dependencies and first-class error reporting.

## Why envigil?

|                            | `std::env` | `envy` | `envconfig` | `dotenvy` | `figment` | `config` |  `envigil`   |
| -------------------------- | :--------: | :----: | :---------: | :-------: | :-------: | :------: | :----------: |
| Zero dependencies          |     ✅     |   ❌   |     ❌      |    ❌     |    ❌     |    ❌    |      ✅      |
| Typed parsing              |     ❌     |   ✅   |     ✅      |    ❌     |    ✅     |    ✅    |      ✅      |
| Semantic validation        |     ❌     |   ❌   |     ❌      |    ❌     |    ❌     |    ❌    |      ✅      |
| Multi-error reporting      |     ❌     |   ❌   |     ❌      |    ❌     |    ❌     |    ❌    |      ✅      |
| Secret redaction           |     ❌     |   ❌   |     ❌      |    ❌     |    ❌     |    ❌    |      ✅      |
| `.env` file support        |     ❌     |   ❌   |     ❌      |    ✅     |    ✅     |    ✅    | ✅ (feature) |
| Derive macro               |     ❌     |   ✅   |     ✅      |    ❌     |    ❌     |    ❌    | ✅ (feature) |
| Layered sources            |     ❌     |   ❌   |     ❌      |    ❌     |    ✅     |    ✅    |      ✅      |
| Testing without `std::env` |     ❌     |   ❌   |     ❌      |    ❌     |    ✅     |    ✅    |      ✅      |
| Miette diagnostics         |     ❌     |   ❌   |     ❌      |    ❌     |    ❌     |    ❌    | ✅ (feature) |

`envigil` is not a replacement for `figment` or `config` (layered providers, async, file formats). It is a lightweight alternative to `envy` / `envconfig` for those who need validation, multi-error reporting, and secret redaction without pulling in dependencies.

The core crate is std-only. No `serde`, no `syn`, no `anyhow`. Proc-macro, `.env`, and `miette` support are opt-in feature flags.

## Quick start

```toml
[dependencies]
envigil = "0.3"
```

### Builder API

```rust
use envigil::{EnvSource, VarBuilder};
use envigil::validate;
use envigil::layer;
use std::time::Duration;

fn main() -> Result<(), envigil::Error> {
    let cfg = EnvSource::new()
        .prefix("APP_")
        .layer(layer::env())
        .declare(
            VarBuilder::new("PORT", |v| v.parse::<u16>().map_err(|e| e.to_string()))
                .default(8080)
                .validate(validate::range(1..=65535)),
        )
        .declare(
            VarBuilder::new("DATABASE_URL", |v| Ok(v.to_owned()))
                .required()
                .secret(),
        )
        .declare(
            VarBuilder::new("TIMEOUT", envigil::parse::duration)
                .default(Duration::from_secs(30)),
        )
        .load()?;

    let port: &u16 = cfg.get("APP_PORT")?;
    let url: &envigil::Secret<String> = cfg.get("APP_DATABASE_URL")?;
    println!("listening on :{port}");
    println!("db = {url}"); // prints: db = [REDACTED]
    Ok(())
}
```

### Derive API

```toml
[dependencies]
envigil = { version = "0.3", features = ["derive"] }
```

```rust
use envigil::{EnvConfig, Secret};

#[derive(Debug, EnvConfig)]
#[env(prefix = "APP_")]
struct Config {
    #[env(default = "8080")]
    port: u16,

    #[env(rename = "DB_DSN", secret)]
    database_url: Secret<String>,

    #[env(default = "30", parse_with = envigil::parse::secs)]
    timeout: std::time::Duration,

    #[env(default = "4", validate(range(1..=128)))]
    workers: u32,

    #[env(skip)]
    runtime_state: u32,

    #[env(validate(not_empty))]
    #[env(validate(url))]
    webhook_url: String,

    #[env(validate(one_of(["debug", "info", "warn", "error"])))]
    log_level: String,
}

let cfg = Config::from_env()?;
```

Generated constructors:

| Constructor                | Description                                                                                              |
| -------------------------- | -------------------------------------------------------------------------------------------------------- |
| `Config::from_env()`       | Loads from the process environment.                                                                      |
| `Config::from_map(values)` | Uses an in-memory map as a fallback. Useful for tests. Real environment variables still take precedence. |

Field attributes:

| Attribute                          | Description                                                                            |
| ---------------------------------- | -------------------------------------------------------------------------------------- |
| `#[env(default = "value")]`        | Parse and use this fallback when the variable is absent.                               |
| `#[env(secret)]`                   | Wrap the parsed value in `Secret<T>`.                                                  |
| `#[env(parse_with = path)]`        | Use a custom parser `fn(&str) -> Result<T, String>`.                                   |
| `#[env(rename = "VAR_NAME")]`      | Use exactly this environment variable name. The struct-level prefix is not applied.    |
| `#[env(validate(range(1..=128)))]` | Add a validator. Bare built-in validators resolve as `envigil::validate::<validator>`. |
| `#[env(skip)]`                     | Do not read from environment; initialize the field from `Default::default()`.          |

Multiple validators can be attached:

```rust
#[env(validate(non_empty(), contains("@")))]
email: String,
```

## Layered sources

`EnvSource` accepts an ordered list of layers. The first layer returning a value wins:

```rust
use envigil::layer;

let cfg = EnvSource::new()
    .layer(layer::env())           // highest priority
    .layer(layer::dotenv())        // .env file
    .layer(layer::map([            // test fallback
        ("APP_PORT", "9090"),
    ]))
    .declare(...)
    .load()?;
```

Layer insertion order = priority order.

Built-in layers: `layer::env()`, `layer::map(...)`, `layer::dotenv()`, `layer::dotenv_path(path)`.

Custom layers — any closure `Fn(&str) -> Option<String>`:

```rust
.layer(|name: &str| -> Option<String> {
    match name {
        "APP_MODE" => Some("production".to_owned()),
        _ => None,
    }
})
```

When no layers are added, `load()` reads from `std::env` automatically (backward compat).

## Testing without `std::env`

```rust
let cfg = EnvSource::from_map([
    ("APP_PORT", "9090"),
    ("APP_HOST", "0.0.0.0"),
])
.declare(VarBuilder::new("APP_PORT", |v| v.parse::<u16>().map_err(|e| e.to_string())))
.load()?;

assert_eq!(*cfg.get::<u16>("APP_PORT")?, 9090);
```

No `unsafe { std::env::set_var(...) }` in tests.

## Error output

All errors are collected and reported together:

```text
environment configuration failed (2 errors)
  ┌─ APP_PORT
  │
  │   value 99999 is out of range 1..=65535
  ┌─ APP_DATABASE_URL
  │
  │   environment variable 'APP_DATABASE_URL' is required but not set
  │   hint: set APP_DATABASE_URL or provide a .env file
```

### Miette diagnostics (feature = `"miette"`)

```toml
[dependencies]
envigil = { version = "0.3", features = ["miette"] }
```

```rust
if let Err(err) = EnvSource::new().declare(...).load() {
    let report: miette::Report = err.into();
    println!("{report:?}");
}
```

Each error gets a code (`envigil::missing`, `envigil::parse`, `envigil::validation`), severity, and help text. Parse errors show the raw value with an underline. Multi-errors expand as related diagnostics.

## Validation

Built-in validators:

| Validator                      | Description                                             |
| ------------------------------ | ------------------------------------------------------- |
| `range(1..=65535)`             | Number within an inclusive range                        |
| `not_empty()`                  | Non-empty string                                        |
| `contains("@")`                | Contains a substring                                    |
| `starts_with("postgres://")`   | Starts with a prefix                                    |
| `ends_with(".rs")`             | Ends with a suffix                                      |
| `length(1..=255)`              | String or collection length within a range              |
| `ip()`                         | Valid IP address (v4 or v6)                             |
| `hostname()`                   | Valid hostname per RFC 1123                             |
| `host()`                       | Valid IP or hostname                                    |
| `email()`                      | Basic email validation (zero-dep, practical checks)     |
| `file_exists()`                | Path exists on the filesystem                           |
| `url()`                        | Basic URL validation (scheme, authority, no whitespace) |
| `strict_url()` (feature `url`) | Strict RFC 3986 validation                              |
| `one_of(["a", "b"])`           | Value matches one of the allowed strings                |

Custom validators — any closure via `validate_with`, or a `Validator<T>` impl:

```rust
VarBuilder::new("WORKERS", |v| v.parse::<u32>().map_err(|e| e.to_string()))
    .validate_with(|n| {
        if *n > 0 { Ok(()) } else { Err("must be positive".to_owned()) }
    })
```

## Parse helpers

| Function                                   | Input                                 | Output                |
| ------------------------------------------ | ------------------------------------- | --------------------- |
| `parse::secs("30")`                        | Seconds                               | `Duration`            |
| `parse::millis("500")`                     | Milliseconds                          | `Duration`            |
| `parse::duration("5m 30s")`                | Units: `ms`, `s`, `m`, `h`            | `Duration`            |
| `parse::bytes("10MB")`                     | `B`/`KB`/`MB`/`GB`, `KiB`/`MiB`/`GiB` | `u64`                 |
| `parse::bool("yes")`                       | true/1/yes/on, false/0/no/of          | `bool`                |
| `parse::flag("yes")`                       | (deprecated, use `bool`)              | `bool`                |
| `parse::list("a, b")`                      | Comma-separated                       | `Vec<String>`         |
| `parse::list_sep(';')`                     | Custom separator                      | `Vec<String>`         |
| `parse::socket_addr("0.0.0.0:8080")`       | Socket address (IPv4/IPv6)            | `SocketAddr`          |
| `parse::url("https://...")`                | URL string                            | `String (normalized)` |
| `parse::strict_url("...")` (feature `url`) | URL string                            | `url::Url` (RFC 3986) |

## Secret handling

Variables marked with `.secret()` are stored as `Secret<T>`:

- `Debug` / `Display` → `[REDACTED]`
- Access the value only via `.expose()` or `.into_inner()`
- `get::<String>()` on a secret variable returns an error (type mismatch protection)
- `.map(f)` — transform without exposing: `Secret<T> → Secret<U>`
- `.as_ref()` — borrow the inner value by reference without consuming

```rust
let db_url: Secret<String> = cfg.get("DATABASE_URL")?.clone();

// Safe transformation — intermediate value never leaves the closure
let host: Secret<String> = db_url.map(|url| {
    url.split("://")
        .nth(1)
        .and_then(|r| r.split('/').next())
        .unwrap_or("unknown")
        .to_owned()
});
println!("connecting to {host}"); // [REDACTED]

// Borrow without consuming
assert_eq!(db_url.as_ref().len(), 42);
```

## `.env` file support

```toml
[dependencies]
envigil = { version = "0.3", features = ["dotenv"] }
```

```rust
let cfg = EnvSource::new()
    .layer(layer::dotenv())                     // .env from CWD
    .layer(layer::dotenv_path(".env.local"))    // or a specific path
    .declare(...)
    .load()?;
```

Real environment variables take priority when `layer::env()` is added first. Missing files are silently ignored. `std::env` is never mutated.

## Feature flags

| Feature  | Default | Adds                                                            |
| -------- | :-----: | --------------------------------------------------------------- |
| `derive` |   ❌    | `#[derive(EnvConfig)]` (pulls `envigil-derive`)                 |
| `dotenv` |   ❌    | `.env` file loading (own parser, no external deps)              |
| `miette` |   ❌    | `miette::Diagnostic` for rich error rendering                   |
| `url`    |   ❌    | `parse::strict_url`, `validate::strict_url` (pulls `url` crate) |

With no features enabled, `envigil` has zero dependencies.

## Minimum Supported Rust Version

1.85.0 (edition 2024). MSRV bumps come with a minor version bump and are noted in the changelog.

## License

Licensed under either of [Apache License, Version 2.0](LICENSE-APACHE) or [MIT license](LICENSE-MIT) at your option.