#![forbid(unsafe_code)]
#![deny(missing_docs)]
#![cfg_attr(
not(test),
warn(clippy::unwrap_used, clippy::expect_used, clippy::panic)
)]
#![cfg_attr(docsrs, feature(doc_cfg))]
use std::collections::BTreeMap;
use std::ffi::OsString;
use std::path::PathBuf;
mod source;
#[doc(hidden)]
pub mod __private;
pub use clap;
pub use clap_layers_proc::Layered;
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum SourceLayer {
EnvVar(String),
ConfigFile {
path: PathBuf,
line: usize,
},
}
impl std::fmt::Display for SourceLayer {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
SourceLayer::EnvVar(var) => write!(f, "environment variable {var}"),
SourceLayer::ConfigFile { path, line } => {
write!(f, "{}, line {line}", path.display())
}
}
}
}
#[derive(thiserror::Error, Debug)]
#[non_exhaustive]
pub enum LayeredError {
#[error(transparent)]
Cli(#[from] clap::Error),
#[error("could not read config file '{}': {source}", path.display())]
Io {
path: PathBuf,
#[source]
source: std::io::Error,
},
#[error("could not parse config file '{}' at line {line}, column {column}: {message}", path.display())]
Parse {
path: PathBuf,
line: usize,
column: usize,
message: String,
},
#[error("invalid value '{value}' for '{field}' — from {layer} ({message})")]
Invalid {
field: String,
value: String,
layer: SourceLayer,
message: String,
},
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct Env {
vars: BTreeMap<String, String>,
}
impl Env {
#[must_use]
pub fn from_system() -> Self {
Self {
vars: std::env::vars_os()
.filter_map(|(k, v)| Some((k.into_string().ok()?, v.into_string().ok()?)))
.collect(),
}
}
#[must_use]
pub fn empty() -> Self {
Self::default()
}
#[must_use]
pub fn get(&self, key: &str) -> Option<&str> {
self.vars.get(key).map(String::as_str)
}
}
impl<K, V> FromIterator<(K, V)> for Env
where
K: Into<String>,
V: Into<String>,
{
fn from_iter<I: IntoIterator<Item = (K, V)>>(iter: I) -> Self {
Self {
vars: iter
.into_iter()
.map(|(key, value)| (key.into(), value.into()))
.collect(),
}
}
}
pub trait Layered: Sized {
fn layered() -> Result<Self, LayeredError> {
match Self::layered_from(std::env::args_os(), &Env::from_system()) {
Err(LayeredError::Cli(e)) => e.exit(),
other => other,
}
}
fn layered_from<I, T>(args: I, env: &Env) -> Result<Self, LayeredError>
where
I: IntoIterator<Item = T>,
T: Into<OsString> + Clone;
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn source_layer_display() {
assert_eq!(
SourceLayer::EnvVar("MYAPP_PORT".to_string()).to_string(),
"environment variable MYAPP_PORT"
);
assert_eq!(
SourceLayer::ConfigFile {
path: PathBuf::from("config.toml"),
line: 12,
}
.to_string(),
"config.toml, line 12"
);
}
#[test]
fn invalid_error_is_source_attributed() {
let err = LayeredError::Invalid {
field: "port".to_string(),
value: "foo".to_string(),
layer: SourceLayer::ConfigFile {
path: PathBuf::from("config.toml"),
line: 12,
},
message: "invalid type: string, expected u16".to_string(),
};
assert!(
err.to_string()
.starts_with("invalid value 'foo' for 'port' — from config.toml, line 12"),
"got: {err}"
);
}
#[test]
fn invalid_error_names_the_env_var() {
let err = LayeredError::Invalid {
field: "port".to_string(),
value: "banana".to_string(),
layer: SourceLayer::EnvVar("MYAPP_PORT".to_string()),
message: "invalid digit".to_string(),
};
assert!(
err.to_string()
.contains("from environment variable MYAPP_PORT"),
"got: {err}"
);
}
#[test]
fn io_error_names_the_path() {
let err = LayeredError::Io {
path: PathBuf::from("config.toml"),
source: std::io::Error::new(std::io::ErrorKind::PermissionDenied, "denied"),
};
assert!(err.to_string().contains("config.toml"), "got: {err}");
}
#[test]
fn env_from_iter_and_get() {
let env = Env::from_iter([("A".to_string(), "1".to_string())]);
assert_eq!(env.get("A"), Some("1"));
assert_eq!(env.get("B"), None);
assert_eq!(Env::empty().get("A"), None);
}
#[test]
fn env_from_system_reads_process_env() {
let env = Env::from_system();
assert!(env.get("PATH").is_some() || env.get("Path").is_some());
}
}