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!(f, "failed to parse env {} value `{}` into {}", key, value, ty)
40            }
41            CfgError::LoadError { msg, .. } => write!(f, "failed to load env: {}", msg),
42        }
43    }
44}
45
46impl std::error::Error for CfgError {
47    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
48        match self {
49            CfgError::MissingEnv(_) => None,
50            CfgError::ParseError { source, .. } => Some(source.as_ref()),
51            CfgError::LoadError { source, .. } => Some(source.as_ref()),
52        }
53    }
54}
55
56pub trait FromEnv: Sized {
57    fn load(env_path: &std::path::Path) -> Result<Self, CfgError>;
58}
59
60/// Utility function for macros: read env and return `Option<String>`
61pub fn get_env(key: &'static str) -> Option<String> {
62    env::var(key).ok()
63}
64
65/// Utility function for macros: load .env file
66pub fn load_env_file(env_path: &std::path::Path) -> Result<(), CfgError> {
67    // Try to load .env file if it exists, but don't fail if it doesn't
68    match dotenvy::from_path(env_path) {
69        Ok(_) => Ok(()),
70        Err(dotenvy::Error::Io(e)) if e.kind() == std::io::ErrorKind::NotFound => Ok(()),
71        Err(e) => Err(CfgError::LoadError {
72            msg: "failed to load .env file",
73            source: Box::new(e),
74        }),
75    }
76}
77
78/// Utility function for macros: parse string to T
79pub fn parse_scalar<T: std::str::FromStr>(key: &'static str, raw: String) -> Result<T, CfgError>
80where
81    <T as std::str::FromStr>::Err: std::error::Error + Send + Sync + 'static,
82{
83    raw.parse::<T>().map_err(|e| CfgError::ParseError {
84        key,
85        value: raw,
86        ty: std::any::type_name::<T>(),
87        source: Box::new(e),
88    })
89}
90
91/// Split string and parse each part to `Vec<T>`
92pub fn parse_vec<T: std::str::FromStr>(
93    key: &'static str,
94    raw: String,
95    sep: &'static str,
96) -> Result<Vec<T>, CfgError>
97where
98    <T as std::str::FromStr>::Err: std::error::Error + Send + Sync + 'static,
99{
100    if sep.is_empty() {
101        return Ok(Vec::new());
102    }
103    let mut out = Vec::new();
104    for part in raw.split(sep) {
105        let s = part.trim().to_string();
106        if s.is_empty() {
107            continue;
108        }
109        out.push(parse_scalar::<T>(key, s)?);
110    }
111    Ok(out)
112}