hextacy/
env.rs

1use std::env::{self, VarError};
2use thiserror::Error;
3
4/// Gets an environment variable for the given key
5pub fn get(key: &str) -> Result<String, VarError> {
6    env::var(key)
7}
8
9/// Sets an environment variable to the given key and value
10pub fn set(key: &str, value: &str) {
11    env::set_var(key, value)
12}
13
14/// Tries to load a variable from the shell env and if not found returns the provided default value
15pub fn get_or_default(key: &str, default: &str) -> String {
16    get(key).unwrap_or_else(|_| String::from(default))
17}
18
19/// Retrieves a vec of values for the given keys set in the env, in the order
20/// of the input vec. Panics if the requested variables are not set.
21pub fn get_multiple(keys: &[&str]) -> Vec<String> {
22    let mut results = vec![];
23    for key in keys {
24        match env::var(key) {
25            Ok(value) => {
26                results.push(value);
27            }
28            Err(e) => panic!("Error at key {key}, {e}"),
29        };
30    }
31    results
32}
33
34/// Retrieves a vec of values for the given keys set in the env, in the order
35/// of the input vec, default to the given value if not found.
36pub fn get_or_default_multiple(keys: &[(&str, &str)]) -> Vec<String> {
37    let mut results = vec![];
38    for (key, default) in keys {
39        match env::var(key) {
40            Ok(value) => {
41                results.push(value);
42            }
43            Err(_) => results.push(default.to_string()),
44        };
45    }
46    results
47}
48
49/// Reads a file and sets all of its declared variables in the shell environment
50pub fn load_from_file(path: &str) -> Result<(), ConfigError> {
51    dotenv::from_path(path).map_err(ConfigError::DotEnv)
52}
53
54#[derive(Debug, Error)]
55pub enum ConfigError {
56    #[error("IO Error: {0}")]
57    Io(#[from] std::io::Error),
58    #[error("Error while loading .env: {0}")]
59    DotEnv(#[from] dotenv::Error),
60}