use std::error::Error;
use crate::{ConfigurationBuilder, Source};
#[derive(Debug, Clone)]
pub struct EnvSource<'a> {
config: envious::Config<'a>,
allow_secrets: bool,
}
impl Default for EnvSource<'_> {
fn default() -> Self {
Self::new()
}
}
impl<'a> EnvSource<'a> {
pub fn new() -> Self {
Self {
config: envious::Config::new(),
allow_secrets: false,
}
}
pub fn with_prefix(mut self, prefix: &'a str) -> Self {
self.config.with_prefix(prefix);
self
}
pub fn with_separator(mut self, separator: &'a str) -> Self {
self.config.with_separator(separator);
self
}
pub fn with_config(mut self, config: envious::Config<'a>) -> Self {
self.config = config;
self
}
pub fn allow_secrets(mut self) -> Self {
self.allow_secrets = true;
self
}
}
impl<T: ConfigurationBuilder> Source<T> for EnvSource<'_> {
fn allows_secrets(&self) -> bool {
self.allow_secrets
}
fn provide(&self) -> Result<T, Box<dyn Error + Sync + Send>> {
Ok(self.config.build_from_env()?)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn separator() {
let mut config = envious::Config::new();
config.with_separator("++");
config.with_prefix("CFG--");
let config_debug = format!("{config:?}");
let source = EnvSource::default()
.with_prefix("CFG--")
.with_separator("++");
let source_debug = format!("{source:?}");
assert!(source_debug.contains(&config_debug));
}
}