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
7use std::fs;
8use std::io;
9use std::path::{Path, PathBuf};
10use std::process::Command;
11
12use super::layout::is_bottle_root;
13use super::manage;
14use super::registry;
15
16/// Env override: host path of a Darwin `7zz` binary (skip download).
17pub const ENV_7ZZ: &str = "KAKEHASHI_7ZZ";
18
19/// Legacy ad-hoc drop location (still checked by discovery helpers).
20pub const DEFAULT_7ZZ_PATH: &str = "/tmp/7zz";
21
22/// Official macOS console 7-Zip (universal arm64 / x86_64 Mach-O).
23pub const DARWIN_7ZZ_URL: &str =
24    "https://github.com/ip7z/7zip/releases/download/26.02/7z2602-mac.tar.xz";
25
26/// Guest-relative install path for Darwin 7zz (under bottle root).
27///
28/// On a real Mac this is `/usr/local/bin/7zz`.
29pub const GUEST_7ZZ_REL: &str = "usr/local/bin/7zz";
30
31/// Known installable package ids (`kh install <name>`).
32#[derive(Debug, Clone, Copy, PartialEq, Eq)]
33pub enum InstallPackage {
34    /// Darwin 7-Zip console (`7zz`).
35    SevenZip,
36}
37
38impl InstallPackage {
39    /// Parse CLI package name (case-insensitive).
40    #[must_use]
41    pub fn parse(name: &str) -> Option<Self> {
42        match name.to_ascii_lowercase().as_str() {
43            "7zip" | "7zz" | "sevenzip" | "p7zip" => Some(Self::SevenZip),
44            _ => None,
45        }
46    }
47
48    /// Canonical name for messages.
49    #[must_use]
50    pub const fn as_str(self) -> &'static str {
51        match self {
52            Self::SevenZip => "7zip",
53        }
54    }
55
56    /// Guest absolute path after install (with leading `/`).
57    #[must_use]
58    pub const fn guest_path(self) -> &'static str {
59        match self {
60            Self::SevenZip => "/usr/local/bin/7zz",
61        }
62    }
63}
64
65/// Errors from package install / download.
66#[derive(Debug, thiserror::Error)]
67pub enum ToolError {
68    /// Bottle lifecycle / registry.
69    #[error("{0}")]
70    Bottle(String),
71    /// I/O while creating dirs or writing the binary.
72    #[error("tool I/O: {0}")]
73    Io(#[from] io::Error),
74    /// `curl` / `tar` missing or failed.
75    #[error("{0}")]
76    Command(String),
77    /// Downloaded archive did not contain the expected binary.
78    #[error("expected binary not found in downloaded archive")]
79    MissingBinary,
80    /// Unknown package name.
81    #[error("unknown package `{0}` (known: 7zip)")]
82    UnknownPackage(String),
83}
84
85/// Host path of an installed package inside a bottle, if present.
86#[must_use]
87pub fn package_host_path(bottle: &Path, package: InstallPackage) -> PathBuf {
88    match package {
89        InstallPackage::SevenZip => bottle.join(GUEST_7ZZ_REL),
90    }
91}
92
93/// Discover Darwin `7zz` for convenience helpers (not required for `kh run`).
94///
95/// Order: explicit → `KAKEHASHI_7ZZ` → active bottle `/usr/local/bin/7zz` →
96/// legacy `/tmp/7zz` → dev-tree fallbacks.
97#[must_use]
98pub fn discover_7zz(explicit: Option<&Path>) -> Option<PathBuf> {
99    if let Some(p) = explicit {
100        if p.is_file() {
101            return Some(p.to_path_buf());
102        }
103        return None;
104    }
105
106    if let Ok(raw) = std::env::var(ENV_7ZZ) {
107        let p = PathBuf::from(raw);
108        if p.is_file() {
109            return Some(p);
110        }
111    }
112
113    if let Ok(Some(root)) = manage::active_root() {
114        let p = package_host_path(&root, InstallPackage::SevenZip);
115        if p.is_file() {
116            return Some(p);
117        }
118    }
119
120    let default = Path::new(DEFAULT_7ZZ_PATH);
121    if default.is_file() {
122        return Some(default.to_path_buf());
123    }
124
125    for rel in [
126        "tests/clang-probe/7zz.bin",
127        "tests/fixtures/7zz",
128        "tests/fixtures/bin/7zz",
129        "tests/clang-probe/7zz",
130    ] {
131        let p = PathBuf::from(rel);
132        if p.is_file() {
133            return Some(p);
134        }
135    }
136
137    None
138}
139
140/// Install a named package into the active bottle (creating the bottle if needed).
141pub fn install_package(name: &str) -> Result<InstallReport, ToolError> {
142    let package =
143        InstallPackage::parse(name).ok_or_else(|| ToolError::UnknownPackage(name.to_owned()))?;
144    match package {
145        InstallPackage::SevenZip => install_sevenzip(),
146    }
147}
148
149/// Result of a successful [`install_package`].
150#[derive(Debug, Clone)]
151pub struct InstallReport {
152    /// Package id.
153    pub package: &'static str,
154    /// Absolute host path of the installed binary.
155    pub host_path: PathBuf,
156    /// Guest absolute path (macOS layout).
157    pub guest_path: &'static str,
158    /// Bottle root used.
159    pub bottle: PathBuf,
160}
161
162fn ensure_active_bottle() -> Result<PathBuf, ToolError> {
163    if let Ok(Some(root)) = manage::active_root()
164        && is_bottle_root(&root)
165    {
166        return Ok(root);
167    }
168    let created = manage::ensure(&manage::CreateOptions {
169        path: None,
170        libsystem: None,
171        skip_libsystem: false,
172    })
173    .map_err(|e| ToolError::Bottle(e.to_string()))?;
174    Ok(created.path)
175}
176
177fn install_sevenzip() -> Result<InstallReport, ToolError> {
178    let bottle = ensure_active_bottle()?;
179    let dest = package_host_path(&bottle, InstallPackage::SevenZip);
180    if let Some(parent) = dest.parent() {
181        fs::create_dir_all(parent)?;
182    }
183
184    // Prefer env override (already a binary) over download.
185    if let Ok(raw) = std::env::var(ENV_7ZZ) {
186        let src = PathBuf::from(raw);
187        if src.is_file() {
188            fs::copy(&src, &dest)?;
189            set_executable(&dest)?;
190            return Ok(InstallReport {
191                package: InstallPackage::SevenZip.as_str(),
192                host_path: dest,
193                guest_path: InstallPackage::SevenZip.guest_path(),
194                bottle,
195            });
196        }
197    }
198
199    let tmp_root = registry::data_dir()?.join(".kh-dl");
200    drop(fs::remove_dir_all(&tmp_root));
201    fs::create_dir_all(&tmp_root)?;
202    let archive = tmp_root.join("7z-mac.tar.xz");
203    download_url(DARWIN_7ZZ_URL, &archive)?;
204
205    let status = Command::new("tar")
206        .args(["-xJf"])
207        .arg(&archive)
208        .current_dir(&tmp_root)
209        .status()
210        .map_err(|e| ToolError::Command(format!("tar: {e}")))?;
211    if !status.success() {
212        drop(fs::remove_dir_all(&tmp_root));
213        return Err(ToolError::Command(format!(
214            "tar extract failed (status {status})"
215        )));
216    }
217
218    let found = find_named_file(&tmp_root, "7zz").ok_or(ToolError::MissingBinary)?;
219    if dest.exists() {
220        drop(fs::remove_file(&dest));
221    }
222    fs::copy(&found, &dest)?;
223    set_executable(&dest)?;
224    drop(fs::remove_dir_all(&tmp_root));
225
226    Ok(InstallReport {
227        package: InstallPackage::SevenZip.as_str(),
228        host_path: dest,
229        guest_path: InstallPackage::SevenZip.guest_path(),
230        bottle,
231    })
232}
233
234fn set_executable(path: &Path) -> io::Result<()> {
235    #[cfg(unix)]
236    {
237        use std::os::unix::fs::PermissionsExt;
238        let mut perms = fs::metadata(path)?.permissions();
239        perms.set_mode(0o755);
240        fs::set_permissions(path, perms)?;
241    }
242    let _ = path;
243    Ok(())
244}
245
246fn download_url(url: &str, dest: &Path) -> Result<(), ToolError> {
247    let curl = Command::new("curl")
248        .args(["-fsSL", "--retry", "3", "-o"])
249        .arg(dest)
250        .arg(url)
251        .status();
252    match curl {
253        Ok(st) if st.success() => return Ok(()),
254        Ok(_) | Err(_) => {}
255    }
256    let wget = Command::new("wget")
257        .args(["-q", "-O"])
258        .arg(dest)
259        .arg(url)
260        .status()
261        .map_err(|e| {
262            ToolError::Command(format!(
263                "download failed: need curl or wget ({e}); url={url}"
264            ))
265        })?;
266    if !wget.success() {
267        return Err(ToolError::Command(format!(
268            "download failed (curl/wget); url={url}"
269        )));
270    }
271    Ok(())
272}
273
274fn find_named_file(root: &Path, name: &str) -> Option<PathBuf> {
275    let mut stack = vec![root.to_path_buf()];
276    while let Some(dir) = stack.pop() {
277        let entries = fs::read_dir(&dir).ok()?;
278        for ent in entries.flatten() {
279            let p = ent.path();
280            if p.is_dir() {
281                stack.push(p);
282            } else if p.file_name().is_some_and(|n| n == name) {
283                return Some(p);
284            }
285        }
286    }
287    None
288}
289
290/// Default guest `PATH` components (macOS-like) used when resolving bare names.
291pub const GUEST_PATH_DIRS: &[&str] = &["/usr/local/bin", "/usr/bin", "/bin", "/usr/sbin", "/sbin"];
292
293/// Resolve a program path for `kh run`.
294///
295/// * Absolute or relative with `/` → unchanged (host path or guest path string).
296/// * Bare name → search bottle under [`GUEST_PATH_DIRS`] (host files that exist).
297#[must_use]
298pub fn resolve_guest_program(spec: &Path, bottle: Option<&Path>) -> PathBuf {
299    let s = spec.as_os_str();
300    // Has path separator → user gave an explicit path.
301    if spec.components().count() > 1 || s.to_string_lossy().contains('/') {
302        return spec.to_path_buf();
303    }
304    let name = spec.file_name().unwrap_or(s);
305    let Some(root) = bottle else {
306        return spec.to_path_buf();
307    };
308    for dir in GUEST_PATH_DIRS {
309        // dir is "/usr/local/bin" → relative "usr/local/bin"
310        let rel = dir.trim_start_matches('/');
311        let candidate = root.join(rel).join(name);
312        if candidate.is_file() {
313            // Return guest absolute path so loader + path translation stay consistent.
314            return PathBuf::from(dir).join(name);
315        }
316    }
317    spec.to_path_buf()
318}
319
320/// Map guest absolute path to host under bottle (for opening the Mach-O file).
321#[must_use]
322pub fn guest_path_to_host(bottle: &Path, guest: &Path) -> PathBuf {
323    let g = guest.to_string_lossy();
324    if g.starts_with('/') {
325        bottle.join(g.trim_start_matches('/'))
326    } else {
327        guest.to_path_buf()
328    }
329}
330
331#[cfg(test)]
332#[allow(clippy::expect_used, clippy::panic, unsafe_code)]
333mod tests {
334    use super::*;
335    use std::sync::atomic::{AtomicU64, Ordering};
336
337    fn unique(prefix: &str) -> PathBuf {
338        static N: AtomicU64 = AtomicU64::new(0);
339        let n = N.fetch_add(1, Ordering::Relaxed);
340        std::env::temp_dir().join(format!("kh-7zz-{}-{}-{n}", prefix, std::process::id()))
341    }
342
343    #[test]
344    fn parse_package_names() {
345        assert_eq!(
346            InstallPackage::parse("7zip"),
347            Some(InstallPackage::SevenZip)
348        );
349        assert_eq!(InstallPackage::parse("7ZZ"), Some(InstallPackage::SevenZip));
350        assert!(InstallPackage::parse("foo").is_none());
351    }
352
353    #[test]
354    fn resolve_bare_name_in_bottle() {
355        let root = unique("path");
356        let bin = root.join("usr/local/bin");
357        fs::create_dir_all(&bin).expect("dirs");
358        let tool = bin.join("7zz");
359        fs::write(&tool, b"x").expect("write");
360        let resolved = resolve_guest_program(Path::new("7zz"), Some(&root));
361        assert_eq!(resolved, PathBuf::from("/usr/local/bin/7zz"));
362        drop(fs::remove_dir_all(&root));
363    }
364
365    #[test]
366    fn discover_explicit_path() {
367        let path = unique("bin");
368        std::fs::write(&path, b"not-a-real-macho").expect("write");
369        let found = discover_7zz(Some(&path)).expect("explicit");
370        assert_eq!(found, path);
371        drop(std::fs::remove_file(&path));
372        assert!(discover_7zz(Some(&path)).is_none());
373    }
374
375    #[test]
376    fn find_nested_name() {
377        let root = unique("tree");
378        fs::create_dir_all(root.join("a/b")).expect("dirs");
379        let target = root.join("a/b/7zz");
380        fs::write(&target, b"x").expect("write");
381        assert_eq!(find_named_file(&root, "7zz"), Some(target));
382        drop(fs::remove_dir_all(&root));
383    }
384}