use std::{collections::HashMap, env, io, path::Path};
use config::{Config, ConfigError, Environment};
use serde::Deserialize;
use thiserror::Error;
#[derive(Debug, Error)]
pub enum ConfigurationError {
#[error("could not read the application environment file")]
Read(#[source] io::Error),
#[error("invalid application environment syntax at character {0}")]
Syntax(usize),
#[error("could not parse the application environment")]
Environment,
#[error("invalid server configuration: {0}")]
Server(#[from] ConfigError),
}
pub fn environment(base_path: &Path) -> Result<HashMap<String, String>, ConfigurationError> {
environment_from(base_path, env::vars().collect())
}
pub fn environment_from(
base_path: &Path,
external: HashMap<String, String>,
) -> Result<HashMap<String, String>, ConfigurationError> {
let mut path = base_path.join(".env");
if let Some(name) = external.get("APP_ENV") {
let candidate = base_path.join(format!(".env.{name}"));
match candidate.try_exists() {
Ok(true) => path = candidate,
Ok(false) => {}
Err(error) => return Err(ConfigurationError::Read(error)),
}
}
let mut values = HashMap::new();
match dotenvy::from_path_iter(&path) {
Ok(entries) => {
for entry in entries {
let (key, value) = entry.map_err(environment_error)?;
values.entry(key).or_insert(value);
}
}
Err(dotenvy::Error::Io(error)) if error.kind() == io::ErrorKind::NotFound => {}
Err(error) => return Err(environment_error(error)),
}
values.extend(external);
Ok(values)
}
fn environment_error(error: dotenvy::Error) -> ConfigurationError {
match error {
dotenvy::Error::Io(error) => ConfigurationError::Read(error),
dotenvy::Error::LineParse(_, position) => ConfigurationError::Syntax(position),
_ => ConfigurationError::Environment,
}
}
#[derive(Debug, Deserialize)]
pub struct ServerConfig {
pub host: String,
pub port: u16,
}
impl ServerConfig {
pub fn from_environment(values: HashMap<String, String>) -> Result<Self, ConfigurationError> {
Ok(Config::builder()
.set_default("host", "127.0.0.1")?
.set_default("port", 8000)?
.add_source(Environment::with_prefix("SERVER").source(Some(values)))
.build()?
.try_deserialize()?)
}
}