toolcraft_config/
lib.rs

1pub mod error;
2
3use config::{Config, File};
4use serde::de::DeserializeOwned;
5
6use crate::error::Error;
7
8pub type Result<T> = std::result::Result<T, Error>;
9
10pub fn load_settings<T>(config_path: &str) -> Result<T>
11where
12    T: DeserializeOwned,
13{
14    let config = Config::builder()
15        .add_source(File::with_name(config_path))
16        .build()
17        .map_err(|e| Error::ErrorMessage(e.to_string().into()))?;
18
19    let r = config
20        .try_deserialize()
21        .map_err(|e| Error::ErrorMessage(e.to_string().into()))?;
22    Ok(r)
23}
24
25#[cfg(test)]
26mod tests {
27    use serde::Deserialize;
28
29    use super::*;
30
31    #[derive(Debug, Deserialize)]
32    pub struct Settings {
33        pub test: TestConfig,
34    }
35
36    #[derive(Debug, Deserialize)]
37    pub struct TestConfig {
38        pub test_key: String,
39    }
40
41    #[test]
42    fn test_load_settings() {
43        let config_path = "tests/test_config.toml"; // Adjust the path as needed
44        let result: Result<Settings> = load_settings(config_path);
45        assert!(result.is_ok());
46        let config = result.unwrap();
47        assert_eq!(config.test.test_key, "test_value");
48    }
49}