Complete the config file with default values

This commit is contained in:
Mylloon 2023-02-16 15:58:43 +01:00
parent 34bf7cecad
commit 23f0c99540
Signed by: Anri
GPG key ID: A82D63DFF8D1317F

View file

@ -9,10 +9,41 @@ pub struct Config {
pub lang: Option<String>, pub lang: Option<String>,
} }
impl Config {
fn new() -> Self {
Self {
scheme: Some("http".to_string()),
port: Some(8080),
..Config::default()
}
}
fn complete(a: Self) -> Self {
// Default config
let d = Config::new();
/// Return the default value if nothing is value is none
fn test<T>(val: Option<T>, default: Option<T>) -> Option<T> {
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),
}
}
}
pub fn get_config(file_path: &str) -> Config { pub fn get_config(file_path: &str) -> Config {
match fs::read_to_string(file_path) { match fs::read_to_string(file_path) {
Ok(file) => match toml::from_str(&file) { Ok(file) => match toml::from_str(&file) {
Ok(stored_config) => stored_config, Ok(stored_config) => Config::complete(stored_config),
Err(file_error) => { Err(file_error) => {
panic!("Error in config file: {file_error}"); panic!("Error in config file: {file_error}");
} }
@ -20,11 +51,7 @@ pub fn get_config(file_path: &str) -> Config {
Err(_) => Err(_) =>
// No config file // No config file
{ {
Config { Config::new()
scheme: Some("http".to_string()),
port: Some(8080),
..Config::default()
}
} }
} }
} }