pub use crate::error::NihilityConfigError;
use serde::Serialize;
use serde::de::DeserializeOwned;
use std::fs;
use std::fs::File;
use std::io::{BufReader, Write};
use std::path::Path;
use tracing::debug;
mod error;
const DEFAULT_BASE_PATH: &str = "./config";
const TOML_SUFFIX: &str = "toml";
const JSON_SUFFIX: &str = "json";
pub fn get_config<T>(module_name: String) -> Result<T, NihilityConfigError>
where
T: Serialize + DeserializeOwned + Default,
{
debug!("Loading Module {} Config", module_name);
let base_path = option_env!("NIHILITY_CONFIG_PATH").unwrap_or_else(|| DEFAULT_BASE_PATH);
if !Path::try_exists(base_path.as_ref())? {
let dir = Path::new(&base_path);
fs::create_dir_all(dir)?;
} else {
let dir = Path::new(&base_path);
if dir.is_file() {
fs::create_dir(dir)?;
}
}
let prefix = format!("{}/{}", base_path, module_name);
if Path::try_exists(format!("{}.{}", prefix, TOML_SUFFIX).as_ref())?
&& cfg!(feature = "toml_config")
{
let toml_str = fs::read_to_string(format!("{}.{}", prefix, TOML_SUFFIX))?;
return Ok(toml::from_str(toml_str.as_str())?);
} else if Path::try_exists(format!("{}.{}", prefix, JSON_SUFFIX).as_ref())?
&& cfg!(feature = "json_config")
{
let reader = BufReader::new(File::open(format!("{}.{}", prefix, JSON_SUFFIX))?);
return Ok(serde_json::from_reader(reader)?);
} else {
let mut config_file: File = File::create(format!("{}.{}", prefix, TOML_SUFFIX))?;
config_file.write_all(toml::to_string_pretty(&T::default())?.as_bytes())?;
config_file.flush()?;
}
Ok(T::default())
}