forked from starship/starship
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcontext_env.rs
48 lines (41 loc) · 1.27 KB
/
context_env.rs
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
#[cfg(test)]
use std::collections::HashMap;
#[cfg(not(test))]
use std::env;
use std::ffi::OsString;
#[derive(Default)]
pub struct Env<'a> {
/// A `HashMap` of environment variable mocks
#[cfg(test)]
pub env: HashMap<&'a str, String>,
#[cfg(not(test))]
_marker: std::marker::PhantomData<&'a ()>,
}
impl<'a> Env<'a> {
// Retrieves a environment variable from the os or from a table if in testing mode
#[cfg(test)]
pub fn get_env<K: AsRef<str>>(&self, key: K) -> Option<String> {
self.env
.get(key.as_ref())
.map(std::string::ToString::to_string)
}
#[cfg(not(test))]
#[inline]
pub fn get_env<K: AsRef<str>>(&self, key: K) -> Option<String> {
env::var(key.as_ref()).ok()
}
// Retrieves a environment variable from the os or from a table if in testing mode (os version)
#[cfg(test)]
pub fn get_env_os<K: AsRef<str>>(&self, key: K) -> Option<OsString> {
self.env.get(key.as_ref()).map(OsString::from)
}
#[cfg(not(test))]
#[inline]
pub fn get_env_os<K: AsRef<str>>(&self, key: K) -> Option<OsString> {
env::var_os(key.as_ref())
}
#[cfg(test)]
pub fn insert(&mut self, k: &'a str, v: String) -> Option<String> {
self.env.insert(k, v)
}
}