1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242//! Minimal `.env` file loader/saver for `~/.openfang/.env`.
//!
//! No external crate needed โ hand-rolled for simplicity.
//! Format: `KEY=VALUE` lines, `#` comments, optional quotes.
use std::collections::BTreeMap;
use std::path::PathBuf;
/// Return the path to `~/.openfang/.env`.
pub fn env_file_path() -> Option<PathBuf> {
dirs::home_dir().map(|h| h.join(".openfang").join(".env"))
}
/// Load `~/.openfang/.env` and `~/.openfang/secrets.env` into `std::env`.
///
/// System env vars take priority โ existing vars are NOT overridden.
/// `secrets.env` is loaded second so `.env` values take priority over secrets
/// (but both yield to system env vars).
/// Silently does nothing if the files don't exist.
pub fn load_dotenv() {
load_env_file(env_file_path());
// Also load secrets.env (written by dashboard "Set API Key" button)
load_env_file(secrets_env_path());
}
/// Return the path to `~/.openfang/secrets.env`.
pub fn secrets_env_path() -> Option<PathBuf> {
dirs::home_dir().map(|h| h.join(".openfang").join("secrets.env"))
}
fn load_env_file(path: Option<PathBuf>) {
let path = match path {
Some(p) => p,
None => return,
};
let content = match std::fs::read_to_string(&path) {
Ok(c) => c,
Err(_) => return,
};
for line in content.lines() {
let trimmed = line.trim();
if trimmed.is_empty() || trimmed.starts_with('#') {
continue;
}
if let Some((key, value)) = parse_env_line(trimmed) {
if std::env::var(&key).is_err() {
std::env::set_var(&key, &value);
}
}
}
}
/// Upsert a key in `~/.openfang/.env`.
///
/// Creates the file if missing. Sets 0600 permissions on Unix.
/// Also sets the key in the current process environment.
pub fn save_env_key(key: &str, value: &str) -> Result<(), String> {
let path = env_file_path().ok_or("Could not determine home directory")?;
// Ensure parent directory exists
if let Some(parent) = path.parent() {
std::fs::create_dir_all(parent).map_err(|e| format!("Failed to create directory: {e}"))?;
}
let mut entries = read_env_file(&path);
entries.insert(key.to_string(), value.to_string());
write_env_file(&path, &entries)?;
// Also set in current process
std::env::set_var(key, value);
Ok(())
}
/// Remove a key from `~/.openfang/.env`.
///
/// Also removes it from the current process environment.
pub fn remove_env_key(key: &str) -> Result<(), String> {
let path = env_file_path().ok_or("Could not determine home directory")?;
let mut entries = read_env_file(&path);
entries.remove(key);
write_env_file(&path, &entries)?;
std::env::remove_var(key);
Ok(())
}
/// List key names (without values) from `~/.openfang/.env`.
#[allow(dead_code)]
pub fn list_env_keys() -> Vec<String> {
let path = match env_file_path() {
Some(p) => p,
None => return Vec::new(),
};
read_env_file(&path).into_keys().collect()
}
/// Check if the `.env` file exists.
#[allow(dead_code)]
pub fn env_file_exists() -> bool {
env_file_path().map(|p| p.exists()).unwrap_or(false)
}
// ---------------------------------------------------------------------------
// Internal helpers
// ---------------------------------------------------------------------------
/// Parse a single `KEY=VALUE` line. Handles optional quotes.
fn parse_env_line(line: &str) -> Option<(String, String)> {
let eq_pos = line.find('=')?;
let key = line[..eq_pos].trim().to_string();
let mut value = line[eq_pos + 1..].trim().to_string();
if key.is_empty() {
return None;
}
// Strip matching quotes
if ((value.starts_with('"') && value.ends_with('"'))
|| (value.starts_with('\'') && value.ends_with('\'')))
&& value.len() >= 2
{
value = value[1..value.len() - 1].to_string();
}
Some((key, value))
}
/// Read all key-value pairs from the .env file.
fn read_env_file(path: &PathBuf) -> BTreeMap<String, String> {
let mut map = BTreeMap::new();
let content = match std::fs::read_to_string(path) {
Ok(c) => c,
Err(_) => return map,
};
for line in content.lines() {
let trimmed = line.trim();
if trimmed.is_empty() || trimmed.starts_with('#') {
continue;
}
if let Some((key, value)) = parse_env_line(trimmed) {
map.insert(key, value);
}
}
map
}
/// Write key-value pairs back to the .env file with a header comment.
fn write_env_file(path: &PathBuf, entries: &BTreeMap<String, String>) -> Result<(), String> {
let mut content =
String::from("# OpenFang environment โ managed by `openfang config set-key`\n");
content.push_str("# Do not edit while the daemon is running.\n\n");
for (key, value) in entries {
// Quote values that contain spaces or special characters
if value.contains(' ') || value.contains('#') || value.contains('"') {
content.push_str(&format!("{key}=\"{}\"\n", value.replace('"', "\\\"")));
} else {
content.push_str(&format!("{key}={value}\n"));
}
}
std::fs::write(path, &content).map_err(|e| format!("Failed to write .env file: {e}"))?;
// Set 0600 permissions on Unix
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
let _ = std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o600));
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_parse_env_line_simple() {
let (k, v) = parse_env_line("FOO=bar").unwrap();
assert_eq!(k, "FOO");
assert_eq!(v, "bar");
}
#[test]
fn test_parse_env_line_quoted() {
let (k, v) = parse_env_line("KEY=\"hello world\"").unwrap();
assert_eq!(k, "KEY");
assert_eq!(v, "hello world");
}
#[test]
fn test_parse_env_line_single_quoted() {
let (k, v) = parse_env_line("KEY='value'").unwrap();
assert_eq!(k, "KEY");
assert_eq!(v, "value");
}
#[test]
fn test_parse_env_line_spaces() {
let (k, v) = parse_env_line(" KEY = value ").unwrap();
assert_eq!(k, "KEY");
assert_eq!(v, "value");
}
#[test]
fn test_parse_env_line_no_value() {
let (k, v) = parse_env_line("KEY=").unwrap();
assert_eq!(k, "KEY");
assert_eq!(v, "");
}
#[test]
fn test_parse_env_line_comment() {
assert!(
parse_env_line("# comment").is_none()
|| parse_env_line("# comment").unwrap().0.starts_with('#')
);
// Comments are filtered before reaching parse_env_line in production code
}
#[test]
fn test_parse_env_line_no_equals() {
assert!(parse_env_line("NOEQUALS").is_none());
}
#[test]
fn test_parse_env_line_empty_key() {
assert!(parse_env_line("=value").is_none());
}
}