Skip to main content

subspace_core/path/
fallback.rs

1//! The usual install folders appended after the captured or inherited
2//! `PATH`, so tools such as `az` are found when the login shell is slow or
3//! prints nothing. The user's own `PATH` order always comes first. System
4//! folders come before per-user ones. A folder is appended only when it
5//! exists and `PATH` does not already hold it.
6//!
7//! Each list is a set of templates: `~/` starts at the home folder and
8//! `%NAME%` reads an environment variable. A template whose home or variable
9//! is not set is skipped, so no drive letter or user name is written here.
10//! To add a folder, add one line with a comment that names what installs
11//! there.
12
13use std::path::{Path, PathBuf};
14
15use super::registry::expand_percent;
16
17/// macOS install folders.
18pub const MACOS_DIRECTORIES: &[&str] = &[
19    // Homebrew on Apple silicon: the azure-cli formula and cask.
20    "/opt/homebrew/bin",
21    "/opt/homebrew/sbin",
22    // Homebrew on Intel; Docker Desktop's kubectl.
23    "/usr/local/bin",
24    "/usr/local/sbin",
25    // MacPorts.
26    "/opt/local/bin",
27    // Microsoft's Azure CLI install script (default exec folder).
28    "~/bin",
29    // pipx and pip --user.
30    "~/.local/bin",
31];
32
33/// Linux install folders. The deb and rpm packages put `az` in `/usr/bin`,
34/// which every `PATH` already holds.
35pub const LINUX_DIRECTORIES: &[&str] = &[
36    // Manual installs and many vendor packages.
37    "/usr/local/bin",
38    // Snap packages.
39    "/snap/bin",
40    // Homebrew on Linux, system and per-user prefixes.
41    "/home/linuxbrew/.linuxbrew/bin",
42    "~/.linuxbrew/bin",
43    // Microsoft's Azure CLI install script (default exec folder).
44    "~/bin",
45    // pipx.
46    "~/.local/bin",
47];
48
49/// Windows install folders. There is no `%LOCALAPPDATA%` entry: the Azure CLI
50/// MSI installs per machine only, and the ZIP package goes to a folder the
51/// user chooses, which no list can know.
52pub const WINDOWS_DIRECTORIES: &[&str] = &[
53    // 64-bit Azure CLI MSI; winget and Chocolatey use this MSI.
54    r"%ProgramFiles%\Microsoft SDKs\Azure\CLI2\wbin",
55    // 32-bit Azure CLI MSI.
56    r"%ProgramFiles(x86)%\Microsoft SDKs\Azure\CLI2\wbin",
57    // Chocolatey shims.
58    r"%ProgramData%\chocolatey\bin",
59    // Scoop shims; the Azure data client finds Scoop's Python beside them.
60    r"%USERPROFILE%\scoop\shims",
61    // pipx.
62    r"%USERPROFILE%\.local\bin",
63];
64
65/// The list for this platform.
66#[cfg(target_os = "macos")]
67pub const FALLBACK_DIRECTORIES: &[&str] = MACOS_DIRECTORIES;
68/// The list for this platform.
69#[cfg(all(unix, not(target_os = "macos")))]
70pub const FALLBACK_DIRECTORIES: &[&str] = LINUX_DIRECTORIES;
71/// The list for this platform.
72#[cfg(windows)]
73pub const FALLBACK_DIRECTORIES: &[&str] = WINDOWS_DIRECTORIES;
74/// No list for other platforms.
75#[cfg(not(any(unix, windows)))]
76pub const FALLBACK_DIRECTORIES: &[&str] = &[];
77
78/// Debug builds only: a PATH-style list of folders that replaces the
79/// platform list, for startup appending and for `find_tool`, so screenshots
80/// and manual tests do not depend on what this computer has installed. An
81/// empty value means no fallback folders. Release builds ignore it.
82/// Example: `SUBSPACE_PATH_FALLBACK_FIXTURE=/tmp/fixture/bin:/tmp/fixture/sbin`.
83#[cfg_attr(not(debug_assertions), allow(dead_code))]
84pub(super) const FIXTURE_ENV: &str = "SUBSPACE_PATH_FALLBACK_FIXTURE";
85
86/// The non-empty folders of a [`FIXTURE_ENV`] value, in order.
87#[cfg_attr(not(debug_assertions), allow(dead_code))]
88pub(super) fn parse_fixture(value: &std::ffi::OsStr) -> Vec<PathBuf> {
89    std::env::split_paths(value)
90        .filter(|entry| !entry.as_os_str().is_empty())
91        .collect()
92}
93
94#[cfg(debug_assertions)]
95fn fixture_folders() -> Option<Vec<PathBuf>> {
96    std::env::var_os(FIXTURE_ENV).map(|value| parse_fixture(&value))
97}
98
99#[cfg(not(debug_assertions))]
100fn fixture_folders() -> Option<Vec<PathBuf>> {
101    None
102}
103
104/// The fallback folders of this process: the debug fixture when set, else
105/// the platform list expanded with `probe`.
106pub(super) fn startup_folders(probe: &Probe<'_>) -> Vec<PathBuf> {
107    fixture_folders().unwrap_or_else(|| expand_all(FALLBACK_DIRECTORIES, probe))
108}
109
110/// What the fallback reads from the environment and the file system.
111pub(super) struct Probe<'a> {
112    /// The home folder for `~/`, or `None` when it is not set.
113    pub(super) home: Option<PathBuf>,
114    /// An environment variable for `%NAME%`.
115    pub(super) lookup: &'a dyn Fn(&str) -> Option<String>,
116    pub(super) is_directory: fn(&Path) -> bool,
117    /// Compare folders as Windows does: `/` is `\` and case is ignored.
118    pub(super) windows: bool,
119}
120
121/// The value of the environment variable `name`, if it is set.
122pub(super) fn env_var(name: &str) -> Option<String> {
123    std::env::var(name).ok()
124}
125
126impl<'a> Probe<'a> {
127    /// The probe of this process: `HOME`, the real environment through
128    /// `lookup` and the file system.
129    pub(super) fn from_env(lookup: &'a dyn Fn(&str) -> Option<String>) -> Self {
130        Self {
131            home: std::env::var_os("HOME")
132                .filter(|home| !home.is_empty())
133                .map(PathBuf::from),
134            lookup,
135            is_directory: Path::is_dir,
136            windows: cfg!(windows),
137        }
138    }
139}
140
141/// `template` with its home folder or variables filled in, or `None` when
142/// one of them is not set.
143pub(super) fn expand(
144    template: &str,
145    home: Option<&Path>,
146    lookup: &dyn Fn(&str) -> Option<String>,
147) -> Option<PathBuf> {
148    if let Some(rest) = template.strip_prefix("~/") {
149        return home.map(|home| home.join(rest));
150    }
151    let expanded = expand_percent(template, |name| {
152        lookup(name).filter(|value| !value.is_empty())
153    });
154    (!expanded.contains('%')).then(|| PathBuf::from(expanded))
155}
156
157/// `directory` as text that compares equal to the same folder written
158/// another way: no trailing separator, and on Windows `\` for `/` and
159/// lower case.
160fn comparable(directory: &Path, windows: bool) -> String {
161    let text = directory.to_string_lossy();
162    let text = if windows {
163        text.replace('/', "\\").to_lowercase()
164    } else {
165        text.into_owned()
166    };
167    let trimmed = text.trim_end_matches(['/', '\\']);
168    if trimmed.is_empty() {
169        text
170    } else {
171        trimmed.to_string()
172    }
173}
174
175/// The `templates` with their home folder and variables filled in, in list
176/// order; templates with an unset home or variable are left out.
177pub(super) fn expand_all(templates: &[&str], probe: &Probe<'_>) -> Vec<PathBuf> {
178    templates
179        .iter()
180        .filter_map(|template| expand(template, probe.home.as_deref(), probe.lookup))
181        .collect()
182}
183
184/// The `candidates` that exist as folders and `present` lacks, in order,
185/// without duplicates.
186pub(super) fn missing_directories(
187    present: &[PathBuf],
188    candidates: Vec<PathBuf>,
189    probe: &Probe<'_>,
190) -> Vec<PathBuf> {
191    let mut known: Vec<String> = present
192        .iter()
193        .map(|entry| comparable(entry, probe.windows))
194        .collect();
195    let mut missing = Vec::new();
196    for directory in candidates {
197        let key = comparable(&directory, probe.windows);
198        if !known.contains(&key) && (probe.is_directory)(&directory) {
199            known.push(key);
200            missing.push(directory);
201        }
202    }
203    missing
204}
205
206#[cfg(test)]
207mod tests;