env-reader 0.1.0

Read configuration from environment variables: blank is absent, every problem is reported at once, and a secret never prints.
Documentation
  • Coverage
  • 100%
    20 out of 20 items documented9 out of 9 items with examples
  • Size
  • Source code size: 79.0 kB This is the summed size of all the files inside the crates.io package for this release.
  • Documentation size: 520.3 kB This is the summed size of all files generated by rustdoc for all configured targets
  • Ø build duration
  • this release: 2s Average build duration of successful builds.
  • all releases: 2s Average build duration of successful builds in releases after 2024-10-23.
  • Links
  • joelparkerhenderson/env-reader
    0 0 0
  • crates.io
  • Dependencies
  • Versions
  • Owners
  • joelparkerhenderson

env-reader

Read a program's configuration out of environment variables: blank is absent, every problem is reported at once, and a secret never prints.

use env_reader::{Errors, Reader, Secret};

#[derive(Debug)]
struct Config {
    service_name: String,
    port: u16,
    database_password: Secret,
}

fn load() -> Result<Config, Errors> {
    let mut reader = Reader::from_env();
    let config = Config {
        service_name: reader.required_string("SERVICE_NAME"),
        port: reader.integer_or("PORT", 8080),
        database_password: reader.required_secret("DB_PASSWORD"),
    };
    reader.finish_with(config)
}

Three variables wrong is one error listing all three, not three restarts:

missing required configuration: SERVICE_NAME
invalid configuration: PORT must be a whole number, got "eighty"
missing required configuration: DB_PASSWORD

Three rules

Blank is absent. A variable set to "", or to spaces, means the same thing as an unset variable. Deployments produce blank values routinely — a templated value whose source was empty, an .env line with nothing after the = — and treating those as "configured, to the empty string" produces failures a long way from their cause. It applies uniformly, including to integers, where the obvious implementation would instead try to parse "" and report a malformed number.

Every problem is reported at once. Reader accumulates problems rather than returning the first. Each getter returns a usable value even when it failed — a missing required string comes back empty — so a whole configuration reads as one straight run of statements with no ? after every line. finish is what decides whether any of it was valid.

A secret never prints. Secret renders as <redacted> through both Debug and Display — not Debug alone, which is the common half-measure that leaves every Display-based logging macro wide open. The value comes out only through expose(), which is deliberately awkward to type and easy to grep for.

# use env_reader::Secret;
#[derive(Debug)]
struct Config { endpoint: String, access_key: Secret }

let config = Config { endpoint: "sb://example".into(), access_key: Secret::new("hunter2") };
let printed = format!("{config:?}");

assert!(printed.contains("sb://example"));
assert!(!printed.contains("hunter2"));

Two smaller decisions

An unparseable value is never a silent fallback. integer_or takes the default and records the problem, because a program quietly running on a default nobody chose is harder to diagnose than one that will not start.

Booleans are read strictly. parse_bool accepts true/1/yes/on and false/0/no/off in any case, and answers None to anything else — rather than the tempting "not false-ish, therefore true", under which ENABLED=disabled comes out true and the deployment looks configured. parse_bool_lenient and Reader::lenient_bool_or exist for an estate that already depends on that older behaviour.

What you can read

Strings required_string, optional_string, string_or
Secrets required_secret, optional_secret
Integers required_integer, optional_integer, integer_or, optional_positive_integer
Anything with FromStr required_parse, optional_parse, parse_or
Booleans bool_or, lenient_bool_or
Lists list, required_list, list_or
Fixed sets required_one_of, optional_one_of
UUIDs (feature) required_uuid, optional_uuid
Your own checks invalid, conflict

The parse family takes the noun phrase its error message uses — an IP address, a socket address, an RFC 3339 timestamp — because that phrase is the whole difference between a message somebody can act on and one they cannot:

use std::net::IpAddr;
use env_reader::Reader;

let mut reader = Reader::from_pairs([("BIND", "localhost")]);
assert_eq!(reader.required_parse::<IpAddr>("BIND", "an IP address"), None);

let errors = reader.finish().unwrap_err();
assert_eq!(
    errors.to_string(),
    r#"invalid configuration: BIND must be an IP address, got "localhost""#
);

Testing

Reader::from_pairs is the constructor for tests and for configuration that arrives from somewhere other than the environment. Reader::from_env is the only function in the crate that touches global state — which std::env::set_var is unsafe for good reason — so nothing else needs it.

Dependencies

None, with default features. uuid is optional and off by default.

License

MIT or Apache-2.0, at your option.