2023-02-08 20:49:05 +01:00
|
|
|
use serde::Deserialize;
|
2023-02-09 11:42:33 +01:00
|
|
|
use std::fs;
|
2023-02-08 20:49:05 +01:00
|
|
|
|
2023-02-09 11:42:33 +01:00
|
|
|
#[derive(Deserialize, Clone, Default)]
|
2023-02-08 20:49:05 +01:00
|
|
|
pub struct Config {
|
2023-02-09 11:36:22 +01:00
|
|
|
pub scheme: Option<String>,
|
|
|
|
pub port: Option<u16>,
|
2023-02-08 22:14:57 +01:00
|
|
|
pub mail: Option<String>,
|
|
|
|
pub lang: Option<String>,
|
2023-02-08 20:49:05 +01:00
|
|
|
}
|
|
|
|
|
2023-02-16 15:58:43 +01:00
|
|
|
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),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-02-08 20:49:05 +01:00
|
|
|
pub fn get_config(file_path: &str) -> Config {
|
2023-02-09 11:42:33 +01:00
|
|
|
match fs::read_to_string(file_path) {
|
2023-02-08 20:49:05 +01:00
|
|
|
Ok(file) => match toml::from_str(&file) {
|
2023-02-16 15:58:43 +01:00
|
|
|
Ok(stored_config) => Config::complete(stored_config),
|
2023-02-08 20:49:05 +01:00
|
|
|
Err(file_error) => {
|
|
|
|
panic!("Error in config file: {file_error}");
|
|
|
|
}
|
|
|
|
},
|
|
|
|
Err(_) =>
|
|
|
|
// No config file
|
|
|
|
{
|
2023-02-16 15:58:43 +01:00
|
|
|
Config::new()
|
2023-02-08 20:49:05 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|