cfgloader_core/
lib.rs

1use std::env;
2
3#[doc(hidden)]
4pub mod fallback {
5    pub fn load_or_default<T>(_env_path: &std::path::Path) -> Result<T, crate::CfgError>
6    where
7        T: Default,
8    {
9        // We need a way to detect if T implements FromEnv
10        // Due to Rust limitations, we use a simple approach: try to call T::load directly
11        // If compilation fails, it means T doesn't implement FromEnv, so we use Default
12
13        // Since we can't detect trait implementation at runtime, we return Default
14        // Users need to explicitly use #[env(...)] to load environment variables
15        Ok(T::default())
16    }
17}
18
19#[derive(Debug)]
20pub enum CfgError {
21    MissingEnv(&'static str),
22    ParseError {
23        key: &'static str,
24        value: String,
25        ty: &'static str,
26        source: Box<dyn std::error::Error + Send + Sync>,
27    },
28    LoadError {
29        msg: &'static str,
30        source: Box<dyn std::error::Error + Send + Sync>,
31    },
32}
33
34impl std::fmt::Display for CfgError {
35    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
36        match self {
37            CfgError::MissingEnv(key) => write!(f, "missing required env: {}", key),
38            CfgError::ParseError { key, value, ty, .. } => {
39                write!(
40                    f,
41                    "failed to parse env {} value `{}` into {}",
42                    key, value, ty
43                )
44            }
45            CfgError::LoadError { msg, .. } => write!(f, "failed to load env: {}", msg),
46        }
47    }
48}
49
50impl std::error::Error for CfgError {
51    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
52        match self {
53            CfgError::MissingEnv(_) => None,
54            CfgError::ParseError { source, .. } => Some(source.as_ref()),
55            CfgError::LoadError { source, .. } => Some(source.as_ref()),
56        }
57    }
58}
59
60pub trait FromEnv: Sized {
61    fn load(env_path: &std::path::Path) -> Result<Self, CfgError>;
62}
63
64/// Utility function for macros: read env and return `Option<String>`
65pub fn get_env(key: &'static str) -> Option<String> {
66    env::var(key).ok()
67}
68
69/// Utility function for macros: load .env file
70pub fn load_env_file(env_path: &std::path::Path) -> Result<(), CfgError> {
71    // Try to load .env file if it exists, but don't fail if it doesn't
72    match dotenvy::from_path(env_path) {
73        Ok(_) => Ok(()),
74        Err(dotenvy::Error::Io(e)) if e.kind() == std::io::ErrorKind::NotFound => Ok(()),
75        Err(e) => Err(CfgError::LoadError {
76            msg: "failed to load .env file",
77            source: Box::new(e),
78        }),
79    }
80}
81
82/// Utility function for macros: parse string to T
83pub fn parse_scalar<T: std::str::FromStr>(key: &'static str, raw: String) -> Result<T, CfgError>
84where
85    <T as std::str::FromStr>::Err: std::error::Error + Send + Sync + 'static,
86{
87    raw.parse::<T>().map_err(|e| CfgError::ParseError {
88        key,
89        value: raw,
90        ty: std::any::type_name::<T>(),
91        source: Box::new(e),
92    })
93}
94
95/// Split string and parse each part to `Vec<T>`
96pub fn parse_vec<T: std::str::FromStr>(
97    key: &'static str,
98    raw: String,
99    sep: &'static str,
100) -> Result<Vec<T>, CfgError>
101where
102    <T as std::str::FromStr>::Err: std::error::Error + Send + Sync + 'static,
103{
104    if sep.is_empty() {
105        return Ok(Vec::new());
106    }
107    let mut out = Vec::new();
108    for part in raw.split(sep) {
109        let s = part.trim().to_string();
110        if s.is_empty() {
111            continue;
112        }
113        out.push(parse_scalar::<T>(key, s)?);
114    }
115    Ok(out)
116}