aurelin_framework/
configuration.rs1use std::{collections::HashMap, env, io, path::Path};
4
5use config::{Config, ConfigError, Environment};
6use serde::Deserialize;
7use thiserror::Error;
8
9#[derive(Debug, Error)]
12pub enum ConfigurationError {
13 #[error("could not read the application environment file")]
14 Read(#[source] io::Error),
15 #[error("invalid application environment syntax at character {0}")]
16 Syntax(usize),
17 #[error("could not parse the application environment")]
18 Environment,
19 #[error("invalid server configuration: {0}")]
20 Server(#[from] ConfigError),
21}
22
23pub fn environment(base_path: &Path) -> Result<HashMap<String, String>, ConfigurationError> {
29 environment_from(base_path, env::vars().collect())
30}
31
32pub fn environment_from(
36 base_path: &Path,
37 external: HashMap<String, String>,
38) -> Result<HashMap<String, String>, ConfigurationError> {
39 let mut path = base_path.join(".env");
40 if let Some(name) = external.get("APP_ENV") {
41 let candidate = base_path.join(format!(".env.{name}"));
42 match candidate.try_exists() {
43 Ok(true) => path = candidate,
44 Ok(false) => {}
45 Err(error) => return Err(ConfigurationError::Read(error)),
46 }
47 }
48
49 let mut values = HashMap::new();
50 match dotenvy::from_path_iter(&path) {
51 Ok(entries) => {
52 for entry in entries {
53 let (key, value) = entry.map_err(environment_error)?;
54 values.entry(key).or_insert(value);
55 }
56 }
57 Err(dotenvy::Error::Io(error)) if error.kind() == io::ErrorKind::NotFound => {}
58 Err(error) => return Err(environment_error(error)),
59 }
60 values.extend(external);
61 Ok(values)
62}
63
64fn environment_error(error: dotenvy::Error) -> ConfigurationError {
65 match error {
66 dotenvy::Error::Io(error) => ConfigurationError::Read(error),
67 dotenvy::Error::LineParse(_, position) => ConfigurationError::Syntax(position),
68 _ => ConfigurationError::Environment,
69 }
70}
71
72#[derive(Debug, Deserialize)]
74pub struct ServerConfig {
75 pub host: String,
76 pub port: u16,
77}
78
79impl ServerConfig {
80 pub fn from_environment(values: HashMap<String, String>) -> Result<Self, ConfigurationError> {
82 Ok(Config::builder()
83 .set_default("host", "127.0.0.1")?
84 .set_default("port", 8000)?
85 .add_source(Environment::with_prefix("SERVER").source(Some(values)))
86 .build()?
87 .try_deserialize()?)
88 }
89}