Skip to main content

day_toolchain/
lib.rs

1// Copyright © The Daybrite Project
2// SPDX-License-Identifier: MPL-2.0
3
4//! day-toolchain is the one place that knows where host toolchains and SDKs live, shared by the
5//! `day` CLI and by crate build scripts (day-toolkit-xaml-sys, every `day-piece-*`/`day-tweak-*` that
6//! compiles its own native shim, and the scaffolds `day new` generates).
7//!
8//! Two rules govern every lookup here (docs/environment.md):
9//!   1. **An environment variable always wins.** Each function documents its override(s).
10//!   2. **No literal install paths.** Default locations are derived from the platform's own
11//!      environment (`%ProgramFiles%`, `$HOME`, `%LOCALAPPDATA%`), never a hardwired `C:\…`,
12//!      so relocated installs (Windows Kits on `D:`, a portable SDK) work by setting one var.
13//!
14//! Functions that are meant to be called from build scripts have `_for_build_script` variants
15//! that also emit the matching `cargo:rerun-if-env-changed=` lines, so changing an override
16//! re-runs the script instead of silently keeping stale results.
17
18use std::path::{Path, PathBuf};
19
20/// The Windows App SDK (WinUI 3) a `windows-winui` build compiles against.
21pub mod winappsdk;
22
23// ---------------------------------------------------------------------------
24// Windows Kits (the Windows 10/11 SDK): cppwinrt headers + bin tools
25// ---------------------------------------------------------------------------
26
27/// Candidate `Windows Kits\10`-style roots, best first.
28///
29/// Overrides: `DAY_WINDOWS_KITS_ROOT` (the `…\Windows Kits\10` directory itself), then the
30/// MS-standard `WindowsSdkDir` (set by Visual Studio developer shells). Fallbacks derive from
31/// `%ProgramFiles(x86)%` / `%ProgramFiles%`, the env vars, not literal `C:\` paths.
32#[must_use]
33pub fn windows_kits_roots() -> Vec<PathBuf> {
34    let mut roots = Vec::new();
35    if let Ok(v) = std::env::var("DAY_WINDOWS_KITS_ROOT") {
36        roots.push(PathBuf::from(v));
37    }
38    if let Ok(v) = std::env::var("WindowsSdkDir") {
39        roots.push(PathBuf::from(v));
40    }
41    for pf in ["ProgramFiles(x86)", "ProgramFiles"] {
42        if let Ok(v) = std::env::var(pf) {
43            roots.push(PathBuf::from(v).join("Windows Kits").join("10"));
44        }
45    }
46    roots.dedup();
47    roots
48}
49
50/// The newest `Include\<version>\cppwinrt` directory (the C++/WinRT projection headers), for
51/// compiling XAML shims with `cc`.
52///
53/// Overrides: `DAY_CPPWINRT` (the exact cppwinrt include dir, highest priority), then the
54/// roots from [`windows_kits_roots`]. Validated by `winrt/base.h`.
55#[must_use]
56pub fn cppwinrt_include() -> Option<PathBuf> {
57    if let Ok(v) = std::env::var("DAY_CPPWINRT") {
58        let p = PathBuf::from(v);
59        if p.join("winrt").join("base.h").exists() {
60            return Some(p);
61        }
62        // An explicit override that doesn't validate is a configuration error worth surfacing
63        // loudly in a build script; returning None lets the caller's expect() name the fix.
64        return None;
65    }
66    let mut found: Vec<PathBuf> = Vec::new();
67    for root in windows_kits_roots() {
68        let Ok(rd) = std::fs::read_dir(root.join("Include")) else {
69            continue;
70        };
71        for entry in rd.flatten() {
72            let cppwinrt = entry.path().join("cppwinrt");
73            if cppwinrt.join("winrt").join("base.h").exists() {
74                found.push(cppwinrt);
75            }
76        }
77    }
78    found.sort(); // version dirs sort lexicographically; newest last
79    found.pop()
80}
81
82/// [`cppwinrt_include`] for build scripts: also emits the `rerun-if-env-changed` lines so an
83/// override change re-runs the script.
84#[must_use]
85pub fn cppwinrt_include_for_build_script() -> Option<PathBuf> {
86    for var in ["DAY_CPPWINRT", "DAY_WINDOWS_KITS_ROOT", "WindowsSdkDir"] {
87        println!("cargo:rerun-if-env-changed={var}");
88    }
89    cppwinrt_include()
90}
91
92/// A Windows-Kits bin tool (`signtool.exe`, `makeappx.exe`, …): newest SDK version, host arch.
93///
94/// Overrides: `DAY_WINDOWS_KIT` (a bin directory containing the tool), then the tool on `PATH`,
95/// then `bin\<version>\<arch>` under each [`windows_kits_roots`] root.
96#[must_use]
97pub fn windows_kit_tool(tool: &str) -> Option<PathBuf> {
98    if let Ok(root) = std::env::var("DAY_WINDOWS_KIT") {
99        let p = PathBuf::from(root).join(tool);
100        if p.exists() {
101            return Some(p);
102        }
103    }
104    if let Some(p) = on_path(tool) {
105        return Some(p);
106    }
107    let arch = if cfg!(target_arch = "aarch64") {
108        "arm64"
109    } else {
110        "x64"
111    };
112    for root in windows_kits_roots() {
113        let Ok(rd) = std::fs::read_dir(root.join("bin")) else {
114            continue;
115        };
116        let mut versions: Vec<PathBuf> = rd
117            .flatten()
118            .map(|e| e.path())
119            .filter(|p| {
120                p.file_name()
121                    .is_some_and(|n| n.to_string_lossy().starts_with("10."))
122            })
123            .collect();
124        versions.sort();
125        while let Some(v) = versions.pop() {
126            let candidate = v.join(arch).join(tool);
127            if candidate.exists() {
128                return Some(candidate);
129            }
130        }
131    }
132    None
133}
134
135// ---------------------------------------------------------------------------
136// NSIS
137// ---------------------------------------------------------------------------
138
139/// The `makensis` NSIS compiler (cross-platform: apt/brew/choco all put it on PATH).
140///
141/// Overrides: `DAY_MAKENSIS` (the executable itself), then `PATH`, then the conventional
142/// Windows install dir under `%ProgramFiles(x86)%` / `%ProgramFiles%`.
143pub fn makensis() -> Option<PathBuf> {
144    if let Ok(v) = std::env::var("DAY_MAKENSIS") {
145        let p = PathBuf::from(v);
146        if p.is_file() {
147            return Some(p);
148        }
149        return None; // explicit override that doesn't exist = configuration error, don't mask it
150    }
151    if let Some(p) = on_path("makensis").or_else(|| on_path("makensis.exe")) {
152        return Some(p);
153    }
154    for pf in ["ProgramFiles(x86)", "ProgramFiles"] {
155        if let Ok(v) = std::env::var(pf) {
156            let p = PathBuf::from(v).join("NSIS").join("makensis.exe");
157            if p.exists() {
158                return Some(p);
159            }
160        }
161    }
162    // Chocolatey (`choco install nsis`), the way CI and most Windows devs get it. Its shim lands
163    // in the chocolatey bin dir, which is on the machine PATH, but a PATH edit made by an install
164    // does not reach a process that is already running: GitHub Actions hands every step the
165    // environment captured when the job started, so `choco install` in one step leaves the next
166    // step's PATH untouched. Probing the location directly is what makes the install usable in
167    // the same job.
168    let choco = std::env::var("ChocolateyInstall").map_or_else(
169        |_| PathBuf::from(r"C:\ProgramData\chocolatey"),
170        PathBuf::from,
171    );
172    let shim = choco.join("bin").join("makensis.exe");
173    if shim.is_file() {
174        return Some(shim);
175    }
176    // The package's own tree, when it unpacks rather than shimming. The directory under `tools`
177    // carries the NSIS version, so scan one level instead of guessing it.
178    let tools = choco.join("lib").join("nsis").join("tools");
179    if let Ok(entries) = std::fs::read_dir(&tools) {
180        for entry in entries.flatten() {
181            for candidate in [
182                entry.path().join("makensis.exe"),
183                entry.path().join("Bin").join("makensis.exe"),
184            ] {
185                if candidate.is_file() {
186                    return Some(candidate);
187                }
188            }
189        }
190    }
191    None
192}
193
194// ---------------------------------------------------------------------------
195// Android SDK + JDK
196// ---------------------------------------------------------------------------
197
198/// The Android SDK root.
199///
200/// Overrides: `ANDROID_HOME`, then `ANDROID_SDK_ROOT` (both standard). Then each platform's
201/// default install location: `~/Library/Android/sdk` (macOS), `%LOCALAPPDATA%\Android\Sdk`
202/// (Windows), `~/Android/Sdk` (Linux), which is where Android Studio puts it. When nothing is
203/// there, the location Android Studio records for its SDK (see [`android_studio_sdk_setting`]),
204/// so an SDK moved elsewhere from Studio's settings is still found. The default is returned when
205/// neither exists, for the diagnostics to name.
206#[must_use]
207pub fn android_sdk_dir() -> PathBuf {
208    if let Ok(v) = std::env::var("ANDROID_HOME").or_else(|_| std::env::var("ANDROID_SDK_ROOT")) {
209        return PathBuf::from(v);
210    }
211    let default = default_android_sdk_dir();
212    if default.is_dir() {
213        return default;
214    }
215    android_studio_sdk_setting()
216        .filter(|p| p.is_dir())
217        .unwrap_or(default)
218}
219
220fn default_android_sdk_dir() -> PathBuf {
221    if cfg!(target_os = "windows")
222        && let Ok(v) = std::env::var("LOCALAPPDATA")
223    {
224        return PathBuf::from(v).join("Android").join("Sdk");
225    }
226    let home = home_dir();
227    if cfg!(target_os = "macos") {
228        home.join("Library/Android/sdk")
229    } else {
230        home.join("Android/Sdk")
231    }
232}
233
234fn home_dir() -> PathBuf {
235    PathBuf::from(
236        std::env::var("HOME")
237            .or_else(|_| std::env::var("USERPROFILE"))
238            .unwrap_or_default(),
239    )
240}
241
242/// Every Android Studio installation this machine has, most likely first.
243///
244/// Where each platform's installers put it: the macOS app bundle (system or per-user
245/// Applications), the Windows installer's directory, and on Linux the Snap, a tarball unpacked
246/// into `/opt`, `/usr/local` or the home directory, JetBrains Toolbox, and the Flathub build.
247/// `ANDROID_STUDIO_HOME` names one explicitly and comes first. A result is a directory holding
248/// Studio's own layout (`bin/` and the bundled `jbr/`), or a macOS bundle's `Contents/`.
249#[must_use]
250pub fn android_studio_homes() -> Vec<PathBuf> {
251    let home = home_dir();
252    let mut candidates: Vec<PathBuf> = Vec::new();
253    if let Ok(v) = std::env::var("ANDROID_STUDIO_HOME") {
254        candidates.push(PathBuf::from(v));
255    }
256    if cfg!(target_os = "macos") {
257        for apps in [PathBuf::from("/Applications"), home.join("Applications")] {
258            for name in ["Android Studio.app", "Android Studio Preview.app"] {
259                candidates.push(apps.join(name).join("Contents"));
260            }
261        }
262    } else if cfg!(target_os = "windows") {
263        for var in ["ProgramFiles", "ProgramFiles(x86)"] {
264            if let Ok(v) = std::env::var(var) {
265                candidates.push(PathBuf::from(v).join("Android").join("Android Studio"));
266            }
267        }
268        if let Ok(v) = std::env::var("LOCALAPPDATA") {
269            candidates.push(PathBuf::from(&v).join("Programs").join("Android Studio"));
270            candidates.push(PathBuf::from(v).join("JetBrains/Toolbox/apps/android-studio"));
271        }
272    } else {
273        candidates.extend([
274            PathBuf::from("/snap/android-studio/current"),
275            PathBuf::from("/opt/android-studio"),
276            PathBuf::from("/usr/local/android-studio"),
277            home.join("android-studio"),
278            home.join(".local/share/JetBrains/Toolbox/apps/android-studio"),
279            PathBuf::from(
280                "/var/lib/flatpak/app/com.google.AndroidStudio/current/active/files/extra/android-studio",
281            ),
282            home.join(
283                ".local/share/flatpak/app/com.google.AndroidStudio/current/active/files/extra/android-studio",
284            ),
285        ]);
286    }
287    candidates.dedup();
288    candidates.retain(|p| p.join("bin").is_dir() || p.join("MacOS").is_dir());
289    candidates
290}
291
292/// The JDK Android Studio bundles (its JetBrains Runtime), from the first installation that has
293/// one. It is the JDK Studio itself runs Gradle with, so the Android build is known to work on it,
294/// whatever other Java the machine has.
295#[must_use]
296pub fn android_studio_jbr() -> Option<PathBuf> {
297    let java = if cfg!(windows) { "java.exe" } else { "java" };
298    android_studio_homes().into_iter().find_map(|studio| {
299        // macOS nests a whole JDK bundle under jbr/.
300        [studio.join("jbr/Contents/Home"), studio.join("jbr")]
301            .into_iter()
302            .find(|jdk| jdk.join("bin").join(java).is_file())
303    })
304}
305
306/// The SDK location Android Studio's own settings record (Settings ▸ Languages & Frameworks ▸
307/// Android SDK), from the newest Studio configuration directory that has one: its
308/// `options/android.sdk.path.xml`, whose path may start with Studio's `$USER_HOME$` macro.
309pub fn android_studio_sdk_setting() -> Option<PathBuf> {
310    let home = home_dir();
311    let config = if cfg!(target_os = "macos") {
312        home.join("Library/Application Support/Google")
313    } else if cfg!(target_os = "windows") {
314        PathBuf::from(std::env::var("APPDATA").ok()?).join("Google")
315    } else {
316        std::env::var("XDG_CONFIG_HOME")
317            .map_or_else(|_| home.join(".config"), PathBuf::from)
318            .join("Google")
319    };
320    let mut dirs: Vec<PathBuf> = std::fs::read_dir(&config)
321        .ok()?
322        .filter_map(|e| e.ok().map(|e| e.path()))
323        .filter(|p| {
324            p.file_name()
325                .and_then(|n| n.to_str())
326                .is_some_and(|n| n.starts_with("AndroidStudio"))
327        })
328        .collect();
329    // The newest release sorts last; its settings are the ones in use.
330    dirs.sort();
331    dirs.iter().rev().find_map(|dir| {
332        let xml = std::fs::read_to_string(dir.join("options/android.sdk.path.xml")).ok()?;
333        parse_studio_sdk_path(&xml, &home)
334    })
335}
336
337/// The `androidSdkAbsolutePath` value in Studio's `android.sdk.path.xml`, with `$USER_HOME$`
338/// expanded.
339fn parse_studio_sdk_path(xml: &str, home: &Path) -> Option<PathBuf> {
340    let at = xml.find("androidSdkAbsolutePath")?;
341    let rest = &xml[at..];
342    let start = rest.find("value=\"")? + "value=\"".len();
343    let end = rest[start..].find('"')?;
344    let raw = &rest[start..start + end];
345    let expanded = match raw.strip_prefix("$USER_HOME$") {
346        Some(tail) => format!("{}{tail}", home.display()),
347        None => raw.to_string(),
348    };
349    (!expanded.is_empty()).then(|| PathBuf::from(expanded))
350}
351
352/// The `sdkmanager` of the SDK's command-line tools, if they are installed. Android Studio
353/// installs them into the SDK (SDK Tools ▸ Android SDK Command-line Tools), not onto PATH.
354#[must_use]
355pub fn android_sdkmanager() -> Option<PathBuf> {
356    let name = if cfg!(windows) {
357        "sdkmanager.bat"
358    } else {
359        "sdkmanager"
360    };
361    let tools = android_sdk_dir().join("cmdline-tools");
362    let latest = tools.join("latest/bin").join(name);
363    if latest.is_file() {
364        return Some(latest);
365    }
366    // A versioned install (`cmdline-tools/19.0/`), newest last.
367    let mut versions: Vec<PathBuf> = std::fs::read_dir(&tools)
368        .ok()?
369        .filter_map(|e| e.ok().map(|e| e.path().join("bin").join(name)))
370        .filter(|p| p.is_file())
371        .collect();
372    versions.sort();
373    versions.pop()
374}
375
376/// The `adb` this machine should use: the SDK's own copy first, then whatever is on PATH.
377///
378/// PATH alone is not enough, and the failure it produces is invisible rather than loud. A GitHub
379/// Linux runner sets `ANDROID_HOME` but does not put `platform-tools` on PATH, so every `adb` call
380/// returns "not found", and code that reads `adb devices` to see whether a device exists then
381/// concludes there is none. A CI boot waited out its full ten minutes reporting "adb sees it: no"
382/// while the emulator sat there fully booted, because the question was never asked.
383#[must_use]
384pub fn adb_bin() -> String {
385    let exe = if cfg!(windows) { "adb.exe" } else { "adb" };
386    let in_sdk = android_sdk_dir().join("platform-tools").join(exe);
387    if in_sdk.is_file() {
388        return in_sdk.display().to_string();
389    }
390    exe.to_string()
391}
392
393/// A JDK home for the Gradle/AGP build. AGP 9's minimum is JDK 17, and Gradle must support the
394/// exact version. Gradle 9.6 runs on 17…26 (verified: the day scaffold builds on 17, 21 and 26
395/// alike, so the old "21 exactly / 22+ breaks the jdk-image transform" restriction was an AGP-8-era
396/// carryover and no longer holds).
397///
398/// Overrides: `JAVA_HOME` (trusted as-is, which is Gradle's contract). Fallbacks: Android
399/// Studio's bundled JDK ([`android_studio_jbr`]), then macOS's
400/// `/usr/libexec/java_home -v 17+` registry (the newest install ≥ 17), then a Homebrew `openjdk`
401/// keg, the unversioned latest first, then pinned 17+ kegs (both Apple-Silicon and Intel
402/// prefixes). Callers export the result as `JAVA_HOME` for the Gradle child process.
403#[must_use]
404pub fn jdk_home() -> Option<PathBuf> {
405    if let Ok(v) = std::env::var("JAVA_HOME") {
406        return Some(PathBuf::from(v));
407    }
408    // Android Studio's bundled runtime, on every host: the JDK Studio runs this same Gradle
409    // build with. It comes before whatever else is installed because it is the one known to be
410    // in Gradle's supported range; a system JDK newer than Gradle supports fails the build.
411    if let Some(jbr) = android_studio_jbr() {
412        return Some(jbr);
413    }
414    if cfg!(target_os = "macos") {
415        // The canonical macOS JDK registry (also finds Temurin/Zulu installs, beyond brew's).
416        if let Ok(out) = std::process::Command::new("/usr/libexec/java_home")
417            .args(["-v", "17+"])
418            .output()
419            && out.status.success()
420        {
421            let p = PathBuf::from(String::from_utf8_lossy(&out.stdout).trim());
422            if p.join("bin/java").exists() {
423                return Some(p);
424            }
425        }
426        // Newest keg first: the unversioned `openjdk` is Homebrew's current, then LTS/common pins.
427        for keg in ["openjdk", "openjdk@21", "openjdk@17"] {
428            for prefix in ["/opt/homebrew", "/usr/local"] {
429                let p = PathBuf::from(prefix).join("opt").join(keg);
430                if p.join("bin/java").exists() {
431                    return Some(p);
432                }
433            }
434        }
435    }
436    None
437}
438
439// ---------------------------------------------------------------------------
440// wasm32 C compiler (web-dom's bundled-SQLite build)
441// ---------------------------------------------------------------------------
442
443/// How a web-dom build gets the C compiler for its `cc`-built dependencies (day-sqlite-worker's
444/// bundled SQLite), resolved by [`wasm_cc`].
445#[derive(Debug, Clone, PartialEq, Eq)]
446pub enum WasmCc {
447    /// A cc-rs compiler variable is set. cc-rs will run this program whatever it is, so the
448    /// resolver reports it unprobed and callers must not override it.
449    Env(String),
450    /// Plain `clang` on PATH has the wasm32 backend; cc-rs's default works untouched.
451    PathClang,
452    /// A wasm-capable clang found outside PATH. Callers export it as
453    /// `CC_wasm32_unknown_unknown` on the cargo child process for cc-rs to use it.
454    Fallback(PathBuf),
455    /// No compiler with the backend anywhere; a day-persistence web build will fail in cc-rs.
456    Missing,
457}
458
459/// The C compiler a web-dom build's `cc`-built dependencies will use for
460/// `wasm32-unknown-unknown`.
461///
462/// Overrides: the `cc` crate's variables, in its order: `CC_wasm32-unknown-unknown`,
463/// `CC_wasm32_unknown_unknown`, `TARGET_CC`, `CC`. With none set, plain `clang` is probed
464/// ([`emits_wasm32`]; Apple's Xcode clang has no wasm32 backend, the usual macOS miss), then
465/// installs that don't put clang on PATH: Homebrew LLVM kegs (keg-only, so `brew install llvm`
466/// alone is enough) and swift.org toolchains, so an LLVM the user installed comes before one
467/// that rode in with Swift.
468pub fn wasm_cc() -> WasmCc {
469    for var in [
470        "CC_wasm32-unknown-unknown",
471        "CC_wasm32_unknown_unknown",
472        "TARGET_CC",
473        "CC",
474    ] {
475        if let Ok(v) = std::env::var(var)
476            && let Some(program) = v.split_whitespace().next()
477        {
478            return WasmCc::Env(program.to_string());
479        }
480    }
481    if emits_wasm32(Path::new("clang")) {
482        return WasmCc::PathClang;
483    }
484    let mut candidates: Vec<PathBuf> = ["/opt/homebrew", "/usr/local"]
485        .iter()
486        .map(|prefix| PathBuf::from(prefix).join("opt/llvm/bin/clang"))
487        .collect();
488    // swift.org toolchains each ship a full LLVM clang. `swift-latest` is the installer's
489    // "current" symlink; the directory scan behind it catches layouts without the symlink,
490    // newest release first where names sort by version.
491    let per_user = std::env::var("HOME")
492        .ok()
493        .map(|h| PathBuf::from(h).join("Library/Developer/Toolchains"));
494    let system = Some(PathBuf::from("/Library/Developer/Toolchains"));
495    for base in [per_user, system].into_iter().flatten() {
496        candidates.push(base.join("swift-latest.xctoolchain/usr/bin/clang"));
497        if let Ok(entries) = std::fs::read_dir(&base) {
498            let mut toolchains: Vec<PathBuf> = entries
499                .flatten()
500                .map(|e| e.path())
501                .filter(|p| p.extension().is_some_and(|e| e == "xctoolchain"))
502                .collect();
503            toolchains.sort();
504            toolchains.reverse();
505            candidates.extend(toolchains.into_iter().map(|p| p.join("usr/bin/clang")));
506        }
507    }
508    candidates
509        .into_iter()
510        .find(|c| c.is_file() && emits_wasm32(c))
511        .map_or(WasmCc::Missing, WasmCc::Fallback)
512}
513
514/// Whether the clang-style driver at `cc` can emit wasm32 objects (`--print-targets` lists a
515/// `wasm32` row). Apple's Xcode clang is the notable no.
516#[must_use]
517pub fn emits_wasm32(cc: &Path) -> bool {
518    std::process::Command::new(cc)
519        .arg("--print-targets")
520        .output()
521        .ok()
522        .filter(|o| o.status.success())
523        .is_some_and(|o| {
524            String::from_utf8_lossy(&o.stdout)
525                .lines()
526                .any(|l| l.trim().starts_with("wasm32 "))
527        })
528}
529
530// ---------------------------------------------------------------------------
531// rustup
532// ---------------------------------------------------------------------------
533
534/// The rustup toolchain to use for cross-std builds (mobile targets need rustup's target std;
535/// a Homebrew/system rustc has none), as `(cargo_path, bin_dir)`. The bin dir is prepended to
536/// `PATH` so the toolchain's `rustc`, not one earlier on `PATH`, is what cargo invokes.
537///
538/// Overrides: `RUSTUP_HOME` (standard; default `~/.rustup`). Among installed toolchains a
539/// `stable-*` one is preferred, then the lexicographically first, which is deterministic where
540/// the old first-directory-wins behavior depended on filesystem order.
541///
542/// # Errors
543///
544/// Returns an error when neither `RUSTUP_HOME` nor `HOME` is set, or the rustup home has no
545/// installed toolchain.
546pub fn rustup_cargo() -> Result<(PathBuf, PathBuf), String> {
547    let rustup_home = std::env::var("RUSTUP_HOME")
548        .map(PathBuf::from)
549        .or_else(|_| {
550            std::env::var("HOME")
551                .map(|h| PathBuf::from(h).join(".rustup"))
552                .map_err(|e| e.to_string())
553        })?;
554    let toolchains = rustup_home.join("toolchains");
555    let mut entries: Vec<PathBuf> = std::fs::read_dir(&toolchains)
556        .map_err(|_| "no rustup toolchains (cross-std needs rustup, not Homebrew rust)")?
557        .flatten()
558        .map(|e| e.path())
559        .collect();
560    entries.sort();
561    let chosen = entries
562        .iter()
563        .find(|p| {
564            p.file_name()
565                .is_some_and(|n| n.to_string_lossy().starts_with("stable-"))
566        })
567        .or_else(|| entries.first())
568        .ok_or("empty rustup toolchains dir")?;
569    let bin = chosen.join("bin");
570    Ok((bin.join("cargo"), bin))
571}
572
573// ---------------------------------------------------------------------------
574
575fn on_path(tool: &str) -> Option<PathBuf> {
576    let path = std::env::var_os("PATH")?;
577    std::env::split_paths(&path)
578        .map(|d| d.join(tool))
579        .find(|p| p.is_file())
580}
581
582/// True when `dir` looks like a usable directory (exists and is a dir); a small helper for
583/// callers validating overrides.
584#[must_use]
585pub fn is_dir(dir: &Path) -> bool {
586    dir.is_dir()
587}
588
589#[cfg(test)]
590mod tests {
591    #[test]
592    fn studio_sdk_path_expands_user_home() {
593        use std::path::{Path, PathBuf};
594        let xml = r#"<application>
595  <component name="AndroidSdkPathStore">
596    <option name="androidSdkAbsolutePath" value="$USER_HOME$/Android/Sdk" />
597  </component>
598</application>"#;
599        assert_eq!(
600            super::parse_studio_sdk_path(xml, Path::new("/home/ada")),
601            Some(PathBuf::from("/home/ada/Android/Sdk"))
602        );
603        let abs = r#"<option name="androidSdkAbsolutePath" value="/data/sdk" />"#;
604        assert_eq!(
605            super::parse_studio_sdk_path(abs, Path::new("/home/ada")),
606            Some(PathBuf::from("/data/sdk"))
607        );
608        assert_eq!(
609            super::parse_studio_sdk_path("<application/>", Path::new("/")),
610            None
611        );
612    }
613
614    use super::*;
615
616    #[test]
617    fn kits_roots_honor_override_first() {
618        // SAFETY: test-local env mutation; tests touch distinct vars.
619        unsafe { std::env::set_var("DAY_WINDOWS_KITS_ROOT", "/custom/kits/10") };
620        let roots = windows_kits_roots();
621        assert_eq!(roots[0], PathBuf::from("/custom/kits/10"));
622        unsafe { std::env::remove_var("DAY_WINDOWS_KITS_ROOT") };
623    }
624
625    #[test]
626    fn android_sdk_honors_android_home() {
627        unsafe { std::env::set_var("ANDROID_HOME", "/custom/android") };
628        assert_eq!(android_sdk_dir(), PathBuf::from("/custom/android"));
629        unsafe { std::env::remove_var("ANDROID_HOME") };
630    }
631
632    #[test]
633    fn wasm_cc_honors_cc_variables_unprobed() {
634        // SAFETY: test-local env mutation; no other test touches the cc-rs variables.
635        unsafe { std::env::set_var("CC_wasm32-unknown-unknown", "/custom/clang --sysroot=/x") };
636        // Reported as-is (program only, flags dropped) even though the path doesn't exist:
637        // cc-rs will run whatever the variable says, so the resolver must not second-guess it.
638        assert_eq!(wasm_cc(), WasmCc::Env("/custom/clang".to_string()));
639        unsafe { std::env::remove_var("CC_wasm32-unknown-unknown") };
640    }
641
642    #[test]
643    fn explicit_cppwinrt_override_must_validate() {
644        unsafe { std::env::set_var("DAY_CPPWINRT", "/does/not/exist") };
645        assert_eq!(cppwinrt_include(), None); // bad override surfaces, not masked by fallbacks
646        unsafe { std::env::remove_var("DAY_CPPWINRT") };
647    }
648
649    #[test]
650    fn explicit_makensis_override_must_validate() {
651        unsafe { std::env::set_var("DAY_MAKENSIS", "/does/not/exist/makensis.exe") };
652        assert_eq!(makensis(), None); // same contract as the other overrides: never masked
653        unsafe { std::env::remove_var("DAY_MAKENSIS") };
654    }
655
656    /// The layouts `choco install nsis` can leave behind. Each is created on disk under a temp
657    /// `ChocolateyInstall` so the probe is exercised rather than assumed; this is the lookup that
658    /// failed a release build after NSIS had actually been installed.
659    #[test]
660    fn makensis_found_in_chocolatey_layouts() {
661        let base = std::env::temp_dir().join(format!("day-choco-probe-{}", std::process::id()));
662        let shimmed = base.join("shim");
663        let unpacked = base.join("unpacked");
664        let nested = base.join("nested");
665        let _ = std::fs::remove_dir_all(&base);
666
667        // 1. the shim chocolatey drops in its bin dir
668        let shim_exe = shimmed.join("bin").join("makensis.exe");
669        std::fs::create_dir_all(shim_exe.parent().unwrap()).unwrap();
670        std::fs::write(&shim_exe, b"").unwrap();
671
672        // 2. unpacked under lib/nsis/tools/<versioned dir>/
673        let flat = unpacked
674            .join("lib/nsis/tools")
675            .join("nsis-3.10")
676            .join("makensis.exe");
677        std::fs::create_dir_all(flat.parent().unwrap()).unwrap();
678        std::fs::write(&flat, b"").unwrap();
679
680        // 3. …with the executable one level deeper, in Bin/
681        let deep = nested
682            .join("lib/nsis/tools")
683            .join("nsis-3.10")
684            .join("Bin")
685            .join("makensis.exe");
686        std::fs::create_dir_all(deep.parent().unwrap()).unwrap();
687        std::fs::write(&deep, b"").unwrap();
688
689        // The earlier probes must not answer first, or this proves nothing, and on a machine that
690        // really has NSIS in Program Files they would. Saved and put back below: PATH in particular
691        // is process-global, and leaving it empty would poison every test that runs after this one.
692        let (path, pf, pf86) = (
693            std::env::var_os("PATH"),
694            std::env::var_os("ProgramFiles"),
695            std::env::var_os("ProgramFiles(x86)"),
696        );
697        unsafe {
698            std::env::remove_var("DAY_MAKENSIS");
699            std::env::set_var("PATH", "");
700            std::env::set_var("ProgramFiles", base.join("no-such-pf"));
701            std::env::set_var("ProgramFiles(x86)", base.join("no-such-pf86"));
702        }
703
704        let found: Vec<_> = [(&shimmed, &shim_exe), (&unpacked, &flat), (&nested, &deep)]
705            .iter()
706            .map(|(root, want)| {
707                unsafe { std::env::set_var("ChocolateyInstall", root) };
708                (makensis(), (*want).clone())
709            })
710            .collect();
711
712        unsafe {
713            std::env::remove_var("ChocolateyInstall");
714            match path {
715                Some(v) => std::env::set_var("PATH", v),
716                None => std::env::remove_var("PATH"),
717            }
718            match pf {
719                Some(v) => std::env::set_var("ProgramFiles", v),
720                None => std::env::remove_var("ProgramFiles"),
721            }
722            match pf86 {
723                Some(v) => std::env::set_var("ProgramFiles(x86)", v),
724                None => std::env::remove_var("ProgramFiles(x86)"),
725            }
726        }
727        let _ = std::fs::remove_dir_all(&base);
728
729        // Asserted only after the environment is back, so a failure can't take the rest with it.
730        for (got, want) in found {
731            assert_eq!(got.as_ref(), Some(&want), "chocolatey layout {want:?}");
732        }
733    }
734}