Skip to content
Snippets Groups Projects
Commit 085ca88d authored by Éloïs's avatar Éloïs
Browse files

fix(conf): modules: handle case of non exist folder or file

parent 6db8efc2
No related branches found
No related tags found
No related merge requests found
Pipeline #12121 passed
......@@ -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 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))?)
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)))
}
}
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment