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

feat(conf): add method write_module_conf & param conf home via env var

parent 4a627493
Branches
Tags
No related merge requests found
Pipeline #12119 passed
......@@ -24,8 +24,10 @@
use anyhow::Context as _;
use dubp::crypto::keys::ed25519::Ed25519KeyPair;
use serde::de::DeserializeOwned;
use std::path::PathBuf;
use serde::{de::DeserializeOwned, Serialize};
use std::path::{Path, PathBuf};
const MODULES_CONF_PATH: &str = "modules-conf";
#[derive(Clone, Debug)]
pub struct DuniterCoreConf {
......@@ -52,13 +54,13 @@ pub enum DuniterMode {
pub fn load_module_conf<C: Default + DeserializeOwned>(
module_name: &'static str,
modules_conf_path_opt: &Option<PathBuf>,
profile_path_opt: &Option<PathBuf>,
) -> anyhow::Result<C> {
if let Some(ref modules_conf_path) = modules_conf_path_opt {
if let Some(ref profile_path) = profile_path_opt {
if let Ok(conf) = envy::prefixed(format!("DUNITER_{}_", module_name)).from_env::<C>() {
Ok(conf)
} else {
let conf_file_path = modules_conf_path.join(format!("{}.conf", module_name));
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 _;
......@@ -70,3 +72,35 @@ pub fn load_module_conf<C: Default + DeserializeOwned>(
Ok(C::default())
}
}
pub fn write_module_conf<C: Default + Serialize>(
module_conf: C,
module_name: &'static str,
profile_path: &Path,
) -> anyhow::Result<()> {
let conf_file_path = find_module_conf_file_path(module_name, profile_path);
let contents = serde_json::to_string_pretty(&module_conf)?;
let mut file = std::fs::File::create(conf_file_path)?;
use std::io::Write as _;
file.write_all(contents.as_bytes())?;
Ok(())
}
fn find_module_conf_file_path(
module_name: &'static str,
profile_path: &std::path::Path,
) -> 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))
} else {
profile_path
.join(MODULES_CONF_PATH)
.join(format!("{}.conf", module_name))
}
}
......@@ -217,13 +217,8 @@ macro_rules! plug_duniter_modules {
software_version: &'static str,
) -> anyhow::Result<()> {
// Read conf of each module
let modules_conf_path_opt = if let Some(ref profile_path) = profile_path_opt {
Some(profile_path.join("modules-conf"))
} else {
None
};
$(
let [<$M:snake _conf>] = duniter_conf::load_module_conf::<<$M as DuniterModule>::Conf>(<$M>::MODULE_NAME, &modules_conf_path_opt)?;
let [<$M:snake _conf>] = duniter_conf::load_module_conf::<<$M as DuniterModule>::Conf>(<$M>::MODULE_NAME, &profile_path_opt)?;
)*
// Initialize each module
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment