use std::env::{VarError, var};
use crate::helpers::join;
use crate::{Source, Key, Value};
pub struct EnvVarSource {
prefix: Option<String>,
}
impl EnvVarSource {
pub fn new() -> Self {
Self { prefix: None }
}
pub fn with_prefix<T: Into<String>>(prefix: T) -> Self {
Self::_with_prefix(prefix.into())
}
fn _with_prefix(mut prefix: String) -> Self {
if !prefix.ends_with('_') {
prefix.push('_');
}
Self {
prefix: Some(prefix),
}
}
}
impl Source for EnvVarSource {
type Error = VarError;
fn get_value(&self, key: &Key) -> Result<Option<Value>, Self::Error> {
let key_with_env_seperator = join(key.components(), "_");
let mut env_key = self.prefix.clone().unwrap_or_default();
env_key.push_str(&key_with_env_seperator);
match var(env_key.to_uppercase()) {
Ok(v) => Ok(Some(Value::String(v))),
Err(std::env::VarError::NotPresent) => Ok(None),
Err(e) => Err(e),
}
}
}