summaryrefslogtreecommitdiffstats
path: root/src/config/mod.rs
blob: 58d3f403f5b799af3f83c510fd8342ccefde3450 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
pub mod clean;
pub mod raw;

pub mod config_type;
pub use config_type::ConfigType;

use serde::de::DeserializeOwned;
use std::fs;
use std::path::{Path, PathBuf};

use crate::error::AppResult;
use crate::CONFIG_HIERARCHY;

pub trait TomlConfigFile: Sized + Default {
    type Raw: Into<Self> + DeserializeOwned;

    fn get_type() -> config_type::ConfigType;

    fn get_config() -> Self {
        parse_config_or_default::<Self::Raw, Self>(Self::get_type().as_filename())
    }
}

// searches a list of folders for a given file in order of preference
pub fn search_directories<P>(file_name: &str, directories: &[P]) -> Option<PathBuf>
where
    P: AsRef<Path>,
{
    directories
        .iter()
        .map(|path| path.as_ref().join(file_name))
        .find(|path| path.exists())
}

pub fn search_config_directories(file_name: &str) -> Option<PathBuf> {
    search_directories(file_name, &CONFIG_HIERARCHY)
}

fn parse_file_to_config<T, S>(file_path: &Path) -> AppResult<S>
where
    T: DeserializeOwned + Into<S>,
{
    let file_contents = fs::read_to_string(file_path)?;
    let config = toml::from_str::<T>(&file_contents)?;
    Ok(config.into())
}

pub fn parse_config_or_default<T, S>(file_name: &str) -> S
where
    T: DeserializeOwned + Into<S>,
    S: std::default::Default,
{
    match search_config_directories(file_name) {
        Some(file_path) => match parse_file_to_config::<T, S>(&file_path) {
            Ok(s) => s,
            Err(e) => {
                eprintln!("Failed to parse {}: {}", file_name, e);
                S::default()
            }
        },
        None => S::default(),
    }
}