anyhow_std/
env.rs

1//! Wrappers for [mod@std::env]
2use anyhow::{anyhow, Context};
3use std::ffi::{OsStr, OsString};
4
5/// Wrap [std::env::var] providing `key` in error context
6pub fn var<K>(key: K) -> anyhow::Result<String>
7where
8    K: AsRef<OsStr>,
9{
10    let os = key.as_ref();
11    std::env::var(os).with_context(|| format!("environment variable {:?}", os.to_string_lossy()))
12}
13
14/// Wrap [std::env::var_os], converting `None` to an error with `key` in error context
15pub fn var_os<K>(key: K) -> anyhow::Result<OsString>
16where
17    K: AsRef<OsStr>,
18{
19    let os = key.as_ref();
20    var_os_without_context(os)
21        .with_context(|| format!("environment variable {:?}", os.to_string_lossy()))
22}
23
24fn var_os_without_context<K>(key: K) -> anyhow::Result<OsString>
25where
26    K: AsRef<OsStr>,
27{
28    let lossy_cow = key.as_ref().to_string_lossy();
29    let lossy_str = lossy_cow.as_ref();
30    for c in ['=', '\0'] {
31        if lossy_str.contains(c) {
32            return Err(anyhow!("environment variable contains {:?}", c));
33        }
34    }
35    std::env::var_os(key).ok_or_else(|| anyhow!("environment variable not found"))
36}
37
38#[cfg(test)]
39mod tests;