feat: add paths and defaults config with graceful fallback

This commit is contained in:
objz committed 2025-07-05 14:45:11 +02:00
1 parent a8f409d2ff
commit 8d8cf4805e
3 files changed
+131 -13

No files matched your search

+66 -13
View File
@@ -8,8 +8,13 @@ use types::Config;
pub mod types;
pub fn get_config_path() -> PathBuf {
let base_dir = config_dir().unwrap();
base_dir.join("mcl/")
match config_dir() {
Some(base_dir) => base_dir.join("mcl/"),
None => {
tracing::error!("Could not determine config directory, falling back to ./config/");
PathBuf::from("./config/")
}
}
}
fn ensure_config_exists(default_path: &str) -> PathBuf {
@@ -17,27 +22,75 @@ fn ensure_config_exists(default_path: &str) -> PathBuf {
if !config_path.exists() {
if let Some(parent_dir) = config_path.parent() {
fs::create_dir_all(parent_dir).expect("Failed to create configuration directory");
match fs::create_dir_all(parent_dir) {
Ok(_) => {}
Err(e) => {
tracing::error!("Failed to create configuration directory: {}", e);
}
}
}
fs::copy(default_path, &config_path).expect("Failed to copy default configuration file");
tracing::debug!(
"Default configuration copied to '{}'",
config_path.display()
);
match fs::copy(default_path, &config_path) {
Ok(_) => {
tracing::debug!(
"Default configuration copied to '{}'",
config_path.display()
);
}
Err(e) => {
tracing::error!(
"Failed to copy default config from '{}' to '{}': {}",
default_path,
config_path.display(),
e
);
}
}
}
config_path
}
pub fn load_config(config_path: &PathBuf) -> Result<Config, ConfigError> {
ConfigLoader::builder()
.add_source(File::from(config_path.clone()))
.build()?
.try_deserialize()
let built = match ConfigLoader::builder()
.add_source(File::from(config_path.clone()).required(false))
.build()
{
Ok(c) => c,
Err(e) => {
tracing::error!(
"Failed to build config from '{}': {}",
config_path.display(),
e
);
return Err(e);
}
};
match built.try_deserialize() {
Ok(config) => Ok(config),
Err(e) => {
tracing::error!(
"Failed to deserialize config from '{}': {}",
config_path.display(),
e
);
Err(e)
}
}
}
pub static SETTINGS: Lazy<Config> = Lazy::new(|| {
let path: PathBuf = ensure_config_exists("assets/default.toml");
load_config(&path).expect("Failed to load configuration")
match load_config(&path) {
Ok(config) => config,
Err(e) => {
tracing::error!("Config load failed, using defaults: {}", e);
Config {
general: types::General::default(),
paths: types::Paths::default(),
defaults: types::Defaults::default(),
}
}
}
});