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;
pub struct Options {
pub root_path: String,
pub env: Option<String>,
pub read_envs: bool,
pub env_separator: Option<String>,
}
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")
}
impl Options {
pub fn new() -> Self {
Options {
root_path: "config".into(),
env: None,
read_envs: true,
env_separator: Some("__".into()),
}
}
pub fn with_root_path(root_path: &str) -> Self {
Options {
root_path: root_path.into(),
env: None,
read_envs: true,
env_separator: Some("__".into()),
}
}
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));
}
}
}
}
}