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
use config::{Config, Environment, File};
pub use config::{ConfigError, FileFormat};
pub fn load<'a, T: serde::de::Deserialize<'a>>(
file: &str,
format: FileFormat,
) -> Result<T, ConfigError> {
let builder = Config::builder();
match std::env::var("CONFIG_PATH") {
Ok(env_file_path) => builder.add_source(File::with_name(&env_file_path)),
Err(_) => builder.add_source(File::from_str(file, format)),
}
.add_source(Environment::default().separator("."))
.build()?
.try_deserialize()
}
#[test]
fn test_load_yaml() {
use serde::Deserialize;
#[derive(Debug, Deserialize)]
struct Author {
pub name: String,
pub books: Vec<String>,
}
#[derive(Debug, Deserialize)]
struct Test {
pub count: u32,
pub author: Author,
}
let expected_data: Test = Test {
count: 10,
author: Author {
name: "John Ronald Reuel Tolkien".to_string(),
books: vec!["The Lord of the Rings".to_string()],
},
};
let data: Test = load(include_str!("./test_config.yaml"), FileFormat::Yaml).unwrap();
assert_eq!(data.count, expected_data.count);
assert_eq!(data.author.name, expected_data.author.name);
assert_eq!(data.author.books, expected_data.author.books);
}