use better_config_core::override_env::merge_with_env_uppercase;
use better_config_core::{AbstractConfig, Error};
use better_config_core::misc;
use ini::Ini;
use std::collections::{HashMap, HashSet};
pub trait IniConfig<T = HashMap<String, String>>: AbstractConfig<T> {
fn load(target: Option<String>) -> Result<T, Error>
where
T: Default,
HashMap<String, String>: Into<T>,
Self: Sized,
{
Self::load_with_override(target, &HashSet::new())
}
fn load_with_override(target: Option<String>, excluded_keys: &HashSet<String>) -> Result<T, Error>
where
T: Default,
HashMap<String, String>: Into<T>,
Self: Sized,
{
let target = target.or(Some("config.ini".to_string()));
let mut ini_map = HashMap::new();
if let Some(target) = target {
let file_paths = misc::validate_and_split_paths(&target)?;
for file_path in file_paths {
misc::check_file_accessibility(&file_path)?;
let ini = Ini::load_from_file(&file_path)
.map_err(|e| Error::IoError {
operation: format!("load INI file '{}'", file_path),
source: Some(Box::new(e)),
})?;
for (section, props) in ini.iter() {
let section_prefix = match section {
Some(s) => format!("{}.", s),
None => String::new(),
};
for (key, value) in props.iter() {
ini_map.insert(format!("{}{}", section_prefix, key), value.to_string());
}
}
}
}
let ini_map = merge_with_env_uppercase(ini_map, None, excluded_keys);
Ok(ini_map.into())
}
}