use std::fs;
use std::path::{Path, PathBuf};
use serde_json::Value;
use crate::error::{Error, Result};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum EnvScope {
Test,
Dev,
Prod,
#[default]
None,
}
impl EnvScope {
fn as_str(self) -> Option<&'static str> {
match self {
Self::Test => Some("test"),
Self::Dev => Some("dev"),
Self::Prod => Some("prod"),
Self::None => None,
}
}
}
#[derive(Debug, Default)]
pub struct ConfigBuilder {
env: EnvScope,
value: Option<Value>,
path: Option<PathBuf>,
}
impl ConfigBuilder {
pub fn new() -> Self {
Self {
env: EnvScope::None,
..Self::default()
}
}
pub fn env(mut self, env: EnvScope) -> Self {
self.env = env;
self
}
pub fn from_value(mut self, v: Value) -> Self {
self.value = Some(v);
self
}
pub fn from_file(mut self, path: impl AsRef<Path>) -> Self {
self.path = Some(path.as_ref().to_path_buf());
self
}
pub fn build(self) -> Result<Config> {
let value = if let Some(v) = self.value {
v
} else if let Some(path) = self.path {
let text = fs::read_to_string(path)?;
serde_json::from_str(&text)?
} else {
return Err(Error::Config("no config source".into()));
};
Ok(Config {
env: self.env,
root: value,
})
}
}
#[derive(Debug, Clone)]
pub struct Config {
env: EnvScope,
root: Value,
}
impl Config {
pub fn from_value(root: Value) -> Self {
Self {
env: EnvScope::None,
root,
}
}
pub fn builder() -> ConfigBuilder {
ConfigBuilder::new()
}
pub fn get(&self, path: &str) -> Result<&Value> {
let full = match self.env.as_str() {
Some(prefix) => format!("{prefix}.{path}"),
None => path.to_string(),
};
lookup(&self.root, &full).ok_or_else(|| Error::Config(format!("key not found: {full}")))
}
pub fn get_str(&self, path: &str) -> Result<String> {
self.get(path)?
.as_str()
.map(|s| s.to_string())
.ok_or_else(|| Error::Config(format!("{path} is not a string")))
}
pub fn get_i64(&self, path: &str) -> Result<i64> {
self.get(path)?
.as_i64()
.ok_or_else(|| Error::Config(format!("{path} is not an integer")))
}
pub fn get_bool(&self, path: &str) -> Result<bool> {
self.get(path)?
.as_bool()
.ok_or_else(|| Error::Config(format!("{path} is not a bool")))
}
}
fn lookup<'a>(root: &'a Value, dotted: &str) -> Option<&'a Value> {
let mut cur = root;
for part in dotted.split('.') {
cur = cur.get(part)?;
}
Some(cur)
}