Skip to content
Snippets Groups Projects
Select Git revision
  • 085ca88dd1d3045d5512e2398c099510938d5a20
  • master default protected
  • duniter-v2s-issue-123-industrialize-releases
  • develop
  • v1.8.3
  • 1.8.2
6 results

lib.rs

Blame
  • lib.rs 3.56 KiB
    //  Copyright (C) 2020 Éloïs SANCHEZ.
    //
    // This program is free software: you can redistribute it and/or modify
    // it under the terms of the GNU Affero General Public License as
    // published by the Free Software Foundation, either version 3 of the
    // License, or (at your option) any later version.
    //
    // This program is distributed in the hope that it will be useful,
    // but WITHOUT ANY WARRANTY; without even the implied warranty of
    // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    // GNU Affero General Public License for more details.
    //
    // You should have received a copy of the GNU Affero General Public License
    // along with this program.  If not, see <https://www.gnu.org/licenses/>.
    
    #![deny(
        clippy::unwrap_used,
        missing_copy_implementations,
        trivial_casts,
        trivial_numeric_casts,
        unstable_features,
        unused_import_braces
    )]
    
    use anyhow::Context as _;
    use dubp::crypto::keys::ed25519::Ed25519KeyPair;
    use serde::{de::DeserializeOwned, Serialize};
    use std::path::{Path, PathBuf};
    
    const MODULES_CONF_PATH: &str = "modules-conf";
    
    #[derive(Clone, Debug)]
    pub struct DuniterCoreConf {
        pub self_key_pair: Ed25519KeyPair,
        pub txs_mempool_size: usize,
    }
    
    impl Default for DuniterCoreConf {
        fn default() -> Self {
            DuniterCoreConf {
                self_key_pair: Ed25519KeyPair::generate_random().expect("fail to gen random keypair"),
                txs_mempool_size: 0,
            }
        }
    }
    
    /// Duniter mode
    #[derive(Clone, Copy, Debug)]
    #[non_exhaustive]
    pub enum DuniterMode {
        Start,
        Sync,
    }
    
    pub fn load_module_conf<C: Default + DeserializeOwned>(
        module_name: &'static str,
        profile_path_opt: &Option<PathBuf>,
    ) -> anyhow::Result<C> {
        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 = 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())
        }
    }
    
    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,
    ) -> anyhow::Result<PathBuf> {
        if let Some(conf_home) = std::env::var_os("DUNITER_CONF_HOME") {
            let conf_home_path = PathBuf::from(conf_home);
            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 {
            let path = profile_path.join(MODULES_CONF_PATH);
            if !path.exists() {
                std::fs::create_dir(&path)?;
            }
            Ok(path.join(format!("{}.conf", module_name)))
        }
    }