Skip to main content

usage_cli/
env.rs

1use std::collections::{BTreeMap, HashSet};
2use std::process::Command;
3
4pub use std::env::*;
5
6pub fn var_true(key: &str) -> bool {
7    matches!(var(key), Ok(v) if v == "1" || v == "true")
8}
9
10/// The prefix this CLI's own settings live under.
11///
12/// Not `USAGE_`, which is the same namespace the parser writes a spec's values into
13/// (`usage_<arg>`). On Windows environment variable names are case-insensitive, so
14/// `USAGE_DEBUG` and a spec's `usage_debug` are one variable there, and two things follow:
15/// a script with an ordinary `--debug` flag cannot read `$usage_debug` when the setting is
16/// also set, and mise — which clears `usage_*` before a task so its own parsed arguments
17/// cannot leak in, comparing the first six characters case-insensitively — takes the
18/// settings with it. Six characters is why no `USAGE_…` spelling escapes: `USAGE_CLI_` and
19/// `USAGE_SETTING_` are cleared just the same.
20const SETTING_PREFIX: &str = "USAGECLI_";
21
22/// The prefix the settings used to live under, still read so nothing that set it breaks.
23const LEGACY_SETTING_PREFIX: &str = "USAGE_";
24
25/// The environment variable naming setting `name`, e.g. `SHELL_BASH` -> `USAGECLI_SHELL_BASH`.
26pub fn setting_var_name(name: &str) -> String {
27    format!("{SETTING_PREFIX}{name}")
28}
29
30/// The value of setting `name`, preferring the current spelling over the legacy one.
31///
32/// First one set wins and the rest are not looked at, which is what makes the old name an
33/// alias rather than a second setting — the same order `usage-config` gives `deprecated_envs`.
34/// Nothing is warned about: one name set is the ordinary case, and the settings read here are
35/// read before there is a logger to warn with.
36///
37/// An empty or blank value reads as unset at each name, matching the `FOO= cmd` convention for
38/// switching something off, so blanking the current name falls through to the legacy one
39/// rather than to nothing.
40pub fn setting(name: &str, lookup: impl Fn(&str) -> Option<String>) -> Option<String> {
41    setting_entry(name, lookup).map(|(_, value)| value)
42}
43
44/// As [`setting`], and also which spelling supplied it.
45///
46/// The name matters to anything that reports back: telling someone their `USAGECLI_SHELL_BASH`
47/// could not be started, when what they set was `USAGE_SHELL_BASH`, sends them looking at a
48/// variable they never touched.
49pub fn setting_entry(
50    name: &str,
51    lookup: impl Fn(&str) -> Option<String>,
52) -> Option<(String, String)> {
53    [
54        format!("{SETTING_PREFIX}{name}"),
55        format!("{LEGACY_SETTING_PREFIX}{name}"),
56    ]
57    .into_iter()
58    .find_map(|key| {
59        let value = lookup(&key)?;
60        let value = value.trim();
61        (!value.is_empty()).then(|| (key, value.to_string()))
62    })
63}
64
65/// The log filter to use, under either spelling of each setting.
66///
67/// Resolved rather than read straight by `env_logger`: `Env::filter_or` falls back to its
68/// default only when the variable is *unset*, so a blank `USAGECLI_LOG` would be taken as the
69/// filter instead of falling through to `USAGE_LOG` — which is the rule [`setting`] promises.
70///
71/// Precedence: trace over debug over an explicit level, and `info` if none of them says
72/// otherwise.
73pub fn log_filter(lookup: impl Fn(&str) -> Option<String>) -> String {
74    // By reference, so the caller's closure need not be `Copy` — `&F` is itself `Fn` when `F`
75    // is, which is what lets one lookup answer all three settings.
76    let on = |name: &str| matches!(setting(name, &lookup), Some(v) if v == "1" || v == "true");
77    if on("TRACE") {
78        return "trace".to_string();
79    }
80    if on("DEBUG") {
81        return "debug".to_string();
82    }
83    setting("LOG", &lookup).unwrap_or_else(|| "info".to_string())
84}
85
86/// Hand the parsed spec's variables to a command we are about to spawn.
87///
88/// On Windows this is not just `Command::env`. The executable search order there puts the
89/// system directory ahead of `PATH`, so `bash` resolves to `C:\Windows\System32\bash.exe` —
90/// the WSL launcher — on any machine with WSL installed, whatever else is on `PATH`. WSL only
91/// carries a Win32 variable across the boundary if `WSLENV` names it, so without this the
92/// script runs with every `usage_*` variable unset, silently and with no error.
93pub fn apply_parsed_env(cmd: &mut Command, env: &BTreeMap<String, String>) {
94    for (key, val) in env {
95        cmd.env(key, val);
96    }
97    if env.is_empty() {
98        return;
99    }
100    // `cfg!` rather than `#[cfg(windows)]`: CI only runs on Linux, so a `#[cfg]` block here
101    // would never be compiled, type-checked or linted anywhere. This compiles everywhere and
102    // optimizes away off Windows.
103    if cfg!(windows) {
104        let existing = var("WSLENV").ok();
105        let keys = env.keys().map(String::as_str);
106        cmd.env("WSLENV", append_to_wslenv(existing.as_deref(), keys));
107    }
108}
109
110/// Whether an entry already in `WSLENV` delivers its value to WSL unchanged.
111///
112/// Only a bare name or `/u` does. Measured against WSL rather than read off the flag list,
113/// because two of them lose the value outright in this direction:
114///
115/// | entry     | `FOO=bar`        | `FOO=C:\Windows` |
116/// | --------- | ---------------- | ---------------- |
117/// | `FOO`     | `bar`            | `C:\Windows`     |
118/// | `FOO/u`   | `bar`            | `C:\Windows`     |
119/// | `FOO/w`   | *unset*          | *unset*          |
120/// | `FOO/uw`  | *unset*          | *unset*          |
121/// | `FOO/p`   | *unset*          | `/mnt/c/Windows` |
122/// | `FOO/l`   | *unset*          | `/mnt/c/Windows` |
123///
124/// `/w` is the other direction only, and `/p` and `/l` translate the value as a path — which
125/// drops anything that is not one. usage's values are arbitrary strings off a command line, so
126/// a `/p` entry would silently swallow almost all of them.
127fn carries_value_verbatim(entry: &str) -> bool {
128    match entry.split_once('/') {
129        None => true,
130        Some((_, flags)) => !flags.is_empty() && flags.chars().all(|flag| flag == 'u'),
131    }
132}
133
134/// Add `keys` to a `WSLENV` value, preserving whatever was already there.
135///
136/// `WSLENV` is a `:`-separated list of *variable names*, each optionally suffixed with flags.
137/// Names are added bare: usage has no idea whether a given value is a path, and `/p` would
138/// silently rewrite anything that merely looks like one. Unflagged names copy the value
139/// verbatim, so a script sees the same bytes it would on Unix.
140///
141/// Existing entries are never rewritten or dropped — a name the caller configured is theirs.
142/// But an existing entry for a name usage is about to set does not stop usage adding its own
143/// bare one unless it [carries the value verbatim](carries_value_verbatim): a `usage_foo/p`
144/// inherited from somewhere would otherwise mean the script sees nothing at all. Listing the
145/// name twice is how it is fixed rather than a problem to avoid — WSL takes the entry that
146/// transfers, so `FOO/p:FOO` arrives as plain `FOO`.
147///
148/// Takes the current value as an argument instead of reading the environment so it stays a
149/// pure function, testable on every platform rather than only where it does anything.
150pub fn append_to_wslenv<'a>(
151    existing: Option<&str>,
152    keys: impl IntoIterator<Item = &'a str>,
153) -> String {
154    let mut entries: Vec<&str> = vec![];
155    let mut names: HashSet<&str> = HashSet::new();
156
157    for entry in existing.unwrap_or_default().split(':') {
158        // Absorbs a leading, trailing or doubled `:`, either inherited or left by a caller
159        // that built the list by naive concatenation.
160        if entry.is_empty() {
161            continue;
162        }
163        if carries_value_verbatim(entry) {
164            names.insert(entry.split('/').next().unwrap_or(entry));
165        }
166        entries.push(entry);
167    }
168
169    for key in keys {
170        // A name carrying `:` or `/` would not just fail to transfer, it would corrupt the
171        // rest of the list and take the caller's own entries down with it. `as_env` derives
172        // names from `to_snake_case`, which cannot produce either, so this is a guard against
173        // that changing out from under us rather than a case we expect.
174        if key.is_empty() || key.contains(':') || key.contains('/') {
175            continue;
176        }
177        if names.insert(key) {
178            entries.push(key);
179        }
180    }
181
182    entries.join(":")
183}
184
185/// Keyed by the *program* rather than the subcommand, because that is what the value names.
186/// `usage powershell` runs `pwsh`, so its variable is `USAGECLI_SHELL_PWSH`.
187///
188/// The current spelling, since this is what error messages tell people to set. The legacy
189/// `USAGE_SHELL_*` is still read — see [`setting`].
190pub fn shell_var_name(shell: &str) -> String {
191    setting_var_name(&shell_setting_name(shell))
192}
193
194fn shell_setting_name(shell: &str) -> String {
195    format!("SHELL_{}", shell.to_ascii_uppercase())
196}
197
198/// The shell program to run in place of `shell`, if one was configured.
199///
200/// `None` means run `shell` as before. The value is a program path or a name to look up on
201/// `PATH` — not a command line: shells on Windows live at paths like
202/// `C:\Program Files\Git\bin\bash.exe`, and treating the value as a command line would make
203/// usage responsible for quoting rules it has no reason to own. `Command` passes the program
204/// and each argument separately, so a path with spaces needs no quoting.
205///
206/// An empty or blank value reads as unset, matching the `FOO= cmd` convention for switching
207/// something off. Nothing checks that the program exists: the value need not be an absolute
208/// path, so deciding would mean reimplementing `PATH`, `PATHEXT` and permission lookup, and
209/// racing the spawn that follows. A bad value surfaces as a spawn error naming it.
210///
211/// `lookup` is injected rather than read from the environment so this stays testable without
212/// mutating process-wide state — the same shape as `parse_partial_with_env` in usage-lib.
213pub fn shell_program_override(
214    shell: &str,
215    lookup: impl Fn(&str) -> Option<String>,
216) -> Option<String> {
217    setting(&shell_setting_name(shell), lookup)
218}
219
220/// As [`shell_program_override`], and also the variable that named it.
221pub fn shell_program_override_entry(
222    shell: &str,
223    lookup: impl Fn(&str) -> Option<String>,
224) -> Option<(String, String)> {
225    setting_entry(&shell_setting_name(shell), lookup)
226}
227
228#[cfg(test)]
229mod tests {
230    use super::*;
231
232    fn append(existing: Option<&str>, keys: &[&str]) -> String {
233        append_to_wslenv(existing, keys.iter().copied())
234    }
235
236    #[test]
237    fn wslenv_adds_keys_in_order() {
238        assert_eq!(append(None, &["usage_workspace"]), "usage_workspace");
239        assert_eq!(
240            append(None, &["usage_workspace", "usage_region"]),
241            "usage_workspace:usage_region"
242        );
243    }
244
245    #[test]
246    fn wslenv_appends_after_existing_entries() {
247        assert_eq!(append(Some("FOO"), &["usage_a"]), "FOO:usage_a");
248    }
249
250    #[test]
251    fn wslenv_leaves_existing_flags_untouched() {
252        assert_eq!(
253            append(Some("FOO/p:BAR/l"), &["usage_a"]),
254            "FOO/p:BAR/l:usage_a"
255        );
256    }
257
258    #[test]
259    fn wslenv_does_not_repeat_an_existing_name() {
260        assert_eq!(
261            append(Some("usage_a"), &["usage_a", "usage_b"]),
262            "usage_a:usage_b"
263        );
264    }
265
266    #[test]
267    fn wslenv_treats_a_direction_only_entry_as_covering_the_name() {
268        // `/u` is this direction — Win32 invoking WSL — so the value already arrives intact.
269        assert_eq!(append(Some("usage_a/u"), &["usage_a"]), "usage_a/u");
270    }
271
272    #[test]
273    fn wslenv_adds_its_own_entry_beside_one_that_would_lose_the_value() {
274        // `/p` translates the value as a path and drops anything that is not one; `/w` is the
275        // other direction entirely. Neither would deliver a parsed argument, so usage adds a
276        // bare entry after it — WSL then takes the one that transfers.
277        for flags in ["/p", "/l", "/w", "/uw"] {
278            let existing = format!("usage_a{flags}");
279            assert_eq!(
280                append(Some(&existing), &["usage_a"]),
281                format!("{existing}:usage_a"),
282                "an inherited {existing} must not swallow the value"
283            );
284        }
285    }
286
287    #[test]
288    fn carries_value_verbatim_only_for_bare_names_and_u() {
289        assert!(carries_value_verbatim("FOO"));
290        assert!(carries_value_verbatim("FOO/u"));
291        for entry in [
292            "FOO/p", "FOO/l", "FOO/w", "FOO/uw", "FOO/wu", "FOO/pu", "FOO/",
293        ] {
294            assert!(!carries_value_verbatim(entry), "{entry}");
295        }
296    }
297
298    #[test]
299    fn wslenv_drops_empty_segments() {
300        assert_eq!(append(Some(""), &["usage_a"]), "usage_a");
301        assert_eq!(append(Some("::FOO::"), &["usage_a"]), "FOO:usage_a");
302    }
303
304    #[test]
305    fn wslenv_with_no_keys_returns_existing() {
306        assert_eq!(append(Some("FOO"), &[]), "FOO");
307        assert_eq!(append(None, &[]), "");
308    }
309
310    #[test]
311    fn wslenv_skips_keys_that_would_corrupt_the_list() {
312        assert_eq!(append(None, &["ok", "bad:name"]), "ok");
313        assert_eq!(append(None, &["ok", "bad/p"]), "ok");
314        assert_eq!(append(None, &["", "ok"]), "ok");
315    }
316
317    #[test]
318    fn wslenv_dedups_within_the_new_keys() {
319        assert_eq!(append(None, &["a", "a"]), "a");
320    }
321
322    #[test]
323    fn wslenv_adds_no_flags() {
324        // Values are arbitrary strings, not known to be paths, so they must cross verbatim.
325        assert!(!append(None, &["usage_a"]).contains('/'));
326    }
327
328    #[test]
329    fn parsed_env_keys_are_safe_for_wslenv() {
330        // `append_to_wslenv` skips names containing `:` or `/`. Nothing usage-lib produces
331        // should ever hit that path; if `as_env` starts generating such names, variables
332        // would go missing on Windows, so pin the invariant here.
333        let spec: usage::Spec = r#"
334            arg "<some file>"
335            flag "--dry-run"
336            "#
337        .parse()
338        .unwrap();
339        let args = ["test", "x", "--dry-run"].map(String::from);
340        let env = usage::parse(&spec, &args).unwrap().as_env();
341
342        assert!(!env.is_empty());
343        for key in env.keys() {
344            assert!(
345                !key.is_empty() && !key.contains(':') && !key.contains('/'),
346                "as_env produced a key that cannot go in WSLENV: {key}"
347            );
348        }
349    }
350
351    fn from(pairs: &[(&str, &str)]) -> impl Fn(&str) -> Option<String> + use<> {
352        let pairs: Vec<(String, String)> = pairs
353            .iter()
354            .map(|(k, v)| ((*k).to_string(), (*v).to_string()))
355            .collect();
356        move |key| {
357            pairs
358                .iter()
359                .find(|(k, _)| k == key)
360                .map(|(_, v)| v.to_string())
361        }
362    }
363
364    #[test]
365    fn shell_var_names_cover_every_shell_subcommand() {
366        // These are the four programs `Cli::run` dispatches to; `powershell` runs `pwsh`.
367        assert_eq!(shell_var_name("bash"), "USAGECLI_SHELL_BASH");
368        assert_eq!(shell_var_name("zsh"), "USAGECLI_SHELL_ZSH");
369        assert_eq!(shell_var_name("fish"), "USAGECLI_SHELL_FISH");
370        assert_eq!(shell_var_name("pwsh"), "USAGECLI_SHELL_PWSH");
371    }
372
373    #[test]
374    fn the_prefix_is_one_mise_does_not_clear() {
375        // mise clears a task's `usage_*` so its own parsed arguments cannot leak in, comparing
376        // the first six characters case-insensitively. Everything this CLI wants to survive
377        // that has to differ inside those six — which is the whole reason for the spelling.
378        for shell in ["bash", "zsh", "fish", "pwsh"] {
379            let name = shell_var_name(shell);
380            assert!(
381                !name[.."usage_".len()].eq_ignore_ascii_case("usage_"),
382                "{name} would be cleared before a mise task ran"
383            );
384        }
385    }
386
387    #[test]
388    fn unset_means_no_override() {
389        assert_eq!(shell_program_override("bash", from(&[])), None);
390    }
391
392    #[test]
393    fn a_blank_value_means_no_override() {
394        for blank in ["", "   ", "\t"] {
395            assert_eq!(
396                shell_program_override("bash", from(&[("USAGE_SHELL_BASH", blank)])),
397                None,
398                "blank value {blank:?} should read as unset"
399            );
400        }
401    }
402
403    #[test]
404    fn surrounding_whitespace_is_trimmed() {
405        assert_eq!(
406            shell_program_override("bash", from(&[("USAGE_SHELL_BASH", "  /usr/bin/bash  ")])),
407            Some("/usr/bin/bash".to_string())
408        );
409    }
410
411    #[test]
412    fn a_path_with_spaces_survives_intact() {
413        let path = r"C:\Program Files\Git\bin\bash.exe";
414        assert_eq!(
415            shell_program_override("bash", from(&[("USAGE_SHELL_BASH", path)])),
416            Some(path.to_string())
417        );
418    }
419
420    #[test]
421    fn another_shells_variable_is_not_picked_up() {
422        assert_eq!(
423            shell_program_override("bash", from(&[("USAGE_SHELL_ZSH", "/bin/zsh")])),
424            None
425        );
426        assert_eq!(
427            shell_program_override("bash", from(&[("USAGECLI_SHELL_ZSH", "/bin/zsh")])),
428            None
429        );
430    }
431
432    // The tests above read the legacy name, which is the point: they were written before the
433    // rename and still pass, so they are what says nothing that set it has broken.
434
435    #[test]
436    fn the_current_name_is_read() {
437        assert_eq!(
438            shell_program_override("bash", from(&[("USAGECLI_SHELL_BASH", "/usr/bin/bash")])),
439            Some("/usr/bin/bash".to_string())
440        );
441    }
442
443    #[test]
444    fn the_current_name_wins_over_the_legacy_one() {
445        assert_eq!(
446            shell_program_override(
447                "bash",
448                from(&[
449                    ("USAGECLI_SHELL_BASH", "/current"),
450                    ("USAGE_SHELL_BASH", "/legacy"),
451                ])
452            ),
453            Some("/current".to_string())
454        );
455    }
456
457    #[test]
458    fn a_blanked_current_name_falls_through_to_the_legacy_one() {
459        // Blank reads as unset at each name rather than at the setting, so `USAGECLI_X= ` does
460        // not switch off a legacy `USAGE_X` the way it switches off its own.
461        assert_eq!(
462            shell_program_override(
463                "bash",
464                from(&[
465                    ("USAGECLI_SHELL_BASH", "  "),
466                    ("USAGE_SHELL_BASH", "/legacy")
467                ])
468            ),
469            Some("/legacy".to_string())
470        );
471    }
472
473    #[test]
474    fn the_log_filter_falls_back_through_both_spellings() {
475        assert_eq!(log_filter(from(&[])), "info");
476        assert_eq!(log_filter(from(&[("USAGE_LOG", "warn")])), "warn");
477        assert_eq!(log_filter(from(&[("USAGECLI_LOG", "warn")])), "warn");
478        // A blank current name is unset at that name, so the legacy one still answers. This is
479        // what `Env::filter_or` could not do: its default applies only to an *unset* variable,
480        // so a blank `USAGECLI_LOG` would have been taken as the filter itself.
481        assert_eq!(
482            log_filter(from(&[("USAGECLI_LOG", "  "), ("USAGE_LOG", "warn")])),
483            "warn"
484        );
485    }
486
487    #[test]
488    fn the_log_filter_keeps_trace_over_debug_over_a_level() {
489        assert_eq!(
490            log_filter(from(&[("USAGE_DEBUG", "1"), ("USAGE_LOG", "warn")])),
491            "debug"
492        );
493        assert_eq!(
494            log_filter(from(&[("USAGECLI_TRACE", "true"), ("USAGE_DEBUG", "1")])),
495            "trace"
496        );
497        // Only `1` and `true` switch it on; anything else is not a level request.
498        assert_eq!(log_filter(from(&[("USAGECLI_DEBUG", "0")])), "info");
499    }
500
501    #[test]
502    fn a_failed_lookup_reports_the_name_that_answered() {
503        assert_eq!(
504            setting_entry("SHELL_BASH", from(&[("USAGE_SHELL_BASH", "/legacy")])),
505            Some(("USAGE_SHELL_BASH".to_string(), "/legacy".to_string()))
506        );
507        assert_eq!(
508            setting_entry("SHELL_BASH", from(&[("USAGECLI_SHELL_BASH", "/current")])),
509            Some(("USAGECLI_SHELL_BASH".to_string(), "/current".to_string()))
510        );
511    }
512
513    #[test]
514    fn settings_are_not_limited_to_shells() {
515        // The same resolution serves USAGECLI_DEBUG, _TRACE and _LOG, which `main` reads.
516        assert_eq!(
517            setting("DEBUG", from(&[("USAGE_DEBUG", "1")])),
518            Some("1".to_string())
519        );
520        assert_eq!(
521            setting(
522                "LOG",
523                from(&[("USAGECLI_LOG", "trace"), ("USAGE_LOG", "debug")])
524            ),
525            Some("trace".to_string())
526        );
527        assert_eq!(setting("TRACE", from(&[])), None);
528    }
529}