1use anyhow::{Context, Result};
2use std::collections::HashMap;
3use std::env;
4use std::fs;
5use std::path::Path;
6
7pub struct EnvManager {
8 vars: HashMap<String, String>,
9}
10
11impl EnvManager {
12 pub fn new() -> Self {
13 Self {
14 vars: HashMap::new(),
15 }
16 }
17
18 pub fn load_from_file<P: AsRef<Path>>(&mut self, path: P) -> Result<()> {
19 if !path.as_ref().exists() {
20 return Ok(());
21 }
22
23 let content = fs::read_to_string(path).context("Failed to read env file")?;
24
25 for line in content.lines() {
26 let line = line.trim();
27 if line.is_empty() || line.starts_with('#') {
28 continue;
29 }
30
31 if let Some((key, value)) = line.split_once('=') {
32 let key = key.trim().to_string();
33 let value = value
34 .trim()
35 .trim_matches('"')
36 .trim_matches('\'')
37 .to_string();
38 self.vars.insert(key, value);
39 }
40 }
41
42 Ok(())
43 }
44
45 pub fn load_from_map(&mut self, env_vars: &HashMap<String, String>) {
46 for (key, value) in env_vars {
47 self.vars.insert(key.clone(), value.clone());
48 }
49 }
50
51 pub fn apply(&self) {
52 for (key, value) in &self.vars {
53 env::set_var(key, value);
54 }
55 }
56
57 pub fn get(&self, key: &str) -> Option<&String> {
58 self.vars.get(key)
59 }
60
61 pub fn set(&mut self, key: String, value: String) {
62 self.vars.insert(key, value);
63 }
64
65 pub fn vars(&self) -> &HashMap<String, String> {
66 &self.vars
67 }
68}
69
70impl Default for EnvManager {
71 fn default() -> Self {
72 Self::new()
73 }
74}