Crate env_flags

Source
Expand description

This crate exports the env_flags macro, which allows a convenient way to declare static environment variables with optional default values and custom parsing functions.

Currently, this crate requires a Rust compiler of at least 1.80 as it uses std::sync::LazyLock under the hood.

§Examples

use env_flags::env_flags;

use std::time::Duration;

env_flags! {
    /// Required env var, panics if missing.
    AUTH_TOKEN: &str;
    /// Env var with a default value if not specified.
    pub(crate) PORT: u16 = 8080;
    /// An optional env var.
    pub OVERRIDE_HOSTNAME: Option<&str> = None;

    /// `Duration` by default is parsed as `f64` seconds.
    TIMEOUT: Duration = Duration::from_secs(5);
    /// Custom parsing function, takes a `String` and returns a `Result<Duration>`.
    TIMEOUT_MS: Duration = Duration::from_millis(30), |value| {
        value.parse().map(Duration::from_millis)
    };

    /// `bool` can be true, false, 1, or 0 (case insensitive)
    /// eg. export ENABLE_FEATURE="true"
    pub ENABLE_FEATURE: bool = true;

    /// `Vec<T>` by default is parsed as a comma-seprated string
    /// eg. export VALID_PORTS="80,443,9121"
    pub VALID_PORTS: Vec<u16> = vec![80, 443, 9121];


    // Attributes are also captured, including docs

    #[cfg(target_os = "linux")]
    /// operating system
    pub OS: &str = "linux";
    #[cfg(not(target_os = "linux"))]
    /// operating system
    pub OS: &str = "not linux";
}

For custom types, you can either specify a parsing function manually (see above TIMEOUT_MS example), or you can implement the ParseEnv trait. An implementation for ParseEnv is included for most std types.

Macros§

env_flags
Declare environment variables with optional defaults and parsing functions.

Structs§

LazyEnv
Static lazily evaluated environment variable.
ParseError
Intermediate error type used in parsing failures to generate helpful messages.

Traits§

ParseEnv
Define the parsing function for a type from a String environment variable.