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
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
use std::env::var;
use std::fs::read_dir;

use config::{Config, Environment, File};
use log::{debug, info};
use serde::Deserialize;

/// Configuration loader options
pub struct Options {
    /// Root config folder (defaults to 'config')
    pub root_path: String,
    /// If not set, use APP_ENV environment value or defaults to 'dev'
    pub env: Option<String>,
    /// Loads env variables (defaults to true)
    pub read_envs: bool,
    /// Environment var separator
    pub env_separator: Option<String>,
}

/// Loads a configuration
///
/// Requires predefined struct with all config options
///
/// ```
/// use serde::Deserialize;
/// use icee_config_rs::{load, Options};
///
/// #[derive(Deserialize)]
/// struct C {
///     pub value: Option<String>,
/// }
///
/// let parsed = load::<C>(Options::new());
/// # assert_eq!(parsed.value, None);
/// ```
pub fn load<'a, T: Deserialize<'a>>(options: Options) -> T {
    info!("Parsing configuration...");
    let mut config = Config::new();

    load_dir(&mut config, &options.root_path);

    let env: String = match options.env {
        Some(v) => v,
        None => var("APP_ENV").unwrap_or_else(|_| "dev".into())
    };

    load_dir(&mut config, &format!("{}/{}", &options.root_path, env));

    let mut env_opt = Environment::new();
    if let Some(separator) = options.env_separator {
        env_opt = env_opt.separator(&separator);
    }

    config.merge(env_opt).unwrap();

    config.try_into().expect("loading configuration")
}

/// Options for loading configuration files
impl Options {
    /// Prepare default options
    ///
    /// ```
    /// use icee_config_rs::Options;
    ///
    /// let opt = Options::new();
    /// # assert_eq!(opt.env, None);
    /// # assert_eq!(opt.root_path, "config");
    /// # assert_eq!(opt.read_envs, true);
    /// ```
    pub fn new() -> Self {
        Options {
            root_path: "config".into(),
            env: None,
            read_envs: true,
            env_separator: Some("__".into()),
        }
    }

    /// Default options with different root path
    ///
    /// ```
    /// use icee_config_rs::Options;
    ///
    /// let opt = Options::with_root_path("conf");
    /// # assert_eq!(opt.env, None);
    /// # assert_eq!(opt.root_path, "conf");
    /// # assert_eq!(opt.read_envs, true);
    /// ```
    pub fn with_root_path(root_path: &str) -> Self {
        Options {
            root_path: root_path.into(),
            env: None,
            read_envs: true,
            env_separator: Some("__".into()),
        }
    }

    /// Default options with different env settings
    ///
    /// ```
    /// use icee_config_rs::Options;
    ///
    /// let opt = Options::with_app_env("test");
    /// # assert_eq!(opt.env, Some("test".into()));
    /// # assert_eq!(opt.root_path, "config");
    /// # assert_eq!(opt.read_envs, true);
    /// ```
    pub fn with_app_env(env: &str) -> Self {
        Options {
            root_path: "config".into(),
            env: Some(env.into()),
            read_envs: true,
            env_separator: Some("__".into()),
        }
    }
}

impl Default for Options {
    fn default() -> Self {
        Self::new()
    }
}

fn load_dir(config: &mut Config, dirname: &str) {
    let supported = ["toml", "ini", "json", "hjson", "yaml", "yml"];
    debug!("Walking {} config directory...", dirname);

    if let Ok(dir) = read_dir(dirname) {
        for path in dir {
            let path = path.unwrap().path();
            let filename = path.to_str().unwrap();

            if let Some(ext) = filename.split('.').last() {
                if supported.contains(&ext) {
                    config
                        .merge(File::with_name(filename))
                        .unwrap_or_else(|_| panic!("invalid config file {}", filename));
                }
            }
        }
    }
}