pub struct Reader { /* private fields */ }Expand description
Reads a configuration from variables, accumulating problems rather than stopping at the first.
A reader is built once, asked for every value the program needs, and
then finished. Each getter returns a usable value
even when it failed — a required string that was missing comes back
empty — so a caller can read the whole configuration in one straight run
of statements without ? after every line. finish is what decides
whether any of it was valid.
That shape is the point: a program with four missing variables reports all four, once, instead of over four restarts.
§Examples
use env_reader::Reader;
#[derive(Debug)]
struct Config {
service_name: String,
port: u16,
upstreams: Vec<String>,
}
let mut reader = Reader::from_pairs([
("SERVICE_NAME", "orders"),
("PORT", "8443"),
("UPSTREAMS", "a.internal, b.internal"),
]);
let config = Config {
service_name: reader.required_string("SERVICE_NAME"),
port: reader.integer_or("PORT", 8080),
upstreams: reader.list("UPSTREAMS"),
};
reader.finish()?;
assert_eq!(config.port, 8443);
assert_eq!(config.upstreams, ["a.internal", "b.internal"]);Implementations§
Source§impl Reader
impl Reader
Sourcepub fn from_env() -> Self
pub fn from_env() -> Self
A reader over the process environment.
The only constructor that touches the environment, so every other
path is testable without mutating global state — which
std::env::set_var is unsafe for good reason.
Sourcepub fn from_pairs<K, V, I>(pairs: I) -> Self
pub fn from_pairs<K, V, I>(pairs: I) -> Self
A reader over an explicit set of variables, for tests and for configuration that arrives from somewhere other than the environment.
§Examples
use env_reader::Reader;
let mut reader = Reader::from_pairs([("PORT", "9000")]);
assert_eq!(reader.integer_or::<u16>("PORT", 8080), 9000);Sourcepub fn raw(&self, name: &str) -> Option<&str>
pub fn raw(&self, name: &str) -> Option<&str>
The raw value of a variable, trimmed, or None when absent or
blank.
§Examples
use env_reader::Reader;
let reader = Reader::from_pairs([("A", " x "), ("B", " ")]);
assert_eq!(reader.raw("A"), Some("x"));
assert_eq!(reader.raw("B"), None);
assert_eq!(reader.raw("C"), None);Sourcepub fn is_set(&self, name: &str) -> bool
pub fn is_set(&self, name: &str) -> bool
Whether a variable is set to something non-blank.
§Examples
use env_reader::Reader;
let reader = Reader::from_pairs([("A", "x"), ("B", " ")]);
assert!(reader.is_set("A"));
assert!(!reader.is_set("B"), "blank is absent");
assert!(!reader.is_set("C"));Sourcepub fn required_string(&mut self, name: &str) -> String
pub fn required_string(&mut self, name: &str) -> String
A variable that must be set.
Records Error::Missing and returns an empty string when it is
not, so reading can continue and every other problem is found too.
§Examples
use env_reader::Reader;
let mut reader = Reader::from_pairs([("SERVICE_NAME", "orders")]);
assert_eq!(reader.required_string("SERVICE_NAME"), "orders");
assert_eq!(reader.required_string("REGION"), "");
assert_eq!(reader.finish().unwrap_err().len(), 1);Sourcepub fn optional_string(&self, name: &str) -> Option<String>
pub fn optional_string(&self, name: &str) -> Option<String>
A variable that need not be set.
§Examples
use env_reader::Reader;
let reader = Reader::from_pairs([("REGION", "eu-west-2")]);
assert_eq!(reader.optional_string("REGION").as_deref(), Some("eu-west-2"));
assert_eq!(reader.optional_string("ZONE"), None);Sourcepub fn string_or(&self, name: &str, default: &str) -> String
pub fn string_or(&self, name: &str, default: &str) -> String
An optional variable with a fallback.
§Examples
use env_reader::Reader;
let reader = Reader::from_pairs([("HOST", "0.0.0.0")]);
assert_eq!(reader.string_or("HOST", "127.0.0.1"), "0.0.0.0");
assert_eq!(reader.string_or("BIND", "127.0.0.1"), "127.0.0.1");Sourcepub fn required_secret(&mut self, name: &str) -> Secret
pub fn required_secret(&mut self, name: &str) -> Secret
A secret that must be set.
§Examples
use env_reader::Reader;
let mut reader = Reader::from_pairs([("DB_PASSWORD", "hunter2")]);
let password = reader.required_secret("DB_PASSWORD");
assert_eq!(format!("{password:?}"), "<redacted>");Sourcepub fn optional_secret(&self, name: &str) -> Option<Secret>
pub fn optional_secret(&self, name: &str) -> Option<Secret>
A secret that need not be set.
§Examples
use env_reader::Reader;
let reader = Reader::from_pairs([("API_KEY", " ")]);
assert!(reader.optional_secret("API_KEY").is_none());Sourcepub fn required_integer<T>(&mut self, name: &str) -> T
pub fn required_integer<T>(&mut self, name: &str) -> T
An integer that must be set.
§Examples
use env_reader::Reader;
let mut reader = Reader::from_pairs([("PORT", "8443")]);
assert_eq!(reader.required_integer::<u16>("PORT"), 8443);Sourcepub fn optional_integer<T>(&mut self, name: &str) -> Option<T>where
T: FromStr,
pub fn optional_integer<T>(&mut self, name: &str) -> Option<T>where
T: FromStr,
An integer that need not be set.
A blank value is absent, not a parse failure.
§Examples
use env_reader::Reader;
let mut reader = Reader::from_pairs([("A", "30"), ("B", " ")]);
assert_eq!(reader.optional_integer::<u64>("A"), Some(30));
assert_eq!(reader.optional_integer::<u64>("B"), None);
assert!(reader.finish().is_ok());Sourcepub fn integer_or<T>(&mut self, name: &str, default: T) -> Twhere
T: FromStr,
pub fn integer_or<T>(&mut self, name: &str, default: T) -> Twhere
T: FromStr,
An integer with a fallback.
An unparseable value is a recorded error, not a silent fallback to the default: a program quietly running on a default nobody chose is harder to diagnose than one that will not start.
§Examples
use env_reader::Reader;
let mut reader = Reader::from_pairs([("PORT", "8443"), ("OTHER", "two")]);
assert_eq!(reader.integer_or::<u16>("PORT", 8080), 8443);
assert_eq!(reader.integer_or::<u16>("MISSING", 8080), 8080);
assert_eq!(reader.integer_or::<u16>("OTHER", 8080), 8080);
// The absent one is fine; the unparseable one is not.
assert_eq!(reader.finish().unwrap_err().len(), 1);Sourcepub fn optional_positive_integer<T>(&mut self, name: &str) -> Option<T>
pub fn optional_positive_integer<T>(&mut self, name: &str) -> Option<T>
An optional integer that, when present, must be greater than zero.
For the “absent means unlimited” shape, where a configured zero is a mistake rather than a request for an infinite wait.
§Examples
use env_reader::Reader;
let mut reader = Reader::from_pairs([("A", "30"), ("B", "0")]);
assert_eq!(reader.optional_positive_integer::<u32>("A"), Some(30));
assert_eq!(reader.optional_positive_integer::<u32>("B"), None);
assert_eq!(reader.optional_positive_integer::<u32>("C"), None);
// Only B is a problem; C was simply absent.
assert_eq!(reader.finish().unwrap_err().len(), 1);Sourcepub fn required_parse<T>(&mut self, name: &str, expected: &str) -> Option<T>where
T: FromStr,
pub fn required_parse<T>(&mut self, name: &str, expected: &str) -> Option<T>where
T: FromStr,
Any FromStr value that must be set.
expected is the noun phrase the error message uses: a socket address, an RFC 3339 timestamp, a log level. It is the whole
difference between a message somebody can act on and one they
cannot, so it is required rather than derived from the type name.
Returns None on either failure, having recorded it.
§Examples
use std::net::IpAddr;
use env_reader::Reader;
let mut reader = Reader::from_pairs([("BIND", "10.0.0.1"), ("PEER", "not-an-ip")]);
assert_eq!(
reader.required_parse::<IpAddr>("BIND", "an IP address"),
Some("10.0.0.1".parse().unwrap())
);
assert_eq!(reader.required_parse::<IpAddr>("PEER", "an IP address"), None);
let errors = reader.finish().unwrap_err();
assert!(errors.to_string().contains("PEER must be an IP address"));Sourcepub fn optional_parse<T>(&mut self, name: &str, expected: &str) -> Option<T>where
T: FromStr,
pub fn optional_parse<T>(&mut self, name: &str, expected: &str) -> Option<T>where
T: FromStr,
Any FromStr value that need not be set.
Absent is None with no error; present-but-unparseable is None
with one.
§Examples
use std::path::PathBuf;
use env_reader::Reader;
let mut reader = Reader::from_pairs([("CA_BUNDLE", "/etc/ca.pem")]);
assert_eq!(
reader.optional_parse::<PathBuf>("CA_BUNDLE", "a path"),
Some(PathBuf::from("/etc/ca.pem"))
);
assert_eq!(reader.optional_parse::<PathBuf>("OTHER", "a path"), None);
assert!(reader.finish().is_ok());Sourcepub fn parse_or<T>(&mut self, name: &str, expected: &str, default: T) -> Twhere
T: FromStr,
pub fn parse_or<T>(&mut self, name: &str, expected: &str, default: T) -> Twhere
T: FromStr,
Any FromStr value with a fallback.
As with Reader::integer_or, an unparseable value is a recorded
error rather than a silent fallback.
§Examples
use std::net::IpAddr;
use env_reader::Reader;
let mut reader = Reader::from_pairs([] as [(&str, &str); 0]);
let bind: IpAddr = reader.parse_or("BIND", "an IP address", "127.0.0.1".parse().unwrap());
assert_eq!(bind.to_string(), "127.0.0.1");
assert!(reader.finish().is_ok());Sourcepub fn bool_or(&mut self, name: &str, default: bool) -> bool
pub fn bool_or(&mut self, name: &str, default: bool) -> bool
A boolean with a fallback, read strictly by crate::parse_bool.
A value that is neither a true spelling nor a false one is a recorded error, not a silent fallback.
§Examples
use env_reader::Reader;
let mut reader = Reader::from_pairs([("TRACING", "off"), ("CACHE", "maybe")]);
assert!(!reader.bool_or("TRACING", true));
assert!(reader.bool_or("METRICS", true), "absent takes the default");
assert!(reader.bool_or("CACHE", true), "unparseable takes it too, but records");
let errors = reader.finish().unwrap_err();
assert_eq!(errors.len(), 1);
assert!(errors.to_string().contains("CACHE"));Sourcepub fn lenient_bool_or(&self, name: &str, default: bool) -> bool
pub fn lenient_bool_or(&self, name: &str, default: bool) -> bool
A boolean with a fallback, read leniently by
crate::parse_bool_lenient: anything not false-ish is true.
Never records an error, because there is no value it cannot read.
See crate::parse_bool_lenient for when that is what you want and
when it is not.
§Examples
use env_reader::Reader;
let reader = Reader::from_pairs([("LEGACY_FLAG", "disabled")]);
assert!(reader.lenient_bool_or("LEGACY_FLAG", false), "not a false spelling");Sourcepub fn list(&self, name: &str) -> Vec<String>
pub fn list(&self, name: &str) -> Vec<String>
A comma-separated list, possibly empty.
§Examples
use env_reader::Reader;
let reader = Reader::from_pairs([("UPSTREAMS", "a, b")]);
assert_eq!(reader.list("UPSTREAMS"), ["a", "b"]);
assert!(reader.list("ABSENT").is_empty());Sourcepub fn required_list(&mut self, name: &str) -> Vec<String>
pub fn required_list(&mut self, name: &str) -> Vec<String>
A comma-separated list that must be set and must have an element.
§Examples
use env_reader::Reader;
let mut reader = Reader::from_pairs([("BAD", " , ")]);
assert!(reader.required_list("ABSENT").is_empty());
assert!(reader.required_list("BAD").is_empty());
// One missing, one set to nothing but separators.
assert_eq!(reader.finish().unwrap_err().len(), 2);Sourcepub fn list_or(&mut self, name: &str, default: &str) -> Vec<String>
pub fn list_or(&mut self, name: &str, default: &str) -> Vec<String>
A comma-separated list, falling back to a default list when the variable is absent.
A variable set to only separators is a recorded error rather than an empty list, because it means someone meant to configure something.
§Examples
use env_reader::Reader;
let mut reader = Reader::from_pairs([("BAD", " , ")]);
assert_eq!(reader.list_or("METHODS", "GET,HEAD"), ["GET", "HEAD"]);
assert!(reader.list_or("BAD", "x").is_empty());
assert_eq!(reader.finish().unwrap_err().len(), 1);Sourcepub fn required_one_of(
&mut self,
name: &str,
accepted: &[&str],
) -> Option<String>
pub fn required_one_of( &mut self, name: &str, accepted: &[&str], ) -> Option<String>
A value that must be set and must be one of a fixed set.
§Examples
use env_reader::Reader;
const LEVELS: &[&str] = &["trace", "debug", "info", "warn", "error"];
let mut reader = Reader::from_pairs([("LOG_LEVEL", "verbose")]);
assert_eq!(reader.required_one_of("LOG_LEVEL", LEVELS), None);
let errors = reader.finish().unwrap_err();
assert!(errors.to_string().contains("one of trace, debug, info, warn, error"));Sourcepub fn optional_one_of(
&mut self,
name: &str,
accepted: &[&str],
) -> Option<String>
pub fn optional_one_of( &mut self, name: &str, accepted: &[&str], ) -> Option<String>
A value that, when set, must be one of a fixed set.
§Examples
use env_reader::Reader;
const LEVELS: &[&str] = &["trace", "debug", "info", "warn", "error"];
let mut reader = Reader::from_pairs([("LOG_LEVEL", "debug")]);
assert_eq!(reader.optional_one_of("LOG_LEVEL", LEVELS).as_deref(), Some("debug"));
assert_eq!(reader.optional_one_of("OTHER", LEVELS), None);
assert!(reader.finish().is_ok());Sourcepub fn invalid(
&mut self,
name: impl Into<String>,
expected: impl Into<String>,
got: impl Into<String>,
)
pub fn invalid( &mut self, name: impl Into<String>, expected: impl Into<String>, got: impl Into<String>, )
Record that one variable held a value this crate cannot check.
optional_one_of covers a fixed set of
accepted strings, and optional_parse
covers anything with a FromStr. This is for what neither can: a
value that has to be resolved against something outside this crate,
where only the caller knows what “valid” means. The problem joins
the others, so a program that rejects a value here still reports
every other problem in the same breath.
§Examples
use env_reader::Reader;
let mut reader = Reader::from_pairs([("TENANT", "unknown-tenant")]);
if let Some(value) = reader.optional_string("TENANT") {
if !["alpha", "beta"].contains(&value.as_str()) {
reader.invalid("TENANT", "a tenant this build knows about", value);
}
}
let errors = reader.finish().unwrap_err();
assert!(errors.to_string().contains("a tenant this build knows about"));Sourcepub fn conflict(&mut self, message: impl Into<String>)
pub fn conflict(&mut self, message: impl Into<String>)
Record a conflict between variables that are individually fine.
§Examples
use env_reader::Reader;
let mut reader = Reader::from_pairs([("QUEUE_NAME", "q"), ("TOPIC_NAME", "t")]);
if reader.is_set("QUEUE_NAME") && reader.is_set("TOPIC_NAME") {
reader.conflict("Cannot specify both QUEUE_NAME and TOPIC_NAME.");
}
assert!(reader.finish().is_err());Sourcepub fn has_errors(&self) -> bool
pub fn has_errors(&self) -> bool
Whether anything has gone wrong so far.
Lets a caller skip a cross-field check that would only produce noise on top of an already-broken configuration.
§Examples
use env_reader::Reader;
let mut reader = Reader::from_pairs([] as [(&str, &str); 0]);
assert!(!reader.has_errors());
let _ = reader.required_string("SERVICE_NAME");
assert!(reader.has_errors());Sourcepub fn error_count(&self) -> usize
pub fn error_count(&self) -> usize
How many problems have been found so far.
Sourcepub fn finish_with<T>(self, value: T) -> Result<T, Errors>
pub fn finish_with<T>(self, value: T) -> Result<T, Errors>
Finish reading, returning value when nothing went wrong.
The shape that lets a Config be built and validated in one
expression, so a caller cannot forget the finish.
§Errors
Returns every problem found, as Reader::finish.
§Examples
use env_reader::{Errors, Reader};
#[derive(Debug)]
struct Config {
port: u16,
}
fn load() -> Result<Config, Errors> {
let mut reader = Reader::from_pairs([("PORT", "8443")]);
let config = Config {
port: reader.integer_or("PORT", 8080),
};
reader.finish_with(config)
}
assert_eq!(load()?.port, 8443);