zlayer-toolchain 0.14.1

Runtime toolchain provisioning (macOS Homebrew bottle resolver/installer) for ZLayer
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
//! Windows keg provisioning — "our apt" for the HCS sandbox.
//!
//! The Windows analogue of the macOS [`crate::source_build`] /
//! [`crate::prebuilt`] paths. The HCS sandbox has no package manager, so this
//! provisions a named tool into a self-contained, **relocatable** keg with the
//! same [`KegManifest`] layout the macOS kegs use, and the same on-disk cache
//! key (`<cache>/<tool>-<version>-<arch>/` + a `.ready` marker).
//!
//! # Strategy
//!
//! 1. **`git` → MinGit** ([`ensure_mingit`]). Git for Windows publishes
//!    **MinGit**, a fully self-contained, relocatable portable zip (no
//!    installer, no registry writes, no absolute-path baking) — exactly the
//!    Windows equivalent of a relocation-free keg. We resolve the latest release
//!    from the `git-for-windows/git` GitHub releases, fetch the right
//!    architecture's `MinGit-<ver>-{64-bit,arm64}.zip`, and extract it into the
//!    keg.
//! 2. **Everything else → choco fallback.** Formulae with no relocatable
//!    portable artifact are installed with `choco install` inside a throwaway
//!    HCS compute system and captured into a keg. That path needs a live HCS
//!    host, so it is owned by the runtime/builder layer (which has the HCS
//!    machinery) — invoked when this module returns
//!    [`ToolchainError::NotImplemented`] for a non-portable formula — rather
//!    than pulled into this leaf crate (which must not depend on the HCS stack).
//!
//! This module is compiled on **all** hosts (it is pure HTTP + zip extraction +
//! manifest I/O), so the keg format and MinGit resolver are unit-testable on a
//! macOS build host even though the kegs are only *provisioned for* Windows
//! containers.

use std::path::{Path, PathBuf};

use serde::Deserialize;

use crate::error::{Result, ToolchainError};
use crate::manifest::{KegManifest, KegSource};

/// `git-for-windows/git` GitHub "latest release" API endpoint.
const GIT_FOR_WINDOWS_LATEST: &str =
    "https://api.github.com/repos/git-for-windows/git/releases/latest";

/// Offline fallback: the latest known Git for Windows release at the time of
/// writing (looked up from `git-for-windows/git` releases — NOT a stale guess).
/// Used only when the live release API is unreachable (offline / rate-limited),
/// so a per-machine cache can still be seeded deterministically.
const MINGIT_FALLBACK_VERSION: &str = "2.55.0";
/// Release tag matching [`MINGIT_FALLBACK_VERSION`].
const MINGIT_FALLBACK_TAG: &str = "v2.55.0.windows.1";

/// Architecture token used in keg cache keys + MinGit asset names
/// (`x86_64`/`arm64`).
#[must_use]
pub fn windows_arch_token() -> &'static str {
    if cfg!(target_arch = "aarch64") {
        "arm64"
    } else {
        "x86_64"
    }
}

/// Split a package request into `(formula, version_token)` — mirrors the macOS
/// `split_pkg`. The full `pkg` is always the formula/tool name.
fn split_pkg(pkg: &str) -> (&str, &str) {
    match pkg.split_once('@') {
        Some((_, ver)) if !ver.is_empty() => (pkg, ver),
        _ => (pkg, "latest"),
    }
}

/// Provision (or reuse) a Windows keg for `pkg`, returning the keg directory.
///
/// Dispatches: `git` lands as a relocatable MinGit keg; every other formula
/// returns [`ToolchainError::NotImplemented`] so the caller routes it to the
/// HCS choco-capture path (which lives in the runtime layer, not this leaf
/// crate).
///
/// # Errors
///
/// Returns [`ToolchainError::NotImplemented`] for a formula with no portable
/// artifact, or propagates download/extraction errors for `git`.
pub async fn ensure_windows_keg(
    pkg: &str,
    cache_dir: &Path,
    lockfile: Option<&crate::ToolchainLockfile>,
) -> Result<PathBuf> {
    let (formula, _version) = split_pkg(pkg);
    match formula {
        "git" => ensure_mingit(cache_dir, lockfile).await,
        other => Err(ToolchainError::NotImplemented(format!(
            "Windows keg for '{other}' has no portable/relocatable artifact; \
             provision it via the HCS choco-capture path in the runtime layer"
        ))),
    }
}

/// Resolve a Windows tool to `(version, url, published_sha256)` for the lockfile
/// resolver, without downloading. Only `git` (MinGit) is portable; everything
/// else routes to the HCS choco-capture path (not lockable here).
///
/// # Errors
///
/// Returns [`ToolchainError::NotImplemented`] for a non-portable formula.
pub(crate) async fn resolve_locked_windows(
    formula: &str,
) -> Result<(String, String, Option<String>)> {
    match formula {
        "git" => Ok(resolve_mingit(windows_arch_token()).await),
        other => Err(ToolchainError::NotImplemented(format!(
            "Windows keg for '{other}' has no portable/relocatable artifact; cannot lock it"
        ))),
    }
}

