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
use error::*;
use source::Source;
use std::collections::HashMap;
use std::env;
use value::{Value, ValueKind};
#[derive(Clone, Debug)]
pub struct Environment {
prefix: Option<String>,
separator: Option<String>,
ignore_empty: bool,
}
impl Environment {
pub fn new() -> Self {
Environment::default()
}
pub fn with_prefix(s: &str) -> Self {
Environment {
prefix: Some(s.into()),
..Environment::default()
}
}
pub fn prefix(mut self, s: &str) -> Self {
self.prefix = Some(s.into());
self
}
pub fn separator(mut self, s: &str) -> Self {
self.separator = Some(s.into());
self
}
pub fn ignore_empty(mut self, ignore: bool) -> Self {
self.ignore_empty = ignore;
self
}
}
impl Default for Environment {
fn default() -> Environment {
Environment {
prefix: None,
separator: None,
ignore_empty: false,
}
}
}
impl Source for Environment {
fn clone_into_box(&self) -> Box<dyn Source + Send + Sync> {
Box::new((*self).clone())
}
fn collect(&self) -> Result<HashMap<String, Value>> {
let mut m = HashMap::new();
let uri: String = "the environment".into();
let separator = match self.separator {
Some(ref separator) => separator,
_ => "",
};
let prefix_pattern = self.prefix.as_ref().map(|prefix| prefix.clone() + "_");
for (key, value) in env::vars() {
if self.ignore_empty && value.is_empty() {
continue;
}
let mut key = key.to_string();
if let Some(ref prefix_pattern) = prefix_pattern {
if key
.to_lowercase()
.starts_with(&prefix_pattern.to_lowercase())
{
key = key[prefix_pattern.len()..].to_string();
} else {
continue;
}
}
if !separator.is_empty() {
key = key.replace(separator, ".");
}
m.insert(
key.to_lowercase(),
Value::new(Some(&uri), ValueKind::String(value)),
);
}
Ok(m)
}
}