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
26pub fn parse(text: &str) -> Vec<(String, String)> {
28 text.lines()
29 .filter_map(|line| {
30 let line = line.trim();
31 if line.is_empty() || line.starts_with('#') {
32 return None;
33 }
34 let line = line.strip_prefix("export ").unwrap_or(line).trim_start();
35 let (name, value) = line.split_once('=')?;
36 let name = name.trim();
37 if name.is_empty() || !name.chars().all(|c| c.is_ascii_alphanumeric() || c == '_') {
38 return None;
39 }
40 let value = value.trim();
41 let value = value
42 .strip_prefix('"')
43 .and_then(|v| v.strip_suffix('"'))
44 .or_else(|| value.strip_prefix('\'').and_then(|v| v.strip_suffix('\'')))
45 .unwrap_or(value);
46 Some((name.to_string(), value.to_string()))
47 })
48 .collect()
49}
50
51pub fn load(path: &Path) -> Result<Vec<String>, String> {
54 let Ok(meta) = std::fs::metadata(path) else {
55 return Ok(Vec::new());
56 };
57 #[cfg(unix)]
58 {
59 use std::os::unix::fs::PermissionsExt;
60 if meta.permissions().mode() & 0o077 != 0 {
61 return Err(format!(
62 "{} can be read by other users, so it was not loaded; run: chmod 600 {}",
63 path.display(),
64 path.display()
65 ));
66 }
67 }
68 #[cfg(not(unix))]
69 let _ = meta;
70 let text = std::fs::read_to_string(path).map_err(|e| format!("{}: {e}", path.display()))?;
71 let mut set = Vec::new();
72 for (name, value) in parse(&text) {
73 if std::env::var_os(&name).is_none() {
74 std::env::set_var(&name, value);
75 set.push(name);
76 }
77 }
78 Ok(set)
79}