1use std::path::{Path, PathBuf};
10
11pub fn default_path() -> Option<PathBuf> {
13 if let Some(p) = std::env::var_os("BLYTE_ENV_FILE") {
14 return if p.is_empty() {
15 None
16 } else {
17 Some(PathBuf::from(p))
18 };
19 }
20 if let Some(x) = std::env::var_os("XDG_CONFIG_HOME").filter(|x| !x.is_empty()) {
21 return Some(PathBuf::from(x).join("blyte/env"));
22 }
23 std::env::var_os("HOME").map(|h| PathBuf::from(h).join(".config/blyte/env"))
24}
25
26fn parse_line(line: &str) -> Option<(&str, &str)> {
28 let line = line.trim();
29 if line.is_empty() || line.starts_with('#') {
30 return None;
31 }
32 let line = line.strip_prefix("export ").unwrap_or(line).trim_start();
33 let (name, value) = line.split_once('=')?;
34 let name = name.trim();
35 if name.is_empty() || !name.chars().all(|c| c.is_ascii_alphanumeric() || c == '_') {
36 return None;
37 }
38 let value = value.trim();
39 let value = value
40 .strip_prefix('"')
41 .and_then(|v| v.strip_suffix('"'))
42 .or_else(|| value.strip_prefix('\'').and_then(|v| v.strip_suffix('\'')))
43 .unwrap_or(value);
44 Some((name, value))
45}
46
47pub fn parse(text: &str) -> Vec<(String, String)> {
49 text.lines()
50 .filter_map(|line| {
51 let (name, value) = parse_line(line)?;
52 Some((name.to_string(), value.to_string()))
53 })
54 .collect()
55}
56
57pub fn get(path: &Path, name: &str) -> Result<Option<String>, String> {
59 let text = match std::fs::read_to_string(path) {
60 Ok(s) => s,
61 Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None),
62 Err(e) => return Err(format!("{}: {e}", path.display())),
63 };
64 Ok(parse(&text)
65 .into_iter()
66 .rfind(|(k, _)| k == name)
67 .map(|(_, v)| v))
68}
69
70pub fn set(path: &Path, vars: &[(&str, &str)]) -> Result<(), String> {
74 let existing = match std::fs::read_to_string(path) {
75 Ok(s) => s,
76 Err(e) if e.kind() == std::io::ErrorKind::NotFound => String::new(),
77 Err(e) => return Err(format!("{}: {e}", path.display())),
78 };
79
80 let mut placed = vec![false; vars.len()];
81 let mut out = String::new();
82 for line in existing.lines() {
83 if let Some((line_name, _)) = parse_line(line) {
84 if let Some(idx) = vars.iter().position(|(k, _)| *k == line_name) {
85 if !placed[idx] {
86 let (k, v) = vars[idx];
87 out.push_str(&format!("{k}={v}\n"));
88 placed[idx] = true;
89 }
90 continue;
91 }
92 }
93 out.push_str(line);
94 out.push('\n');
95 }
96 for (idx, (k, v)) in vars.iter().enumerate() {
97 if !placed[idx] {
98 out.push_str(&format!("{k}={v}\n"));
99 placed[idx] = true;
100 }
101 }
102
103 if let Some(parent) = path.parent().filter(|p| !p.as_os_str().is_empty()) {
104 std::fs::create_dir_all(parent).map_err(|e| format!("{}: {e}", parent.display()))?;
105 }
106
107 #[cfg(unix)]
108 {
109 use std::io::Write;
110 use std::os::unix::fs::{OpenOptionsExt, PermissionsExt};
111 let mut file = std::fs::OpenOptions::new()
112 .write(true)
113 .create(true)
114 .truncate(true)
115 .mode(0o600)
116 .open(path)
117 .map_err(|e| format!("{}: {e}", path.display()))?;
118 file.write_all(out.as_bytes())
119 .map_err(|e| format!("{}: {e}", path.display()))?;
120 std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o600))
121 .map_err(|e| format!("{}: {e}", path.display()))?;
122 }
123 #[cfg(not(unix))]
124 {
125 std::fs::write(path, out).map_err(|e| format!("{}: {e}", path.display()))?;
126 }
127
128 Ok(())
129}
130
131pub fn load(path: &Path) -> Result<Vec<String>, String> {
134 let Ok(meta) = std::fs::metadata(path) else {
135 return Ok(Vec::new());
136 };
137 #[cfg(unix)]
138 {
139 use std::os::unix::fs::PermissionsExt;
140 if meta.permissions().mode() & 0o077 != 0 {
141 return Err(format!(
142 "{} can be read by other users, so it was not loaded; run: chmod 600 {}",
143 path.display(),
144 path.display()
145 ));
146 }
147 }
148 #[cfg(not(unix))]
149 let _ = meta;
150 let text = std::fs::read_to_string(path).map_err(|e| format!("{}: {e}", path.display()))?;
151 let mut set = Vec::new();
152 for (name, value) in parse(&text) {
153 if std::env::var_os(&name).is_none() {
154 std::env::set_var(&name, value);
155 set.push(name);
156 }
157 }
158 Ok(set)
159}