This repository has been archived by the owner on Dec 22, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 5
/
fromenvstatic.rs
71 lines (71 loc) · 2.65 KB
/
fromenvstatic.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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
////////////////////////////////////////////////////////////////////////
// Macros
////////////////////////////////////////////////////////////////////////
/// Help setting up static variables based on user environment.
///
/// We allow the user to configure certain properties/behaviours of tm
/// using environment variables. To reduce boilerplate in code, we use a
/// macro for setting them. We use [mod@`lazy_static`] to define them as
/// global variables, so they are available throughout the whole program -
/// they aren't going to change during runtime, ever, anyways.
///
/// # Examples
///
/// ```
/// # fn main() {
/// static ref TMPDIR: String = fromenvstatic!(asString "TMPDIR", "/tmp");
/// static ref TMSORT: bool = fromenvstatic!(asBool "TMSORT", true);
/// static ref TMWIN: u8 = fromenvstatic!(asU32 "TMWIN", 1);
/// # }
/// ```
macro_rules! fromenvstatic {
(asString $envvar:literal, $default:expr) => {
match env::var($envvar) {
Ok(val) => val,
Err(_) => $default.to_string(),
}
};
(asBool $envvar:literal, $default:literal) => {
match env::var($envvar) {
Ok(val) => match val.to_ascii_lowercase().as_str() {
"true" => true,
"false" => false,
&_ => {
// Test run as "cargo test -- --nocapture" will print this
if cfg!(test) {
println!(
"Variable {} expects true or false, not {}, assuming {}",
$envvar, val, $default
);
}
error!(
"Variable {} expects true or false, not {}, assuming {}",
$envvar, val, $default
);
return $default;
}
},
Err(_) => $default,
}
};
(asU32 $envvar:literal, $default:literal) => {
match env::var($envvar) {
Ok(val) => {
return val.parse::<u32>().unwrap_or_else(|err| {
if cfg!(test) {
println!(
"Couldn't parse variable {} (value: {}) as number (error: {}), assuming {}",
$envvar, val, err, $default
);
}
error!(
"Couldn't parse variable {} (value: {}) as number (error: {}), assuming {}",
$envvar, val, err, $default
);
$default
});
}
Err(_) => $default,
}
};
}