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
//! # config
//!
//! Enable to load/store user level configuration for cargo-make.
//!

#[cfg(test)]
#[path = "./config_test.rs"]
mod config_test;

use crate::storage;
use crate::types::GlobalConfig;
use dirs;
use std::fs::File;
use std::io::Read;
use std::path::{Path, PathBuf};
use toml;

static CONFIG_FILE: &'static str = "config.toml";

fn get_config_directory() -> Option<PathBuf> {
    let os_directory = dirs::config_dir();
    storage::get_storage_directory(os_directory, CONFIG_FILE, true)
}

fn load_from_path(directory: PathBuf) -> GlobalConfig {
    let file_path = Path::new(&directory).join(CONFIG_FILE);
    debug!("Loading config from: {:#?}", &file_path);

    if file_path.exists() {
        let mut file = match File::open(&file_path) {
            Ok(value) => value,
            Err(error) => panic!(
                "Unable to open config file, directory: {:#?} error: {}",
                &directory, error
            ),
        };

        let mut config_str = String::new();
        file.read_to_string(&mut config_str).unwrap();

        let mut global_config: GlobalConfig = match toml::from_str(&config_str) {
            Ok(value) => value,
            Err(error) => panic!("Unable to parse global configuration file, {}", error),
        };

        match file_path.to_str() {
            Some(value) => global_config.file_name = Some(value.to_string()),
            None => global_config.file_name = None,
        };

        global_config
    } else {
        GlobalConfig::new()
    }
}

/// Returns the configuration
pub(crate) fn load() -> GlobalConfig {
    match get_config_directory() {
        Some(directory) => load_from_path(directory),
        None => GlobalConfig::new(),
    }
}