forked from Txio-labs/txio
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmod.rs
More file actions
327 lines (285 loc) · 10.8 KB
/
Copy pathmod.rs
File metadata and controls
327 lines (285 loc) · 10.8 KB
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
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
use anyhow::{Result, anyhow};
use std::fs;
use std::path::{Path, PathBuf};
#[cfg(unix)]
use std::os::unix::fs::PermissionsExt;
/// Load environment overrides for the CLI.
///
/// Security: unlike the previous `dotenvy::dotenv()` call, this does NOT search
/// the current directory (or its ancestors) for a `.env` file. Overrides come
/// only from the trusted config dir (`~/.txio/.env`) plus an explicit
/// `--env-file` opt-in.
///
/// Precedence (highest wins): pre-existing process env vars, then `--env-file`,
/// then `~/.txio/.env`. dotenvy's `from_path` is non-override (it sets a var
/// only when it is not already present), so loading the explicit file first
/// makes it win over the trusted default, while real process env — set before
/// either loader runs — always wins over both.
pub fn load_environment(explicit_env_file: Option<&Path>) -> Result<()> {
let mut trusted = get_config_dir();
trusted.push(".env");
let cwd_env = Path::new(".env");
load_env_files(explicit_env_file, &trusted, cwd_env)
}
fn load_env_files(explicit: Option<&Path>, trusted_env: &Path, cwd_env: &Path) -> Result<()> {
// Explicit opt-in first so it wins over the trusted default (dotenvy is
// non-override: first loader to set a var wins). An explicitly requested
// file that cannot be loaded is a hard error, not a silent shrug.
if let Some(path) = explicit {
dotenvy::from_path(path)
.map_err(|e| anyhow!("failed to load --env-file '{}': {}", path.display(), e))?;
}
// Trusted config dir: best-effort, silent when absent.
if trusted_env.exists() {
let _ = dotenvy::from_path(trusted_env);
}
// Discoverability: a planted `./.env` is never auto-loaded; if one is present
// and the user did not opt in, point them at the explicit flag.
if should_warn_unloaded_cwd_env(explicit.is_some(), cwd_env) {
eprintln!("warning: found ./.env but it was not loaded; pass --env-file .env to use it");
}
Ok(())
}
/// Whether to emit the "found ./.env but it was not loaded" discoverability
/// warning: only when the user did not pass `--env-file` and a `./.env` exists.
fn should_warn_unloaded_cwd_env(explicit_provided: bool, cwd_env: &Path) -> bool {
!explicit_provided && cwd_env.exists()
}
pub fn get_config_dir() -> PathBuf {
let mut path = dirs_next::home_dir().unwrap_or_else(|| PathBuf::from("."));
path.push(".txio");
if !path.exists() {
fs::create_dir_all(&path).ok();
#[cfg(unix)]
let _ = fs::set_permissions(&path, fs::Permissions::from_mode(0o700));
}
path
}
pub fn save_current_chain(chain: &str) -> Result<()> {
let mut path = get_config_dir();
path.push("current_chain");
fs::write(path, chain)?;
Ok(())
}
pub fn get_current_chain() -> Option<String> {
let mut path = get_config_dir();
path.push("current_chain");
fs::read_to_string(path).ok().map(|s| s.trim().to_string())
}
pub fn save_token(token: &str) -> Result<()> {
let mut path = get_config_dir();
path.push("token");
fs::write(&path, token)?;
#[cfg(unix)]
fs::set_permissions(&path, fs::Permissions::from_mode(0o600))?;
Ok(())
}
pub fn get_token() -> Option<String> {
let mut path = get_config_dir();
path.push("token");
fs::read_to_string(path).ok().map(|s| s.trim().to_string())
}
pub fn remove_token() -> Result<()> {
let mut path = get_config_dir();
path.push("token");
if path.exists() {
fs::remove_file(path)?;
}
Ok(())
}
pub fn save_config(key: &str, value: &str) -> Result<()> {
let mut path = get_config_dir();
path.push("config.json");
let mut map: serde_json::Map<String, serde_json::Value> = if path.exists() {
let content = fs::read_to_string(&path)?;
serde_json::from_str(&content).unwrap_or_default()
} else {
serde_json::Map::new()
};
map.insert(
key.to_string(),
serde_json::Value::String(value.to_string()),
);
fs::write(path, serde_json::to_string_pretty(&map)?)?;
Ok(())
}
pub fn get_config(key: &str) -> Result<Option<String>> {
let mut path = get_config_dir();
path.push("config.json");
if !path.exists() {
return Ok(None);
}
let content = fs::read_to_string(&path)?;
let map: serde_json::Map<String, serde_json::Value> =
serde_json::from_str(&content).unwrap_or_default();
Ok(map.get(key).and_then(|v| v.as_str()).map(|s| s.to_string()))
}
pub fn list_config() -> Result<Vec<(String, String)>> {
let mut path = get_config_dir();
path.push("config.json");
if !path.exists() {
return Ok(vec![]);
}
let content = fs::read_to_string(&path)?;
let map: serde_json::Map<String, serde_json::Value> =
serde_json::from_str(&content).unwrap_or_default();
Ok(map
.into_iter()
.filter_map(|(k, v)| v.as_str().map(|s| (k, s.to_string())))
.collect())
}
pub fn remove_config(key: &str) -> Result<()> {
let mut path = get_config_dir();
path.push("config.json");
if !path.exists() {
return Ok(());
}
let content = fs::read_to_string(&path)?;
let mut map: serde_json::Map<String, serde_json::Value> =
serde_json::from_str(&content).unwrap_or_default();
map.remove(key);
fs::write(path, serde_json::to_string_pretty(&map)?)?;
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
use std::io::Write;
use std::sync::Mutex;
use std::sync::atomic::{AtomicU64, Ordering};
// Env vars are process-global. Serialize every test that reads or writes the
// process environment so parallel test threads can't observe each other's
// mutations. Combined with per-test unique var KEYS, this keeps the suite
// deterministic.
static ENV_LOCK: Mutex<()> = Mutex::new(());
static COUNTER: AtomicU64 = AtomicU64::new(0);
/// A unique-per-call scratch directory under the OS temp dir.
fn unique_dir(tag: &str) -> PathBuf {
let n = COUNTER.fetch_add(1, Ordering::SeqCst);
let mut d = std::env::temp_dir();
d.push(format!(
"txio_env_test_{}_{}_{}",
tag,
std::process::id(),
n
));
fs::create_dir_all(&d).unwrap();
d
}
/// A unique env var key so concurrent tests never collide on the same name.
fn unique_key(tag: &str) -> String {
let n = COUNTER.fetch_add(1, Ordering::SeqCst);
format!("TXIO_TEST_{}_{}_{}", tag, std::process::id(), n)
}
fn write_file(dir: &Path, name: &str, contents: &str) -> PathBuf {
let p = dir.join(name);
let mut f = fs::File::create(&p).unwrap();
f.write_all(contents.as_bytes()).unwrap();
p
}
#[test]
fn loads_from_trusted_location() {
let _g = ENV_LOCK.lock().unwrap();
let dir = unique_dir("trusted");
let key = unique_key("TRUSTED");
let trusted = write_file(&dir, ".env", &format!("{key}=from_trusted\n"));
let missing_cwd = dir.join("nope.env");
load_env_files(None, &trusted, &missing_cwd).unwrap();
assert_eq!(std::env::var(&key).unwrap(), "from_trusted");
unsafe {
std::env::remove_var(&key);
}
}
#[test]
fn does_not_load_cwd_env_by_default() {
let _g = ENV_LOCK.lock().unwrap();
let dir = unique_dir("cwd");
let key = unique_key("CWD");
// A ".env" sitting where the CWD file would be must never be read for values.
let cwd_env = write_file(&dir, ".env", &format!("{key}=planted\n"));
let missing_trusted = dir.join("trusted.env");
load_env_files(None, &missing_trusted, &cwd_env).unwrap();
assert!(
std::env::var(&key).is_err(),
"a CWD .env must not be loaded without --env-file"
);
}
#[test]
fn loads_explicit_env_file() {
let _g = ENV_LOCK.lock().unwrap();
let dir = unique_dir("explicit");
let key = unique_key("EXPLICIT");
let explicit = write_file(&dir, "custom.env", &format!("{key}=from_explicit\n"));
let missing_trusted = dir.join("trusted.env");
let missing_cwd = dir.join("nope.env");
load_env_files(Some(&explicit), &missing_trusted, &missing_cwd).unwrap();
assert_eq!(std::env::var(&key).unwrap(), "from_explicit");
unsafe {
std::env::remove_var(&key);
}
}
#[test]
fn missing_explicit_env_file_is_an_error() {
let _g = ENV_LOCK.lock().unwrap();
let dir = unique_dir("missing");
let explicit = dir.join("does_not_exist.env");
let missing_trusted = dir.join("trusted.env");
let missing_cwd = dir.join("nope.env");
let result = load_env_files(Some(&explicit), &missing_trusted, &missing_cwd);
assert!(
result.is_err(),
"an explicitly requested missing file must error"
);
}
#[test]
fn explicit_env_file_wins_over_trusted() {
let _g = ENV_LOCK.lock().unwrap();
let dir = unique_dir("precedence");
let key = unique_key("PRECEDENCE");
let explicit = write_file(&dir, "explicit.env", &format!("{key}=from_explicit\n"));
let trusted = write_file(&dir, ".env", &format!("{key}=from_trusted\n"));
let missing_cwd = dir.join("nope.env");
load_env_files(Some(&explicit), &trusted, &missing_cwd).unwrap();
assert_eq!(
std::env::var(&key).unwrap(),
"from_explicit",
"--env-file must take precedence over the trusted default"
);
unsafe {
std::env::remove_var(&key);
}
}
#[test]
fn preexisting_env_var_is_never_clobbered() {
let _g = ENV_LOCK.lock().unwrap();
let dir = unique_dir("preexisting");
let key = unique_key("PREEXISTING");
unsafe {
std::env::set_var(&key, "real_value");
}
let explicit = write_file(&dir, "explicit.env", &format!("{key}=from_explicit\n"));
let trusted = write_file(&dir, ".env", &format!("{key}=from_trusted\n"));
let missing_cwd = dir.join("nope.env");
load_env_files(Some(&explicit), &trusted, &missing_cwd).unwrap();
assert_eq!(
std::env::var(&key).unwrap(),
"real_value",
"a pre-existing process env var must survive both loaders"
);
unsafe {
std::env::remove_var(&key);
}
}
#[test]
fn warns_only_when_cwd_env_present_and_no_opt_in() {
let dir = unique_dir("warn");
let present = write_file(&dir, ".env", "X=1\n");
let absent = dir.join("nope.env");
// Warn: no opt-in and a ./.env exists.
assert!(should_warn_unloaded_cwd_env(false, &present));
// No warn: user opted in via --env-file.
assert!(!should_warn_unloaded_cwd_env(true, &present));
// No warn: no ./.env exists.
assert!(!should_warn_unloaded_cwd_env(false, &absent));
}
}