//! Parsing the config file use anyhow; use std::fs; use std::sync::{Arc, Mutex}; use serde_derive::Deserialize; use toml; use log4rs; use crate::types::errors::HuskError; use crate::types::defaults::CONSOLE_LOGGING; use crate::types::defaults::PID_FILE_LOCATION; use crate::types::defaults::SUBJECT_REPLACEMENT; #[derive(Deserialize, Debug, Clone)] pub struct HuskConfig { pub connection: String, pub sequoia_home: String, pub keyservers: Option>, pub subject_replacement: Option, pub pid_file: Option, logging: Option, } impl HuskConfig { pub fn load(path: &str, home: Option) -> anyhow::Result { match fs::read_to_string(path) { Ok(data) => { match toml::from_str::(data.as_str()) { Ok(mut configuration) => { if let Some(home) = home { configuration.sequoia_home = home; } Ok(configuration) }, Err(e) => { Err(HuskError::ConfigFileParseError(e.to_string()).into()) } } }, Err(e) => { Err(HuskError::ConfigFileOpenError(format!( "{} - {}", path, e)).into()) } } } pub fn init_logging(&self) -> anyhow::Result<()> { let config = match toml::to_string(&self.logging) { Ok(c) => c, Err(e) => { eprintln!("use default logging, because {}", e); eprintln!("{:?}", self.logging); CONSOLE_LOGGING.to_string() } }; let raw_config = toml::from_str::(config.as_str())?; log4rs::init_raw_config(raw_config)?; Ok(()) } pub fn get_keyservers(&self) -> Vec { if let Some(kss) = &self.keyservers { kss.clone() } else { Vec::new() } } pub fn get_subject_replacement(&self) -> String { if let Some(replacement) = &self.subject_replacement { replacement.clone() } else { SUBJECT_REPLACEMENT.to_string() } } pub fn get_pid_file(&self) -> String { if let Some(pid_file) = &self.pid_file { pid_file.clone() } else { PID_FILE_LOCATION.to_string() } } } pub type HuskConfigContainer = Arc>; impl From for HuskConfig { fn from(container: HuskConfigContainer) -> Self { let config = container.lock().unwrap(); config.clone() } } #[cfg(test)] mod tests { use crate::types::defaults; use super::HuskConfig; #[test] fn subject_line() { let config = HuskConfig { connection: "".into(), sequoia_home: "".into(), keyservers: None, subject_replacement: None, logging: None, pid_file: None, }; assert_eq!(config.get_subject_replacement(), defaults::SUBJECT_REPLACEMENT); } }