/// A single asset attached to a GitHub release.
#[derive(Debug, Clone, Deserialize)]
struct GhAsset {
    name: String,
    #[serde(default)]
    browser_download_url: String,
}

/// The subset of the GitHub release JSON we consume.
#[derive(Debug, Clone, Deserialize)]
struct GhRelease {
    #[serde(default)]
    tag_name: String,
    #[serde(default)]
    assets: Vec<GhAsset>,
}

/// Resolve `<ver>` from a Git for Windows tag (`v2.55.0.windows.1` → `2.55.0`).
fn mingit_version_from_tag(tag: &str) -> String {
    tag.trim_start_matches('v')
        .split(".windows")
        .next()
        .unwrap_or(tag)
        .to_string()
}

/// The MinGit asset file name for `version` + `arch`.
///
/// Git for Windows names them `MinGit-<ver>-64-bit.zip` (x86_64) and
/// `MinGit-<ver>-arm64.zip` (arm64). The plain (non-`busybox`) variant is the
/// full MinGit with the real coreutils.
fn mingit_asset_name(version: &str, arch: &str) -> String {
    let suffix = if arch == "arm64" { "arm64" } else { "64-bit" };
    format!("MinGit-{version}-{suffix}.zip")
}

/// Pick the right MinGit asset from a release's assets for `arch`, preferring
/// the plain (non-`busybox`, non-`32-bit`) build. Returns the download URL.
fn pick_mingit_asset<'a>(assets: &'a [GhAsset], version: &str, arch: &str) -> Option<&'a GhAsset> {
    let want = mingit_asset_name(version, arch);
    assets
        .iter()
        .find(|a| a.name == want && !a.browser_download_url.is_empty())
}

/// Construct the canonical MinGit download URL for a `(tag, version, arch)` —
/// the offline fallback when the release API can't be queried.
fn mingit_download_url(tag: &str, version: &str, arch: &str) -> String {
    format!(
        "https://github.com/git-for-windows/git/releases/download/{tag}/{}",
        mingit_asset_name(version, arch)
    )
}

/// Resolve the MinGit `(version, download_url)` to fetch: query the live release
/// API, falling back to the canonical URL for the pinned fallback version when
/// the API is unreachable.
async fn resolve_mingit(arch: &str) -> (String, String, Option<String>) {
    match fetch_latest_release().await {
        Ok(rel) => {
            let version = mingit_version_from_tag(&rel.tag_name);
            if let Some(asset) = pick_mingit_asset(&rel.assets, &version, arch) {
                // Git for Windows sometimes ships a sibling `<asset>.sha256`.
                let sha = mingit_sibling_sha256(&rel.assets, &asset.name).await;
                return (version, asset.browser_download_url.clone(), sha);
            }
            // API reachable but the expected asset name wasn't found — construct
            // the canonical URL for the resolved tag/version.
            let url = mingit_download_url(&rel.tag_name, &version, arch);
            (version, url, None)
        }
        Err(_) => (
            MINGIT_FALLBACK_VERSION.to_string(),
            mingit_download_url(MINGIT_FALLBACK_TAG, MINGIT_FALLBACK_VERSION, arch),
            None,
        ),
    }
}

/// Best-effort: find a sibling `<asset>.sha256` checksum asset and return its hex
/// digest. Returns `None` when absent or unreadable (compute-on-download).
async fn mingit_sibling_sha256(assets: &[GhAsset], asset_name: &str) -> Option<String> {
    let want = format!("{asset_name}.sha256");
    let asset = assets
        .iter()
        .find(|a| a.name == want && !a.browser_download_url.is_empty())?;
    let text = reqwest::get(&asset.browser_download_url)
        .await
        .ok()?
        .text()
        .await
        .ok()?;
    let token = text.split_whitespace().next()?;
    (token.len() == 64 && token.chars().all(|c| c.is_ascii_hexdigit()))
        .then(|| token.to_ascii_lowercase())
}

/// Fetch + parse the latest `git-for-windows/git` release. GitHub requires a
/// `User-Agent`; we parse from text so no extra reqwest feature is needed.
async fn fetch_latest_release() -> Result<GhRelease> {
    let client = reqwest::Client::builder()
        .user_agent("zlayer-toolchain")
        .build()
        .map_err(|e| ToolchainError::RegistryError {
            message: format!("failed to build HTTP client: {e}"),
        })?;
    let text = client
        .get(GIT_FOR_WINDOWS_LATEST)
        .send()
        .await
        .map_err(|e| ToolchainError::RegistryError {
            message: format!("failed to query git-for-windows releases: {e}"),
        })?
        .text()
        .await
        .map_err(|e| ToolchainError::RegistryError {
            message: format!("failed to read git-for-windows release body: {e}"),
        })?;
    serde_json::from_str(&text).map_err(|e| ToolchainError::RegistryError {
        message: format!("failed to parse git-for-windows release JSON: {e}"),
    })
}

