Skip to main content

blyte_cli/
env_file.rs

1//! Provider keys from a file, for sessions that did not export them: a Claude Code session started
2//! without `GEMINI_API_KEY` failed every `blyte dispatch` at turn 0 (2026-09-29).
3//!
4//! The file is `$BLYTE_ENV_FILE` (empty turns it off), else `$XDG_CONFIG_HOME/blyte/env`, else
5//! `~/.config/blyte/env`: `NAME=value` lines, with an optional `export ` prefix, surrounding quotes,
6//! blank lines and `#` comments. A variable already set in the environment wins. A file other users
7//! can read is not loaded.
8
9use std::path::{Path, PathBuf};
10
11/// Where blyte looks for the file, or `None` when it is turned off.
12pub 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
26/// The `NAME=value` pairs in `text`.
27pub 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
51/// Sets each variable in the file at `path` that is not already set, and returns their names.
52/// A missing file sets nothing. Call it before any threads start: it uses `std::env::set_var`.
53pub 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}