Skip to main content

kh_runtime/bottle/
guest_tools.rs

1//! Optional guest tools installed **into the bottle** at real macOS paths.
2//!
3//! Example: Darwin `7zz` → `{bottle}/usr/local/bin/7zz`, which is guest path
4//! `/usr/local/bin/7zz` — the same place a real Mac would keep a CLI install.
5//! Kakehashi is not a 7-Zip product; packages are opt-in via `kh install`.
6//!
7//! Downloads go through [`super::download_cache`] so Docker/Colima re-runs
8//! (bind-mounted `KAKEHASHI_DATA_DIR`) do not re-fetch archives. Install is
9//! **idempotent** when the guest binary is already present in the bottle.
10
11use std::fs;
12use std::io;
13use std::path::{Path, PathBuf};
14use std::process::Command;
15
16use super::download_cache;
17use super::layout::is_bottle_root;
18use super::manage;
19use super::xcode_tools;
20
21/// Env override: host path of a Darwin `7zz` binary (skip download).
22pub const ENV_7ZZ: &str = "KAKEHASHI_7ZZ";
23
24/// Env override: host path of a Darwin `curl` binary (skip download).
25pub const ENV_CURL: &str = "KAKEHASHI_CURL";
26
27/// Legacy ad-hoc drop location (still checked by discovery helpers).
28pub const DEFAULT_7ZZ_PATH: &str = "/tmp/7zz";
29
30/// Official macOS console 7-Zip (universal arm64 / x86_64 Mach-O).
31pub const DARWIN_7ZZ_URL: &str =
32    "https://github.com/ip7z/7zip/releases/download/26.02/7z2602-mac.tar.xz";
33
34/// Public Darwin arm64 static-ish curl (stunnel/static-curl release).
35///
36/// Archive root contains a single `curl` Mach-O. Prefer this over Apple
37/// `/usr/bin/curl` (which needs `libcurl.4.dylib`). Still may link Apple
38/// frameworks for TLS — probe will surface that; see `docs/curl.md`.
39pub const DARWIN_CURL_URL: &str = "https://github.com/stunnel/static-curl/releases/download/8.21.0/curl-macos-arm64-8.21.0.tar.xz";
40
41/// Cache object names under `data/cache/downloads/`.
42const CACHE_7ZZ_ARCHIVE: &str = "7z2602-mac.tar.xz";
43const CACHE_CURL_ARCHIVE: &str = "curl-macos-arm64-8.21.0.tar.xz";
44
45/// Guest-relative install path for Darwin 7zz (under bottle root).
46///
47/// On a real Mac this is `/usr/local/bin/7zz`.
48pub const GUEST_7ZZ_REL: &str = "usr/local/bin/7zz";
49
50/// Guest-relative install path for Darwin curl (under bottle root).
51///
52/// On a real Mac this is `/usr/local/bin/curl`.
53pub const GUEST_CURL_REL: &str = "usr/local/bin/curl";
54
55/// Known installable package ids (`kh install <name>`).
56#[derive(Debug, Clone, Copy, PartialEq, Eq)]
57pub enum InstallPackage {
58    /// Darwin 7-Zip console (`7zz`).
59    SevenZip,
60    /// Darwin `curl` (downloaded arm64 Mach-O; see `docs/curl.md`).
61    Curl,
62    /// Apple Command Line Tools (includes Apple `git`; see `docs/git.md`).
63    XcodeTools,
64}
65
66impl InstallPackage {
67    /// Parse CLI package name (case-insensitive).
68    #[must_use]
69    pub fn parse(name: &str) -> Option<Self> {
70        match name.to_ascii_lowercase().as_str() {
71            "7zip" | "7zz" | "sevenzip" | "p7zip" => Some(Self::SevenZip),
72            "curl" => Some(Self::Curl),
73            "xcode-tools" | "xcodetools" | "clt" | "command-line-tools"
74            | "commandlinetools" | "git" => Some(Self::XcodeTools),
75            _ => None,
76        }
77    }
78
79    /// Canonical name for messages.
80    #[must_use]
81    pub const fn as_str(self) -> &'static str {
82        match self {
83            Self::SevenZip => "7zip",
84            Self::Curl => "curl",
85            Self::XcodeTools => "xcode-tools",
86        }
87    }
88
89    /// Guest absolute path after install (with leading `/`).
90    #[must_use]
91    pub const fn guest_path(self) -> &'static str {
92        match self {
93            Self::SevenZip => "/usr/local/bin/7zz",
94            Self::Curl => "/usr/local/bin/curl",
95            Self::XcodeTools => xcode_tools::GUEST_GIT_PATH,
96        }
97    }
98}
99
100/// Errors from package install / download.
101#[derive(Debug, thiserror::Error)]
102pub enum ToolError {
103    /// Bottle lifecycle / registry.
104    #[error("{0}")]
105    Bottle(String),
106    /// I/O while creating dirs or writing the binary.
107    #[error("tool I/O: {0}")]
108    Io(#[from] io::Error),
109    /// `curl` / `tar` missing or failed.
110    #[error("{0}")]
111    Command(String),
112    /// Downloaded archive did not contain the expected binary.
113    #[error("expected binary not found in downloaded archive")]
114    MissingBinary,
115    /// Unknown package name.
116    #[error("unknown package `{0}` (known: 7zip, curl, xcode-tools)")]
117    UnknownPackage(String),
118}
119
120/// Host path of an installed package inside a bottle, if present.
121#[must_use]
122pub fn package_host_path(bottle: &Path, package: InstallPackage) -> PathBuf {
123    match package {
124        InstallPackage::SevenZip => bottle.join(GUEST_7ZZ_REL),
125        InstallPackage::Curl => bottle.join(GUEST_CURL_REL),
126        InstallPackage::XcodeTools => bottle.join(xcode_tools::GUEST_GIT_REL),
127    }
128}
129
130/// Discover Darwin `7zz` for convenience helpers (not required for `kh run`).
131///
132/// Order: explicit → `KAKEHASHI_7ZZ` → active bottle `/usr/local/bin/7zz` →
133/// legacy `/tmp/7zz` → dev-tree fallbacks.
134#[must_use]
135pub fn discover_7zz(explicit: Option<&Path>) -> Option<PathBuf> {
136    if let Some(p) = explicit {
137        if p.is_file() {
138            return Some(p.to_path_buf());
139        }
140        return None;
141    }
142
143    if let Ok(raw) = std::env::var(ENV_7ZZ) {
144        let p = PathBuf::from(raw);
145        if p.is_file() {
146            return Some(p);
147        }
148    }
149
150    if let Ok(Some(root)) = manage::active_root() {
151        let p = package_host_path(&root, InstallPackage::SevenZip);
152        if p.is_file() {
153            return Some(p);
154        }
155    }
156
157    let default = Path::new(DEFAULT_7ZZ_PATH);
158    if default.is_file() {
159        return Some(default.to_path_buf());
160    }
161
162    for rel in [
163        "tests/clang-probe/7zz.bin",
164        "tests/fixtures/7zz",
165        "tests/fixtures/bin/7zz",
166        "tests/clang-probe/7zz",
167    ] {
168        let p = PathBuf::from(rel);
169        if p.is_file() {
170            return Some(p);
171        }
172    }
173
174    None
175}
176
177/// Install a named package into the active bottle (creating the bottle if needed).
178pub fn install_package(name: &str) -> Result<InstallReport, ToolError> {
179    let package =
180        InstallPackage::parse(name).ok_or_else(|| ToolError::UnknownPackage(name.to_owned()))?;
181    match package {
182        InstallPackage::SevenZip => install_sevenzip(),
183        InstallPackage::Curl => install_curl(),
184        InstallPackage::XcodeTools => xcode_tools::install_xcode_tools(),
185    }
186}
187
188/// Result of a successful [`install_package`].
189#[derive(Debug, Clone)]
190pub struct InstallReport {
191    /// Package id.
192    pub package: &'static str,
193    /// Absolute host path of the installed binary.
194    pub host_path: PathBuf,
195    /// Guest absolute path (macOS layout).
196    pub guest_path: &'static str,
197    /// Bottle root used.
198    pub bottle: PathBuf,
199}
200
201fn ensure_active_bottle() -> Result<PathBuf, ToolError> {
202    if let Ok(Some(root)) = manage::active_root()
203        && is_bottle_root(&root)
204    {
205        return Ok(root);
206    }
207    let created = manage::ensure(&manage::CreateOptions {
208        path: None,
209        libsystem: None,
210        skip_libsystem: false,
211    })
212    .map_err(|e| ToolError::Bottle(e.to_string()))?;
213    Ok(created.path)
214}
215
216fn install_sevenzip() -> Result<InstallReport, ToolError> {
217    let bottle = ensure_active_bottle()?;
218    let dest = package_host_path(&bottle, InstallPackage::SevenZip);
219    if let Some(parent) = dest.parent() {
220        fs::create_dir_all(parent)?;
221    }
222
223    // Prefer env override (already a binary) over download.
224    if let Ok(raw) = std::env::var(ENV_7ZZ) {
225        let src = PathBuf::from(raw);
226        if src.is_file() {
227            fs::copy(&src, &dest)?;
228            set_executable(&dest)?;
229            return Ok(InstallReport {
230                package: InstallPackage::SevenZip.as_str(),
231                host_path: dest,
232                guest_path: InstallPackage::SevenZip.guest_path(),
233                bottle,
234            });
235        }
236    }
237
238    // Idempotent: bottle already has the binary (Docker re-run).
239    if !download_cache::force_download() && dest.is_file() {
240        return Ok(InstallReport {
241            package: InstallPackage::SevenZip.as_str(),
242            host_path: dest,
243            guest_path: InstallPackage::SevenZip.guest_path(),
244            bottle,
245        });
246    }
247
248    let archive =
249        download_cache::ensure_named_url(DARWIN_7ZZ_URL, CACHE_7ZZ_ARCHIVE).map_err(|e| {
250            ToolError::Command(e.to_string())
251        })?;
252
253    let tmp_root = download_cache::cache_dir()
254        .map_err(ToolError::Io)?
255        .join("tmp-extract-7zz");
256    drop(fs::remove_dir_all(&tmp_root));
257    fs::create_dir_all(&tmp_root)?;
258
259    let status = Command::new("tar")
260        .args(["-xJf"])
261        .arg(&archive)
262        .current_dir(&tmp_root)
263        .status()
264        .map_err(|e| ToolError::Command(format!("tar: {e}")))?;
265    if !status.success() {
266        drop(fs::remove_dir_all(&tmp_root));
267        return Err(ToolError::Command(format!(
268            "tar extract failed (status {status})"
269        )));
270    }
271
272    let found = find_named_file(&tmp_root, "7zz").ok_or(ToolError::MissingBinary)?;
273    if dest.exists() {
274        drop(fs::remove_file(&dest));
275    }
276    fs::copy(&found, &dest)?;
277    set_executable(&dest)?;
278    drop(fs::remove_dir_all(&tmp_root));
279
280    Ok(InstallReport {
281        package: InstallPackage::SevenZip.as_str(),
282        host_path: dest,
283        guest_path: InstallPackage::SevenZip.guest_path(),
284        bottle,
285    })
286}
287
288/// Install Darwin `curl` into the bottle at `/usr/local/bin/curl`.
289///
290/// Order: `KAKEHASHI_CURL` (already a binary) → download [`DARWIN_CURL_URL`]
291/// and extract the `curl` Mach-O from the tarball.
292fn install_curl() -> Result<InstallReport, ToolError> {
293    let bottle = ensure_active_bottle()?;
294    let dest = package_host_path(&bottle, InstallPackage::Curl);
295    if let Some(parent) = dest.parent() {
296        fs::create_dir_all(parent)?;
297    }
298
299    // Prefer env override (already a binary) over download.
300    if let Ok(raw) = std::env::var(ENV_CURL) {
301        let src = PathBuf::from(raw);
302        if src.is_file() {
303            if dest.exists() {
304                drop(fs::remove_file(&dest));
305            }
306            fs::copy(&src, &dest)?;
307            set_executable(&dest)?;
308            return Ok(InstallReport {
309                package: InstallPackage::Curl.as_str(),
310                host_path: dest,
311                guest_path: InstallPackage::Curl.guest_path(),
312                bottle,
313            });
314        }
315    }
316
317    // Idempotent: bottle already has the binary (Docker re-run).
318    if !download_cache::force_download() && dest.is_file() {
319        return Ok(InstallReport {
320            package: InstallPackage::Curl.as_str(),
321            host_path: dest,
322            guest_path: InstallPackage::Curl.guest_path(),
323            bottle,
324        });
325    }
326
327    let archive =
328        download_cache::ensure_named_url(DARWIN_CURL_URL, CACHE_CURL_ARCHIVE).map_err(|e| {
329            ToolError::Command(e.to_string())
330        })?;
331
332    let tmp_root = download_cache::cache_dir()
333        .map_err(ToolError::Io)?
334        .join("tmp-extract-curl");
335    drop(fs::remove_dir_all(&tmp_root));
336    fs::create_dir_all(&tmp_root)?;
337
338    let status = Command::new("tar")
339        .args(["-xJf"])
340        .arg(&archive)
341        .current_dir(&tmp_root)
342        .status()
343        .map_err(|e| ToolError::Command(format!("tar: {e}")))?;
344    if !status.success() {
345        drop(fs::remove_dir_all(&tmp_root));
346        return Err(ToolError::Command(format!(
347            "tar extract failed (status {status})"
348        )));
349    }
350
351    let found = find_named_file(&tmp_root, "curl").ok_or(ToolError::MissingBinary)?;
352    // Avoid copying the archive itself if it were ever named `curl`.
353    if found == archive {
354        drop(fs::remove_dir_all(&tmp_root));
355        return Err(ToolError::MissingBinary);
356    }
357    if dest.exists() {
358        drop(fs::remove_file(&dest));
359    }
360    fs::copy(&found, &dest)?;
361    set_executable(&dest)?;
362    drop(fs::remove_dir_all(&tmp_root));
363
364    Ok(InstallReport {
365        package: InstallPackage::Curl.as_str(),
366        host_path: dest,
367        guest_path: InstallPackage::Curl.guest_path(),
368        bottle,
369    })
370}
371
372/// Discover Darwin `curl` for convenience helpers.
373///
374/// Order: explicit → `KAKEHASHI_CURL` → active bottle `/usr/local/bin/curl`.
375#[must_use]
376pub fn discover_curl(explicit: Option<&Path>) -> Option<PathBuf> {
377    if let Some(p) = explicit {
378        if p.is_file() {
379            return Some(p.to_path_buf());
380        }
381        return None;
382    }
383
384    if let Ok(raw) = std::env::var(ENV_CURL) {
385        let p = PathBuf::from(raw);
386        if p.is_file() {
387            return Some(p);
388        }
389    }
390
391    if let Ok(Some(root)) = manage::active_root() {
392        let p = package_host_path(&root, InstallPackage::Curl);
393        if p.is_file() {
394            return Some(p);
395        }
396    }
397
398    None
399}
400
401fn set_executable(path: &Path) -> io::Result<()> {
402    #[cfg(unix)]
403    {
404        use std::os::unix::fs::PermissionsExt;
405        let mut perms = fs::metadata(path)?.permissions();
406        perms.set_mode(0o755);
407        fs::set_permissions(path, perms)?;
408    }
409    let _ = path;
410    Ok(())
411}
412
413fn find_named_file(root: &Path, name: &str) -> Option<PathBuf> {
414    let mut stack = vec![root.to_path_buf()];
415    while let Some(dir) = stack.pop() {
416        let entries = fs::read_dir(&dir).ok()?;
417        for ent in entries.flatten() {
418            let p = ent.path();
419            if p.is_dir() {
420                stack.push(p);
421            } else if p.file_name().is_some_and(|n| n == name) {
422                return Some(p);
423            }
424        }
425    }
426    None
427}
428
429/// Default guest `PATH` components (macOS-like) used when resolving bare names.
430pub const GUEST_PATH_DIRS: &[&str] = &[
431    "/usr/local/bin",
432    "/Library/Developer/CommandLineTools/usr/bin",
433    "/usr/bin",
434    "/bin",
435    "/usr/sbin",
436    "/sbin",
437];
438
439/// Resolve a program path for `kh run`.
440///
441/// * Absolute or relative with `/` → unchanged (host path or guest path string).
442/// * Bare name → search bottle under [`GUEST_PATH_DIRS`] (host files that exist).
443#[must_use]
444pub fn resolve_guest_program(spec: &Path, bottle: Option<&Path>) -> PathBuf {
445    let s = spec.as_os_str();
446    // Has path separator → user gave an explicit path.
447    if spec.components().count() > 1 || s.to_string_lossy().contains('/') {
448        return spec.to_path_buf();
449    }
450    let name = spec.file_name().unwrap_or(s);
451    let Some(root) = bottle else {
452        return spec.to_path_buf();
453    };
454    for dir in GUEST_PATH_DIRS {
455        // dir is "/usr/local/bin" → relative "usr/local/bin"
456        let rel = dir.trim_start_matches('/');
457        let candidate = root.join(rel).join(name);
458        if candidate.is_file() {
459            // Return guest absolute path so loader + path translation stay consistent.
460            return PathBuf::from(dir).join(name);
461        }
462    }
463    spec.to_path_buf()
464}
465
466/// Map guest absolute path to host under bottle (for opening the Mach-O file).
467#[must_use]
468pub fn guest_path_to_host(bottle: &Path, guest: &Path) -> PathBuf {
469    let g = guest.to_string_lossy();
470    if g.starts_with('/') {
471        bottle.join(g.trim_start_matches('/'))
472    } else {
473        guest.to_path_buf()
474    }
475}
476
477#[cfg(test)]
478#[allow(clippy::expect_used, clippy::panic, unsafe_code)]
479mod tests {
480    use super::*;
481    use std::sync::atomic::{AtomicU64, Ordering};
482
483    fn unique(prefix: &str) -> PathBuf {
484        static N: AtomicU64 = AtomicU64::new(0);
485        let n = N.fetch_add(1, Ordering::Relaxed);
486        std::env::temp_dir().join(format!("kh-7zz-{}-{}-{n}", prefix, std::process::id()))
487    }
488
489    #[test]
490    fn parse_package_names() {
491        assert_eq!(
492            InstallPackage::parse("7zip"),
493            Some(InstallPackage::SevenZip)
494        );
495        assert_eq!(InstallPackage::parse("7ZZ"), Some(InstallPackage::SevenZip));
496        assert_eq!(InstallPackage::parse("curl"), Some(InstallPackage::Curl));
497        assert_eq!(InstallPackage::parse("CURL"), Some(InstallPackage::Curl));
498        assert_eq!(
499            InstallPackage::parse("xcode-tools"),
500            Some(InstallPackage::XcodeTools)
501        );
502        assert_eq!(InstallPackage::parse("clt"), Some(InstallPackage::XcodeTools));
503        assert_eq!(InstallPackage::parse("git"), Some(InstallPackage::XcodeTools));
504        assert!(InstallPackage::parse("foo").is_none());
505    }
506
507    #[test]
508    fn resolve_bare_name_in_bottle() {
509        let root = unique("path");
510        let bin = root.join("usr/local/bin");
511        fs::create_dir_all(&bin).expect("dirs");
512        let tool = bin.join("7zz");
513        fs::write(&tool, b"x").expect("write");
514        let resolved = resolve_guest_program(Path::new("7zz"), Some(&root));
515        assert_eq!(resolved, PathBuf::from("/usr/local/bin/7zz"));
516        drop(fs::remove_dir_all(&root));
517    }
518
519    #[test]
520    fn discover_explicit_path() {
521        let path = unique("bin");
522        std::fs::write(&path, b"not-a-real-macho").expect("write");
523        let found = discover_7zz(Some(&path)).expect("explicit");
524        assert_eq!(found, path);
525        drop(std::fs::remove_file(&path));
526        assert!(discover_7zz(Some(&path)).is_none());
527    }
528
529    #[test]
530    fn find_nested_name() {
531        let root = unique("tree");
532        fs::create_dir_all(root.join("a/b")).expect("dirs");
533        let target = root.join("a/b/7zz");
534        fs::write(&target, b"x").expect("write");
535        assert_eq!(find_named_file(&root, "7zz"), Some(target));
536        drop(fs::remove_dir_all(&root));
537    }
538}