use std::path::{Path, PathBuf};
pub fn default_path() -> Option<PathBuf> {
if let Some(p) = std::env::var_os("BLYTE_ENV_FILE") {
return if p.is_empty() {
None
} else {
Some(PathBuf::from(p))
};
}
if let Some(x) = std::env::var_os("XDG_CONFIG_HOME").filter(|x| !x.is_empty()) {
return Some(PathBuf::from(x).join("blyte/env"));
}
std::env::var_os("HOME").map(|h| PathBuf::from(h).join(".config/blyte/env"))
}
pub fn parse(text: &str) -> Vec<(String, String)> {
text.lines()
.filter_map(|line| {
let line = line.trim();
if line.is_empty() || line.starts_with('#') {
return None;
}
let line = line.strip_prefix("export ").unwrap_or(line).trim_start();
let (name, value) = line.split_once('=')?;
let name = name.trim();
if name.is_empty() || !name.chars().all(|c| c.is_ascii_alphanumeric() || c == '_') {
return None;
}
let value = value.trim();
let value = value
.strip_prefix('"')
.and_then(|v| v.strip_suffix('"'))
.or_else(|| value.strip_prefix('\'').and_then(|v| v.strip_suffix('\'')))
.unwrap_or(value);
Some((name.to_string(), value.to_string()))
})
.collect()
}
pub fn load(path: &Path) -> Result<Vec<String>, String> {
let Ok(meta) = std::fs::metadata(path) else {
return Ok(Vec::new());
};
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
if meta.permissions().mode() & 0o077 != 0 {
return Err(format!(
"{} can be read by other users, so it was not loaded; run: chmod 600 {}",
path.display(),
path.display()
));
}
}
#[cfg(not(unix))]
let _ = meta;
let text = std::fs::read_to_string(path).map_err(|e| format!("{}: {e}", path.display()))?;
let mut set = Vec::new();
for (name, value) in parse(&text) {
if std::env::var_os(&name).is_none() {
std::env::set_var(&name, value);
set.push(name);
}
}
Ok(set)
}