Skip to main content

env_reader/
lib.rs

1//! Reading a program's configuration out of environment variables.
2//!
3//! A program configured by the environment and nothing else — no files, no
4//! defaults baked into an image, no service discovery — needs one place
5//! that turns a variable into a value, so the rules that turn out to matter
6//! are stated once. This is that place.
7//!
8//! # Three rules worth knowing before anything else
9//!
10//! **Blank is absent.** A variable set to `""`, or to spaces, means the
11//! same thing as an unset variable. Deployments produce blank values
12//! routinely — a templated value whose source was empty, an `.env` line
13//! with nothing after the `=` — and treating those as "configured, to the
14//! empty string" produces failures a long way from their cause. It applies
15//! uniformly, including to integers, where the obvious implementation would
16//! instead try to parse `""` and report a malformed number.
17//!
18//! **Every problem is reported at once.** [`Reader`] accumulates problems
19//! rather than returning the first, so a program with four missing
20//! variables says so once instead of over four restarts. Each getter
21//! returns a usable value even when it failed, so a whole configuration
22//! reads as one straight run of statements with no `?` after every line;
23//! [`Reader::finish`] is what decides whether any of it was valid.
24//!
25//! **A secret never prints.** [`Secret`] holds one and renders as
26//! `<redacted>` through both [`Debug`] and [`std::fmt::Display`] — not
27//! `Debug` alone, which is the common half-measure that leaves every
28//! `Display`-based logging macro wide open. A configuration struct ends up
29//! in a log line eventually, and a connection string with an access key in
30//! it must not be what is there.
31//!
32//! # Two smaller decisions
33//!
34//! **An unparseable value is never a silent fallback.** [`Reader::integer_or`]
35//! takes the default *and records the problem*, because a program quietly
36//! running on a default nobody chose is harder to diagnose than one that
37//! will not start.
38//!
39//! **Booleans are read strictly.** [`parse_bool`] accepts four spellings
40//! each way and answers `None` to anything else, rather than the tempting
41//! "not false-ish, therefore true" — under which `ENABLED=disabled` comes
42//! out true and the deployment looks configured.
43//! [`parse_bool_lenient`] is there for an existing estate that already
44//! depends on that behaviour.
45//!
46//! # Examples
47//!
48//! ```
49//! use env_reader::Reader;
50//!
51//! let mut reader = Reader::from_pairs([
52//!     ("SERVICE_NAME", "orders"),
53//!     ("PORT", "8443"),
54//!     ("REGION", "   "), // blank: the same as absent
55//! ]);
56//!
57//! let service: String = reader.required_string("SERVICE_NAME");
58//! let port: u16 = reader.integer_or("PORT", 8080);
59//! let region: Option<String> = reader.optional_string("REGION");
60//!
61//! reader.finish().expect("the configuration is complete");
62//! assert_eq!(service, "orders");
63//! assert_eq!(port, 8443);
64//! assert_eq!(region, None);
65//! ```
66//!
67//! A whole configuration, with every problem reported together:
68//!
69//! ```
70//! use env_reader::{Errors, Reader, Secret};
71//!
72//! #[derive(Debug)]
73//! struct Config {
74//!     service_name: String,
75//!     port: u16,
76//!     database_password: Secret,
77//! }
78//!
79//! fn load() -> Result<Config, Errors> {
80//!     let mut reader = Reader::from_pairs([("PORT", "eighty")]);
81//!     let config = Config {
82//!         service_name: reader.required_string("SERVICE_NAME"),
83//!         port: reader.integer_or("PORT", 8080),
84//!         database_password: reader.required_secret("DB_PASSWORD"),
85//!     };
86//!     reader.finish_with(config)
87//! }
88//!
89//! let errors = load().unwrap_err();
90//! assert_eq!(errors.len(), 3, "all three, not just the first");
91//! ```
92//!
93//! # Features
94//!
95//! - `uuid` — adds [`Reader::required_uuid`] and
96//!   [`Reader::optional_uuid`]. Off by default; with it off this crate has
97//!   no dependencies at all.
98
99#![cfg_attr(test, allow(clippy::unwrap_used, clippy::expect_used, clippy::panic))]
100
101mod error;
102mod reader;
103mod secret;
104mod value;
105
106pub use error::{Error, Errors};
107pub use reader::Reader;
108pub use secret::Secret;
109pub use value::{
110    FALSE_SPELLINGS, TRUE_SPELLINGS, parse_bool, parse_bool_lenient, parse_csv, parse_separated,
111    present,
112};