/// Provision the `git` keg from MinGit (a relocatable portable zip).
///
/// Idempotent via the `<keg>/.ready` marker written last. Extracts MinGit into
/// `<cache>/git-<ver>-<arch>/` and writes a [`KegManifest`] whose `path_dirs`
/// are the in-keg MinGit binary directories (`cmd`, `mingw64\bin`, `usr\bin`).
///
/// # Errors
///
/// Propagates download/extraction failures.
pub async fn ensure_mingit(
    cache_dir: &Path,
    lockfile: Option<&crate::ToolchainLockfile>,
) -> Result<PathBuf> {
    let arch = windows_arch_token();

    // A lock hit pins the exact version + URL + digest (consume-only).
    let (version, url, expected_sha) = match lockfile.and_then(|l| {
        use crate::ToolchainLockfileExt;
        l.lookup("git", "windows", arch)
    }) {
        Some(locked) => (
            locked.version.clone(),
            locked.url.clone(),
            Some(locked.sha256.clone()),
        ),
        None => resolve_mingit(arch).await,
    };

    let keg = cache_dir.join(format!("git-{version}-{arch}"));
    let ready_marker = keg.join(".ready");
    if tokio::fs::try_exists(&ready_marker).await.unwrap_or(false) {
        return Ok(keg);
    }

    // Fresh extract — clear any partial keg.
    let _ = tokio::fs::remove_dir_all(&keg).await;
    tokio::fs::create_dir_all(&keg).await?;

    tracing::info!(url = %url, "downloading MinGit for the Windows git keg");
    // Stream + verify (against a lockfile/published digest when available) into a
    // temp zip inside the keg, recording the computed digest in the manifest.
    let zip_path = keg.join(".mingit.zip");
    let computed_sha =
        crate::package_index::download_verified(&url, &zip_path, expected_sha.as_deref()).await?;
    let bytes = tokio::fs::read(&zip_path).await?;

    let keg_clone = keg.clone();
    tokio::task::spawn_blocking(move || extract_zip_to(&bytes, &keg_clone))
        .await
        .map_err(|e| ToolchainError::RegistryError {
            message: format!("MinGit extraction task panicked: {e}"),
        })??;
    let _ = tokio::fs::remove_file(&zip_path).await;

    // MinGit's `git.exe` lives at `cmd\git.exe`; the POSIX helpers + dlls live
    // under `mingw64\bin` and `usr\bin`. All are relocatable (resolved relative
    // to the exe), so the manifest just prepends the in-keg dirs to PATH.
    let path_dirs = ["cmd", "mingw64\\bin", "usr\\bin"]
        .iter()
        .map(|sub| keg.join(sub).display().to_string())
        .collect::<Vec<_>>();

    let manifest = KegManifest {
        tool: "git".to_string(),
        version: version.clone(),
        arch: arch.to_string(),
        platform: "windows".to_string(),
        path_dirs,
        env: std::collections::HashMap::new(),
        source: KegSource::Prebuilt {
            url,
            sha256: computed_sha,
        },
        build_deps: Vec::new(),
        provisioned_at: chrono::Utc::now().to_rfc3339(),
    };
    manifest.write_to_keg(&keg).await?;
    tokio::fs::write(&ready_marker, b"").await?;
    Ok(keg)
}

