diff --git a/conf/src/lib.rs b/conf/src/lib.rs index 15ea6f16953eb3d9eaaf86c4688c344956b417ff..24e9d20adb0aca0052174154416c135024141d65 100644 --- a/conf/src/lib.rs +++ b/conf/src/lib.rs @@ -60,13 +60,18 @@ pub fn load_module_conf<C: Default + DeserializeOwned>( if let Ok(conf) = envy::prefixed(format!("DUNITER_{}_", module_name)).from_env::<C>() { Ok(conf) } else { - let conf_file_path = find_module_conf_file_path(module_name, profile_path); - let mut file = std::fs::File::open(conf_file_path)?; - let mut contents = String::new(); - use std::io::Read as _; - file.read_to_string(&mut contents)?; - Ok(serde_json::from_str::<C>(&contents) - .with_context(|| format!("Invalid configuration for module '{}'", module_name))?) + let conf_file_path = find_module_conf_file_path(module_name, profile_path)?; + if conf_file_path.exists() { + let mut file = std::fs::File::open(conf_file_path)?; + let mut contents = String::new(); + use std::io::Read as _; + file.read_to_string(&mut contents)?; + Ok(serde_json::from_str::<C>(&contents).with_context(|| { + format!("Invalid configuration for module '{}'", module_name) + })?) + } else { + Ok(C::default()) + } } } else { Ok(C::default()) @@ -78,7 +83,7 @@ pub fn write_module_conf<C: Default + Serialize>( module_name: &'static str, profile_path: &Path, ) -> anyhow::Result<()> { - let conf_file_path = find_module_conf_file_path(module_name, profile_path); + let conf_file_path = find_module_conf_file_path(module_name, profile_path)?; let contents = serde_json::to_string_pretty(&module_conf)?; @@ -92,15 +97,19 @@ pub fn write_module_conf<C: Default + Serialize>( fn find_module_conf_file_path( module_name: &'static str, profile_path: &std::path::Path, -) -> PathBuf { +) -> anyhow::Result<PathBuf> { if let Some(conf_home) = std::env::var_os("DUNITER_CONF_HOME") { let conf_home_path = PathBuf::from(conf_home); - conf_home_path - .join(MODULES_CONF_PATH) - .join(format!("{}.conf", module_name)) + let path = conf_home_path.join(MODULES_CONF_PATH); + if !path.exists() { + std::fs::create_dir(&path)?; + } + Ok(path.join(format!("{}.conf", module_name))) } else { - profile_path - .join(MODULES_CONF_PATH) - .join(format!("{}.conf", module_name)) + let path = profile_path.join(MODULES_CONF_PATH); + if !path.exists() { + std::fs::create_dir(&path)?; + } + Ok(path.join(format!("{}.conf", module_name))) } }