Skip to main content

Reader

Struct Reader 

Source
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

Source

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.

Source

pub fn from_pairs<K, V, I>(pairs: I) -> Self
where I: IntoIterator<Item = (K, V)>, K: Into<String>, V: Into<String>,

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);
Source

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);
Source

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"));
Source

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);
Source

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);
Source

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");
Source

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>");
Source

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());
Source

pub fn required_integer<T>(&mut self, name: &str) -> T
where T: FromStr + Default,

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);
Source

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());
Source

pub fn integer_or<T>(&mut self, name: &str, default: T) -> T
where 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);
Source

pub fn optional_positive_integer<T>(&mut self, name: &str) -> Option<T>
where T: FromStr + PartialOrd + Default,

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);
Source

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"));
Source

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());
Source

pub fn parse_or<T>(&mut self, name: &str, expected: &str, default: T) -> T
where 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());
Source

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"));
Source

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");
Source

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());
Source

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);
Source

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);
Source

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"));
Source

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());
Source

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"));
Source

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());
Source

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());
Source

pub fn error_count(&self) -> usize

How many problems have been found so far.

Source

pub fn finish(self) -> Result<(), Errors>

Finish reading.

§Errors

Returns every problem found, in the order it was found, when there was at least one.

§Examples
use env_reader::Reader;

let mut reader = Reader::from_pairs([("SERVICE_NAME", "orders")]);
let _ = reader.required_string("SERVICE_NAME");
assert!(reader.finish().is_ok());
Source

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);

Trait Implementations§

Source§

impl Clone for Reader

Source§

fn clone(&self) -> Self

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for Reader

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.