/// Extract a zip archive (in memory) into `dest`, preserving the archive's
/// internal directory structure. Synchronous (the `zip` crate is blocking) —
/// call under `spawn_blocking`.
fn extract_zip_to(bytes: &[u8], dest: &Path) -> Result<()> {
    let reader = std::io::Cursor::new(bytes);
    let mut archive = zip::ZipArchive::new(reader).map_err(|e| ToolchainError::RegistryError {
        message: format!("failed to open MinGit zip: {e}"),
    })?;
    for i in 0..archive.len() {
        let mut file = archive
            .by_index(i)
            .map_err(|e| ToolchainError::RegistryError {
                message: format!("failed to read zip entry {i}: {e}"),
            })?;
        // `enclosed_name` returns an owned `PathBuf` sanitized against path
        // traversal (`None` = the entry name escaped the archive root); it holds
        // no borrow on `file`, so the later `&mut file` for the copy is free.
        let Some(rel) = file.enclosed_name() else {
            continue; // skip unsafe (path-traversal) entries
        };
        let out_path = dest.join(&rel);
        if file.is_dir() {
            std::fs::create_dir_all(&out_path)?;
            continue;
        }
        if let Some(parent) = out_path.parent() {
            std::fs::create_dir_all(parent)?;
        }
        let mut out = std::fs::File::create(&out_path)?;
        std::io::copy(&mut file, &mut out)?;
    }
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn version_parsed_from_tag() {
        assert_eq!(mingit_version_from_tag("v2.55.0.windows.1"), "2.55.0");
        assert_eq!(mingit_version_from_tag("v2.43.2.windows.2"), "2.43.2");
        assert_eq!(mingit_version_from_tag("2.40.0"), "2.40.0");
    }

    #[test]
    fn asset_name_per_arch() {
        assert_eq!(
            mingit_asset_name("2.55.0", "x86_64"),
            "MinGit-2.55.0-64-bit.zip"
        );
        assert_eq!(
            mingit_asset_name("2.55.0", "arm64"),
            "MinGit-2.55.0-arm64.zip"
        );
    }

    #[test]
    fn download_url_is_canonical() {
        let url = mingit_download_url("v2.55.0.windows.1", "2.55.0", "x86_64");
        assert_eq!(
            url,
            "https://github.com/git-for-windows/git/releases/download/\
             v2.55.0.windows.1/MinGit-2.55.0-64-bit.zip"
        );
    }

    #[test]
    fn picks_plain_mingit_not_busybox_or_32bit() {
        let assets = vec![
            GhAsset {
                name: "MinGit-2.55.0-32-bit.zip".to_string(),
                browser_download_url: "https://x/32".to_string(),
            },
            GhAsset {
                name: "MinGit-2.55.0-busybox-64-bit.zip".to_string(),
                browser_download_url: "https://x/bb".to_string(),
            },
            GhAsset {
                name: "MinGit-2.55.0-64-bit.zip".to_string(),
                browser_download_url: "https://x/64".to_string(),
            },
            GhAsset {
                name: "MinGit-2.55.0-arm64.zip".to_string(),
                browser_download_url: "https://x/arm".to_string(),
            },
        ];
        assert_eq!(
            pick_mingit_asset(&assets, "2.55.0", "x86_64")
                .unwrap()
                .browser_download_url,
            "https://x/64"
        );
        assert_eq!(
            pick_mingit_asset(&assets, "2.55.0", "arm64")
                .unwrap()
                .browser_download_url,
            "https://x/arm"
        );
    }

    #[test]
    fn pick_returns_none_when_asset_missing() {
        let assets = vec![GhAsset {
            name: "MinGit-2.55.0-32-bit.zip".to_string(),
            browser_download_url: "https://x/32".to_string(),
        }];
        assert!(pick_mingit_asset(&assets, "2.55.0", "x86_64").is_none());
    }

    #[test]
    fn release_json_parses() {
        let json = r#"{
            "tag_name": "v2.55.0.windows.1",
            "assets": [
                {"name": "MinGit-2.55.0-64-bit.zip", "browser_download_url": "https://x/64"}
            ]
        }"#;
        let rel: GhRelease = serde_json::from_str(json).unwrap();
        assert_eq!(mingit_version_from_tag(&rel.tag_name), "2.55.0");
        assert_eq!(rel.assets.len(), 1);
    }

    #[tokio::test]
    async fn non_git_formula_is_not_implemented() {
        let tmp = tempfile::tempdir().unwrap();
        let err = ensure_windows_keg("cowsay", tmp.path(), None)
            .await
            .unwrap_err();
        assert!(matches!(err, ToolchainError::NotImplemented(_)));
    }

    #[tokio::test]
    async fn extract_zip_roundtrips_nested_layout() {
        // Build a tiny in-memory zip mirroring MinGit's nested layout, extract
        // it, and assert the tree (and a file's bytes) materialize correctly.
        use std::io::Write;
        let mut buf = Vec::new();
        {
            let mut zw = zip::ZipWriter::new(std::io::Cursor::new(&mut buf));
            let opts = zip::write::SimpleFileOptions::default();
            zw.start_file("cmd/git.exe", opts).unwrap();
            zw.write_all(b"MZ-fake-exe").unwrap();
            zw.start_file("mingw64/bin/git.exe", opts).unwrap();
            zw.write_all(b"MZ-fake-exe-2").unwrap();
            zw.finish().unwrap();
        }
        let tmp = tempfile::tempdir().unwrap();
        extract_zip_to(&buf, tmp.path()).unwrap();
        assert!(tmp.path().join("cmd/git.exe").is_file());
        assert!(tmp.path().join("mingw64/bin/git.exe").is_file());
        assert_eq!(
            std::fs::read(tmp.path().join("cmd/git.exe")).unwrap(),
            b"MZ-fake-exe"
        );
    }
}