uncurses/terminal/env.rs
1//! Environment variables for terminal configuration.
2//!
3//! [`Env`] is a read-only view of a set of environment variables.
4//! [`ProcessEnv`] reads the live process environment, and [`EnvList`] holds a
5//! fixed list of variables. `EnvList` covers both testing with deterministic
6//! inputs and environments that arrive from somewhere other than this process,
7//! such as the variable list an SSH client forwards.
8
9/// A read-only view of environment variables.
10///
11/// Implementations decide where the variables come from and whether they can
12/// change: [`ProcessEnv`] reads the live process environment on every lookup,
13/// while [`EnvList`] answers from a fixed list.
14///
15/// Only [`get`](Self::get) needs implementing; [`has`](Self::has) is derived
16/// from it.
17pub trait Env: Send + Sync {
18 /// Return a variable's value.
19 ///
20 /// # Parameters
21 ///
22 /// * `key` — variable name.
23 ///
24 /// # Returns
25 ///
26 /// The value, or `None` if `key` is absent.
27 ///
28 /// # Errors and panics
29 ///
30 /// Implementations should not panic for an absent or malformed variable.
31 fn get(&self, key: &str) -> Option<String>;
32
33 /// Return whether a variable is present with a non-empty value.
34 ///
35 /// Overriding this is only for taking a shortcut, not for changing the
36 /// answer: it must stay equivalent to
37 /// `get(key).is_some_and(|v| !v.is_empty())`.
38 ///
39 /// # Parameters
40 ///
41 /// * `key` — variable name.
42 ///
43 /// # Returns
44 ///
45 /// `true` if `key` is present and its value is not empty.
46 ///
47 /// # Errors and panics
48 ///
49 /// This method does not fail or intentionally panic.
50 fn has(&self, key: &str) -> bool {
51 self.get(key).is_some_and(|v| !v.is_empty())
52 }
53}
54
55impl<T: Env + ?Sized> Env for Box<T> {
56 fn get(&self, key: &str) -> Option<String> {
57 (**self).get(key)
58 }
59
60 fn has(&self, key: &str) -> bool {
61 (**self).has(key)
62 }
63}
64
65/// Return whether `env` identifies Apple Terminal.
66///
67/// Matches `TERM_PROGRAM` exactly against `Apple_Terminal`.
68/// Callers select protocol restrictions and version-dependent behavior.
69///
70/// ```
71/// use uncurses::terminal::{EnvList, is_apple_terminal};
72///
73/// let env = EnvList::from_pairs([("TERM_PROGRAM", "Apple_Terminal")]);
74/// assert!(is_apple_terminal(&env));
75/// ```
76pub fn is_apple_terminal(env: &dyn Env) -> bool {
77 env.get("TERM_PROGRAM").as_deref() == Some("Apple_Terminal")
78}
79
80/// The live process environment.
81///
82/// Every lookup reads through to [`std::env::var`], so a variable changed after
83/// this value was created is visible to the next lookup. This is the
84/// environment a [`Terminal`](crate::terminal::Terminal) uses when built over
85/// process stdio or the controlling terminal.
86///
87/// Two things follow from going through [`std::env::var`], and neither is true
88/// of [`EnvList`]: a value that is not valid Unicode reads as absent rather
89/// than panicking, and on Windows names match case-insensitively.
90#[derive(Debug, Clone, Copy, Default)]
91pub struct ProcessEnv;
92
93impl Env for ProcessEnv {
94 fn get(&self, key: &str) -> Option<String> {
95 std::env::var(key).ok()
96 }
97}
98
99/// A fixed list of environment variables.
100///
101/// Use this for an environment that does not come from this process, such as
102/// the variables an SSH client forwards or a set read from a configuration
103/// file, and for tests that need deterministic lookups.
104///
105/// Variables are stored as an ordered list of `(key, value)` pairs, matching
106/// how an environment is passed around at the process boundary. Duplicate keys
107/// are allowed, and lookups return the last matching value.
108#[derive(Debug, Clone, Default)]
109pub struct EnvList {
110 vars: Vec<(String, String)>,
111}
112
113impl EnvList {
114 /// Build an empty environment.
115 ///
116 /// # Returns
117 ///
118 /// An [`EnvList`] with no variables.
119 ///
120 /// # Errors and panics
121 ///
122 /// This method does not fail or intentionally panic.
123 pub fn new() -> Self {
124 Self::default()
125 }
126
127 /// Capture the current process environment.
128 ///
129 /// The result is a snapshot: later changes to the process environment are
130 /// not visible to it. Use [`ProcessEnv`] to read through to the live
131 /// environment instead.
132 ///
133 /// # Returns
134 ///
135 /// An [`EnvList`] containing all variables yielded by [`std::env::vars`] at
136 /// the time of the call.
137 ///
138 /// # Errors and panics
139 ///
140 /// This method does not return errors. It has the same panic behavior as
141 /// [`std::env::vars`] if the process environment contains invalid data.
142 pub fn from_process() -> Self {
143 Self {
144 vars: std::env::vars().collect(),
145 }
146 }
147
148 /// Build an environment from `(key, value)` pairs.
149 ///
150 /// Pair order and duplicate keys are preserved. Later duplicates shadow
151 /// earlier values for [`get`](Env::get) and [`has`](Env::has).
152 ///
153 /// # Parameters
154 ///
155 /// * `iter` — variables to store.
156 ///
157 /// # Returns
158 ///
159 /// An [`EnvList`] containing the supplied variables.
160 ///
161 /// # Errors and panics
162 ///
163 /// This method does not return errors. It may panic only if allocation for
164 /// the stored strings fails.
165 pub fn from_pairs<I, K, V>(iter: I) -> Self
166 where
167 I: IntoIterator<Item = (K, V)>,
168 K: Into<String>,
169 V: Into<String>,
170 {
171 Self {
172 vars: iter
173 .into_iter()
174 .map(|(k, v)| (k.into(), v.into()))
175 .collect(),
176 }
177 }
178
179 /// Append a variable to the list.
180 ///
181 /// If `key` is already present, the new value shadows earlier values for
182 /// [`get`](Env::get) and [`has`](Env::has).
183 ///
184 /// # Parameters
185 ///
186 /// * `key` — variable name.
187 /// * `value` — variable value.
188 ///
189 /// # Returns
190 ///
191 /// `self`, for chaining.
192 ///
193 /// # Errors and panics
194 ///
195 /// This method does not return errors. It may panic only if allocation for
196 /// the stored strings fails.
197 pub fn set(&mut self, key: impl Into<String>, value: impl Into<String>) -> &mut Self {
198 self.vars.push((key.into(), value.into()));
199 self
200 }
201}
202
203impl Env for EnvList {
204 fn get(&self, key: &str) -> Option<String> {
205 self.vars
206 .iter()
207 .rev()
208 .find(|(k, _)| k == key)
209 .map(|(_, v)| v.clone())
210 }
211}
212
213#[cfg(test)]
214mod tests {
215 use super::*;
216
217 #[test]
218 fn apple_terminal_detection_uses_exact_program_name() {
219 for program in [
220 None,
221 Some(""),
222 Some("Apple_Terminal"),
223 Some("apple_terminal"),
224 Some("iTerm.app"),
225 ] {
226 let mut env = EnvList::from_pairs([("TERM", "Apple_Terminal")]);
227 if let Some(program) = program {
228 env.set("TERM_PROGRAM", program);
229 }
230 assert_eq!(
231 is_apple_terminal(&env),
232 program == Some("Apple_Terminal"),
233 "TERM_PROGRAM={program:?}"
234 );
235 }
236 }
237
238 #[test]
239 fn duplicate_keys_last_wins() {
240 let e = EnvList::from_pairs([("FOO", "a"), ("BAR", "x"), ("FOO", "b")]);
241 assert_eq!(e.get("FOO").as_deref(), Some("b"));
242 assert_eq!(e.get("BAR").as_deref(), Some("x"));
243 }
244
245 #[test]
246 fn set_shadows_earlier_value() {
247 let mut e = EnvList::from_pairs([("K", "first")]);
248 e.set("K", "second");
249 assert_eq!(e.get("K").as_deref(), Some("second"));
250 }
251
252 #[test]
253 fn has_requires_non_empty() {
254 let e = EnvList::from_pairs([("EMPTY", ""), ("SET", "v")]);
255 assert!(!e.has("EMPTY"));
256 assert!(e.has("SET"));
257 assert!(!e.has("MISSING"));
258 }
259
260 #[test]
261 fn boxed_env_forwards() {
262 let e: Box<dyn Env> = Box::new(EnvList::from_pairs([("TERM", "xterm")]));
263 assert_eq!(e.get("TERM").as_deref(), Some("xterm"));
264 assert!(e.has("TERM"));
265 }
266
267 #[test]
268 fn boxed_env_forwards_has_override() {
269 struct TrackedEnv(std::sync::Arc<std::sync::atomic::AtomicUsize>);
270 impl Env for TrackedEnv {
271 fn get(&self, _key: &str) -> Option<String> {
272 Some(String::new())
273 }
274 fn has(&self, _key: &str) -> bool {
275 self.0.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
276 false
277 }
278 }
279
280 let calls = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0));
281 let e: Box<dyn Env> = Box::new(TrackedEnv(calls.clone()));
282 assert!(!e.has("ANYTHING"));
283 assert_eq!(calls.load(std::sync::atomic::Ordering::Relaxed), 1);
284 }
285}