use std::collections::HashMap;
use std::fs::File;
use std::io::{BufRead, BufReader};
use std::sync::Once;
use std::env;
use crate::error::Error;
static INIT: Once = Once::new();
static mut ENV_MAP: Option<HashMap<String, String>> = None;
fn read_env_file(path: &str) -> Result<HashMap<String, String>, Error> {
let mut map = HashMap::new();
if let Ok(file) = File::open(path) {
let reader = BufReader::new(file);
for line in reader.lines() {
if let Ok(line) = line {
let line = line.trim();
if line.is_empty() || line.starts_with('#') {
continue;
}
if let Some(idx) = line.find('=') {
let key = line[..idx].trim().to_string();
let value = line[idx + 1..].trim().to_string();
let value = value.trim_matches('"').trim_matches('\'').to_string();
map.insert(key, value);
}
}
}
} else {
return Err(Error::NotFoundFile(path.to_string()));
}
Ok(map)
}
pub fn ensure_env_loaded_with(path: &str) -> Result<(), Error> {
let map = read_env_file(path)?;
unsafe {
INIT.call_once(|| {
for (key, value) in &map {
env::set_var(key, value);
}
ENV_MAP = Some(map);
});
}
Ok(())
}
pub fn ensure_env_loaded() -> Result<(), Error> {
let map = read_env_file(".env")?;
unsafe {
INIT.call_once(|| {
for (key, value) in &map {
env::set_var(key, value);
}
ENV_MAP = Some(map);
});
}
Ok(())
}