Skip to main content

heldar_kernel/
env.rs

1//! Small environment-variable helpers shared by the kernel + every app crate's config loader.
2//! Single source of truth so parsing behavior (empty-string filtering, bool truthiness) stays
3//! identical everywhere. Treats an empty/whitespace value the same as unset.
4
5/// The trimmed value of `key`, or `None` when unset/empty.
6pub fn var(key: &str) -> Option<String> {
7    std::env::var(key).ok().filter(|s| !s.trim().is_empty())
8}
9
10/// `var(key)` or a string default.
11pub fn var_or(key: &str, default: &str) -> String {
12    var(key).unwrap_or_else(|| default.to_string())
13}
14
15/// Parse `key` into `T`, falling back to `default` when unset/empty/unparseable.
16pub fn parse_or<T: std::str::FromStr>(key: &str, default: T) -> T {
17    var(key).and_then(|v| v.parse().ok()).unwrap_or(default)
18}
19
20/// Truthy-string bool (`1|true|yes|on`), or `default` when unset.
21pub fn parse_bool(key: &str, default: bool) -> bool {
22    match var(key) {
23        Some(v) => matches!(v.to_ascii_lowercase().as_str(), "1" | "true" | "yes" | "on"),
24        None => default,
25    }
26}