forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBff99ad6Tahinli6 days ago1055 commits

envcfg.rs64 lines, 2.3 KiBHistoryRawDownload
1//! Environment switches the engine reads, with a process-local override layer.
2//!
3//! Editing the real environment is `unsafe` in Rust 2024, so the tests that pin a
4//! switch (`VE_SW`, `VE_HW_TEST_ABORT`, ...) record it here instead. Engine code
5//! reads these keys through [`var`] / [`var_os`], which answer from the overrides
6//! first and fall back to the real environment. A helper process the engine
7//! starts gets the overrides through [`apply`], because it reads its own
8//! environment and not ours.
9
10use std::collections::BTreeMap;
11use std::ffi::{OsStr, OsString};
12use std::process::Command;
13use std::sync::RwLock;
14
15/// `None` as a value means "unset": the key behaves as if it were absent, even
16/// when the real environment has it.
17static OVERRIDES: RwLock<BTreeMap<&'static str, Option<OsString>>> = RwLock::new(BTreeMap::new());
18
19fn table() -> std::sync::RwLockReadGuard<'static, BTreeMap<&'static str, Option<OsString>>> {
20 OVERRIDES.read().unwrap_or_else(|poisoned| poisoned.into_inner())
21}
22
23/// The value of `key`: the override if one is recorded, else the real environment.
24pub fn var_os(key: &str) -> Option<OsString> {
25 match table().get(key) {
26 Some(overridden) => overridden.clone(),
27 None => std::env::var_os(key),
28 }
29}
30
31/// [`var_os`] as text; `None` when the value is absent or not valid Unicode.
32pub fn var(key: &str) -> Option<String> {
33 var_os(key).and_then(|value| value.into_string().ok())
34}
35
36/// Records `key = value` for every engine read from here on.
37#[doc(hidden)]
38pub fn set(key: &'static str, value: impl AsRef<OsStr>) {
39 OVERRIDES
40 .write()
41 .unwrap_or_else(|poisoned| poisoned.into_inner())
42 .insert(key, Some(value.as_ref().to_os_string()));
43}
44
45/// Records `key` as absent for every engine read from here on.
46#[doc(hidden)]
47pub fn unset(key: &'static str) {
48 OVERRIDES
49 .write()
50 .unwrap_or_else(|poisoned| poisoned.into_inner())
51 .insert(key, None);
52}
53
54/// Passes every recorded override on to a helper process that is about to start,
55/// so the helper sees the same switches as this process.
56#[doc(hidden)]
57pub fn apply(command: &mut Command) {
58 for (key, value) in table().iter() {
59 match value {
60 Some(value) => command.env(key, value),
61 None => command.env_remove(key),
62 };
63 }
64}