spring_boot/config/
mod.rs

1pub mod env;
2
3use crate::error::{AppError, Result};
4use anyhow::Context;
5use env::Env;
6use serde_toml_merge::merge_tables;
7pub use spring_macros::Configurable;
8use std::fs;
9use std::path::Path;
10use toml::Table;
11
12pub trait Configurable {
13    /// Prefix used to read toml configuration.
14    /// If you need to load external configuration, you need to rewrite this method
15    fn config_prefix(&self) -> &str;
16}
17
18/// load toml config
19pub(crate) fn load_config(config_path: &Path, env: Env) -> Result<Table> {
20    let config_file_content = fs::read_to_string(config_path);
21    let main_toml_str = match config_file_content {
22        Err(e) => {
23            log::warn!("Failed to read configuration file {:?}: {}", config_path, e);
24            return Ok(Table::new());
25        }
26        Ok(content) => content,
27    };
28
29    let main_table = toml::from_str::<Table>(main_toml_str.as_str())
30        .with_context(|| format!("Failed to parse the toml file at path {:?}", config_path))?;
31
32    let config_table: Table = match env.get_config_path(config_path) {
33        Ok(env_path) => {
34            let env_path = env_path.as_path();
35            if !env_path.exists() {
36                return Ok(main_table);
37            }
38
39            let env_toml_str = fs::read_to_string(env_path)
40                .with_context(|| format!("Failed to read configuration file {:?}", env_path))?;
41            let env_table = toml::from_str::<Table>(env_toml_str.as_str())
42                .with_context(|| format!("Failed to parse the toml file at path {:?}", env_path))?;
43            merge_tables(main_table, env_table)
44                .map_err(|e| AppError::TomlMergeError(e.to_string()))
45                .with_context(|| {
46                    format!("Failed to merge files {:?} and {:?}", config_path, env_path)
47                })?
48        }
49        Err(_) => {
50            log::debug!("{:?} config not found", env);
51            main_table
52        }
53    };
54
55    Ok(config_table)
56}
57
58#[allow(unused_imports)]
59mod tests {
60    use super::env::Env;
61    use crate::error::Result;
62    use std::fs;
63
64    #[test]
65    fn test_load_config() -> Result<()> {
66        let temp_dir = tempfile::tempdir()?;
67
68        let foo = temp_dir.path().join("foo.toml");
69        #[rustfmt::skip]
70        let _ = fs::write(&foo,r#"
71        [group]
72        key = "A"
73        "#,
74        );
75
76        let table = super::load_config(&foo, Env::from_string("dev"))?;
77        let group = table.get("group");
78        assert_eq!(group.unwrap().get("key").unwrap().as_str(), Some("A"));
79
80        // test merge
81        let foo_dev = temp_dir.path().join("foo-dev.toml");
82        #[rustfmt::skip]
83        let _ = fs::write(&foo_dev,r#"
84        [group]
85        key = "OOOOA"
86        "#,
87        );
88
89        let table = super::load_config(&foo, Env::from_string("dev"))?;
90        let group = table.get("group");
91        assert_eq!(group.unwrap().get("key").unwrap().as_str(), Some("OOOOA"));
92
93        Ok(())
94    }
95}