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/// Parses a single `NAME=value` line (with optional `export ` prefix and surrounding quotes).
27fn 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
47/// The `NAME=value` pairs in `text`.
48pub 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
57/// Reads the value of `name` from `path`, or `Ok(None)` if the file or variable is absent.
58pub 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
70/// Sets one or more `NAME=value` lines in the file at `path`: replaces an existing line for the
71/// same name, keeps all other lines and comments, and appends new names. Creates the file and its
72/// parent directory if needed, with file mode 0600 on Unix.
73pub 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
131/// Sets each variable in the file at `path` that is not already set, and returns their names.
132/// A missing file sets nothing. Call it before any threads start: it uses `std::env::set_var`.
133pub 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}