Skip to content

Commit a608884

Browse files
joelgallantjohnb8
authored andcommitted
Adds 'parse_numbers' options for Environment
This can be particularly helpful for `MY_SERVER_PORT=4334 cargo run`
1 parent 86f8776 commit a608884

File tree

2 files changed

+43
-4
lines changed

2 files changed

+43
-4
lines changed

src/env.rs

Lines changed: 23 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
use std::collections::HashMap;
2+
use std::convert::TryInto;
23
use std::env;
34

45
use crate::error::*;
@@ -23,6 +24,9 @@ pub struct Environment {
2324

2425
/// Ignore empty env values (treat as unset).
2526
ignore_empty: bool,
27+
28+
/// Parse numbers if they're detected.
29+
parse_numbers: bool,
2630
}
2731

2832
impl Environment {
@@ -51,6 +55,11 @@ impl Environment {
5155
self.ignore_empty = ignore;
5256
self
5357
}
58+
59+
pub fn parse_numbers(mut self, parse_numbers: bool) -> Self {
60+
self.parse_numbers = parse_numbers;
61+
self
62+
}
5463
}
5564

5665
impl Default for Environment {
@@ -59,6 +68,7 @@ impl Default for Environment {
5968
prefix: None,
6069
separator: None,
6170
ignore_empty: false,
71+
parse_numbers: false,
6272
}
6373
}
6474
}
@@ -115,10 +125,19 @@ impl Source for Environment {
115125
key = key.replace(separator, ".");
116126
}
117127

118-
m.insert(
119-
key.to_lowercase(),
120-
Value::new(Some(&uri), ValueKind::String(value)),
121-
);
128+
let value = if self.parse_numbers {
129+
if let Ok(parsed) = value.parse() {
130+
ValueKind::Integer(parsed)
131+
} else if let Ok(parsed) = value.parse() {
132+
ValueKind::Float(parsed)
133+
} else {
134+
ValueKind::String(value)
135+
}
136+
} else {
137+
ValueKind::String(value)
138+
};
139+
140+
m.insert(key.to_lowercase(), Value::new(Some(&uri), value));
122141
}
123142

124143
Ok(m)

tests/env.rs

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -83,3 +83,23 @@ fn test_custom_separator_behavior() {
8383

8484
env::remove_var("C.B.A");
8585
}
86+
87+
fn test_parse_numbers() {
88+
env::set_var("INT_VAL", "42");
89+
env::set_var("FLOAT_VAL", "42.2");
90+
91+
let environment = Environment::new().parse_numbers(true);
92+
let values = environment.collect().unwrap();
93+
94+
assert_eq!(
95+
values.get("int_val").unwrap().clone().into_int().ok(),
96+
Some(42)
97+
);
98+
assert_eq!(
99+
values.get("float_val").unwrap().clone().into_float().ok(),
100+
Some(42.2)
101+
);
102+
103+
env::remove_var("INT_VAL");
104+
env::remove_var("FLOAT_VAL");
105+
}

0 commit comments

Comments
 (0)