1pub use crate::error::NihilityConfigError;
2use serde::Serialize;
3use serde::de::DeserializeOwned;
4use std::fs;
5use std::fs::File;
6use std::io::{BufReader, Write};
7use std::path::Path;
8use tracing::debug;
9
10mod error;
11
12const DEFAULT_BASE_PATH: &str = "./config";
13const TOML_SUFFIX: &str = "toml";
14const JSON_SUFFIX: &str = "json";
15
16pub fn get_config<T>(module_name: String) -> Result<T, NihilityConfigError>
17where
18 T: Serialize + DeserializeOwned + Default,
19{
20 debug!("Loading Module {} Config", module_name);
21 let base_path = option_env!("NIHILITY_CONFIG_PATH").unwrap_or_else(|| DEFAULT_BASE_PATH);
22 if !Path::try_exists(base_path.as_ref())? {
23 let dir = Path::new(&base_path);
24 fs::create_dir_all(dir)?;
25 } else {
26 let dir = Path::new(&base_path);
27 if dir.is_file() {
28 fs::create_dir(dir)?;
29 }
30 }
31 let prefix = format!("{}/{}", base_path, module_name);
32 if Path::try_exists(format!("{}.{}", prefix, TOML_SUFFIX).as_ref())?
33 && cfg!(feature = "toml_config")
34 {
35 let toml_str = fs::read_to_string(format!("{}.{}", prefix, TOML_SUFFIX))?;
36 return Ok(toml::from_str(toml_str.as_str())?);
37 } else if Path::try_exists(format!("{}.{}", prefix, JSON_SUFFIX).as_ref())?
38 && cfg!(feature = "json_config")
39 {
40 let reader = BufReader::new(File::open(format!("{}.{}", prefix, JSON_SUFFIX))?);
41 return Ok(serde_json::from_reader(reader)?);
42 } else {
43 let mut config_file: File = File::create(format!("{}.{}", prefix, TOML_SUFFIX))?;
44 config_file.write_all(toml::to_string_pretty(&T::default())?.as_bytes())?;
45 config_file.flush()?;
46 }
47 Ok(T::default())
48}