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
//! # 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_next;
use fsio::file::read_text_file;
use fsio::path::from_path::FromPath;
use std::path::{Path, PathBuf};
use toml;

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

fn get_config_directory() -> Option<PathBuf> {
    let os_directory = dirs_next::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() {
        match read_text_file(&file_path) {
            Ok(config_str) => {
                let mut global_config: GlobalConfig = match toml::from_str(&config_str) {
                    Ok(value) => value,
                    Err(error) => panic!("Unable to parse global configuration file, {}", error),
                };

                global_config.file_name = Some(FromPath::from_path(&file_path));

                global_config
            }
            Err(error) => panic!(
                "Unable to read config file: {:?} error: {}",
                &file_path, error
            ),
        }
    } else {
        GlobalConfig::new()
    }
}

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