Skip to main content

rustolio_utils/
env.rs

1//
2// SPDX-License-Identifier: MPL-2.0
3//
4// Copyright (c) 2026 Tobias Binnewies. All rights reserved.
5//
6// This Source Code Form is subject to the terms of the Mozilla Public
7// License, v. 2.0. If a copy of the MPL was not distributed with this
8// file, You can obtain one at http://mozilla.org/MPL/2.0/.
9//
10
11use std::{env, error::Error, ffi::OsStr, str::FromStr};
12
13use crate::{
14    error::{FromCustom, FromCustomError},
15    prelude::Threadsafe,
16};
17
18#[track_caller]
19pub fn var<K, V>(key: K) -> crate::Result<V>
20where
21    K: AsRef<OsStr>,
22    V: FromStr,
23    V::Err: Error + Threadsafe,
24{
25    env::var(key)
26        .context("Failed to get environment variable")?
27        .parse()
28        .context("Failed to parse environment variable")
29}
30
31#[track_caller]
32pub fn var_default<K, V>(key: K, default: V) -> crate::Result<V>
33where
34    K: AsRef<OsStr>,
35    V: FromStr,
36    V::Err: Error + Threadsafe,
37{
38    match env::var(key) {
39        Ok(v) => Ok(v.parse().context("Failed to parse environment variable")?),
40        Err(env::VarError::NotPresent) => Ok(default),
41        Err(e) => Err(e.with_context("Failed to get environment variable")),
42    }
43}