use serde::Deserialize; use std::fs; #[derive(Deserialize, Clone, Default)] pub struct FileConfig { pub scheme: Option, pub port: Option, pub mail: Option, pub lang: Option, pub onion: Option, } #[derive(Clone)] pub struct Config { pub fc: FileConfig, } impl FileConfig { fn new() -> Self { Self { scheme: Some("http".to_string()), port: Some(8080), ..FileConfig::default() } } fn complete(a: Self) -> Self { // Default config let d = FileConfig::new(); /// Return the default value if nothing is value is none fn test(val: Option, default: Option) -> Option { if val.is_some() { val } else { default } } Self { scheme: test(a.scheme, d.scheme), port: test(a.port, d.port), mail: test(a.mail, d.mail), lang: test(a.lang, d.lang), onion: test(a.onion, d.onion), } } } fn get_file_config(file_path: &str) -> FileConfig { match fs::read_to_string(file_path) { Ok(file) => match toml::from_str(&file) { Ok(stored_config) => FileConfig::complete(stored_config), Err(file_error) => { panic!("Error in config file: {file_error}"); } }, Err(_) => // No config file { FileConfig::new() } } } pub fn get_config(file_path: &str) -> Config { let internal_config = get_file_config(file_path); Config { fc: internal_config, } }