1use anyhow::{Context as _, Result};
 2use std::fs;
 3use std::path::Path;
 4
 5pub fn get_dotenv_vars(current_dir: impl AsRef<Path>) -> Result<Vec<(String, String)>> {
 6    let current_dir = current_dir.as_ref();
 7
 8    let mut vars = Vec::new();
 9    let env_content =
10        fs::read_to_string(current_dir.join(".env.toml")).context("no .env.toml file found")?;
11
12    add_vars(env_content, &mut vars)?;
13
14    if let Ok(secret_content) = fs::read_to_string(current_dir.join(".env.secret.toml")) {
15        add_vars(secret_content, &mut vars)?;
16    }
17
18    Ok(vars)
19}
20
21pub fn load_dotenv() -> Result<()> {
22    for (key, value) in get_dotenv_vars("./crates/collab")? {
23        unsafe { std::env::set_var(key, value) };
24    }
25    Ok(())
26}
27
28fn add_vars(env_content: String, vars: &mut Vec<(String, String)>) -> Result<()> {
29    let env: toml::map::Map<String, toml::Value> = toml::de::from_str(&env_content)?;
30    for (key, value) in env {
31        let value = match value {
32            toml::Value::String(value) => value,
33            toml::Value::Integer(value) => value.to_string(),
34            toml::Value::Float(value) => value.to_string(),
35            toml::Value::Boolean(value) => value.to_string(),
36            _ => panic!("unsupported TOML value in .env.toml for key {}", key),
37        };
38        vars.push((key, value));
39    }
40    Ok(())
41}