Skip to main content

byob_exec/env/
system.rs

1//! The last resort: installing system-wide with Homebrew (macOS, Linuxbrew) or winget
2//! (Windows), through `install_system_packages`. Never the default — it changes the
3//! machine for every program and user, outside the workspace, and byob can't undo it —
4//! so a person must approve every call (no grant or `--auto-approve` does), and only for
5//! packages the workspace installer (Nix, pixi) couldn't provide, or where there is none.
6//!
7//! It runs outside the sandbox: Homebrew writes its prefix (`/opt/homebrew`,
8//! `/home/linuxbrew/.linuxbrew`) and winget runs installers that may ask for elevation.
9
10use byob_types::process::NoWindow as _;
11use std::ffi::OsString;
12use std::path::{Path, PathBuf};
13use std::process::Command;
14use std::time::Duration;
15
16use byob_sandbox::{Outcome, RunOptions};
17
18use super::Layer;
19
20const TIMEOUT: Duration = Duration::from_secs(1800);
21const MAX_OUTPUT: usize = 16 * 1024;
22
23#[derive(Debug, Clone, Copy, PartialEq, Eq)]
24pub enum Kind {
25    Brew,
26    Winget,
27}
28
29/// Homebrew or winget on this machine.
30#[derive(Debug, Clone, PartialEq, Eq)]
31pub struct SystemInstaller {
32    pub kind: Kind,
33    pub program: PathBuf,
34}
35
36impl SystemInstaller {
37    /// `winget` on Windows; elsewhere `brew` on `PATH` or in its usual places (a GUI app
38    /// on macOS often starts without `/opt/homebrew/bin` on `PATH`).
39    pub fn detect() -> Option<Self> {
40        if cfg!(windows) {
41            return byob_sandbox::which("winget".as_ref()).map(|program| Self { kind: Kind::Winget, program });
42        }
43        byob_sandbox::which("brew".as_ref())
44            .or_else(|| {
45                ["/opt/homebrew/bin/brew", "/usr/local/bin/brew", "/home/linuxbrew/.linuxbrew/bin/brew"].into_iter().map(PathBuf::from).find(|p| p.is_file())
46            })
47            .map(|program| Self { kind: Kind::Brew, program })
48    }
49
50    pub fn name(&self) -> &'static str {
51        match self.kind {
52            Kind::Brew => "Homebrew",
53            Kind::Winget => "winget",
54        }
55    }
56
57    /// The warning on the approval card.
58    pub fn warning(&self, packages: &[String]) -> String {
59        let list = packages.join(" ");
60        match self.kind {
61            Kind::Brew => format!(
62                "Installs SYSTEM-WIDE with Homebrew, outside the workspace: it changes {} for every program and user on this computer, \
63                 runs without byob's sandbox, and byob can't undo it (remove it later with `brew uninstall {list}`).",
64                self.prefix().map_or_else(|| "Homebrew's folder".to_owned(), |p| p.display().to_string())
65            ),
66            Kind::Winget => format!(
67                "Installs SYSTEM-WIDE with winget, outside the workspace: installers run without byob's sandbox, may ask for \
68                 administrator rights, and byob can't undo it (remove it later with `winget uninstall {list}`)."
69            ),
70        }
71    }
72
73    /// Homebrew's prefix: the folder above `bin/brew`.
74    fn prefix(&self) -> Option<PathBuf> {
75        let bin = self.program.parent()?;
76        (bin.file_name()? == "bin").then(|| bin.parent().map(Path::to_path_buf)).flatten()
77    }
78
79    /// What sandboxed runs need to find what it installed: Homebrew's `bin` on `PATH`.
80    pub fn layer(&self) -> Layer {
81        match (self.kind, self.prefix()) {
82            (Kind::Brew, Some(prefix)) => Layer { path: vec![prefix.join("bin")], read: vec![prefix], ..Default::default() },
83            _ => Layer::default(),
84        }
85    }
86
87    /// The command lines that install `packages` (winget takes one package per call).
88    pub fn commands(&self, packages: &[String]) -> Vec<Vec<OsString>> {
89        match self.kind {
90            Kind::Brew => {
91                let mut args: Vec<OsString> = vec!["install".into()];
92                args.extend(packages.iter().map(OsString::from));
93                vec![args]
94            }
95            Kind::Winget => packages
96                .iter()
97                .map(|p| {
98                    ["install", "--exact", "--accept-package-agreements", "--accept-source-agreements", "--disable-interactivity"]
99                        .into_iter()
100                        .map(OsString::from)
101                        .chain([OsString::from(p)])
102                        .collect()
103                })
104                .collect(),
105        }
106    }
107
108    /// Install `packages` (names checked with [`valid_name`]), stopping when `cancelled`.
109    pub fn install(&self, packages: &[String], cancelled: &dyn Fn() -> bool) -> Result<String, String> {
110        if let Some(bad) = packages.iter().find(|p| !valid_name(p)) {
111            return Err(format!("{bad:?} is not a package name"));
112        }
113        let mut log = String::new();
114        for args in self.commands(packages) {
115            let mut cmd = Command::new(&self.program);
116            cmd.no_window();
117            cmd.args(&args);
118            if self.kind == Kind::Brew {
119                cmd.env("NONINTERACTIVE", "1").env("HOMEBREW_NO_ENV_HINTS", "1").env("HOMEBREW_NO_AUTO_UPDATE", "1");
120            }
121            let opts = RunOptions { timeout: TIMEOUT, max_output: MAX_OUTPUT, ..Default::default() };
122            let out: Outcome = byob_sandbox::run(cmd, &opts, cancelled)?;
123            let text = [out.stdout.text(), out.stderr.text()].iter().map(|s| s.trim().to_owned()).filter(|s| !s.is_empty()).collect::<Vec<_>>().join("\n");
124            if out.cancelled {
125                return Err(super::STOPPED.into());
126            }
127            if !out.success() {
128                return Err(format!("`{} {}` failed:\n{text}", self.kind_cmd(), args.iter().map(|a| a.to_string_lossy()).collect::<Vec<_>>().join(" ")));
129            }
130            log.push_str(&text);
131            log.push('\n');
132        }
133        let after = match self.kind {
134            Kind::Brew => "They are on PATH for run_command now.",
135            Kind::Winget => "Programs installed this way may only be on PATH after byob restarts.",
136        };
137        Ok(format!("Installed system-wide with {}: {}. {after}\n{}", self.name(), packages.join(", "), log.trim_end()))
138    }
139
140    fn kind_cmd(&self) -> &'static str {
141        match self.kind {
142            Kind::Brew => "brew",
143            Kind::Winget => "winget",
144        }
145    }
146}
147
148/// A package name or id (`jq`, `ffmpeg@6`, `Git.Git`, `homebrew/cask/foo`): no options,
149/// no spaces, nothing a shell would interpret.
150pub fn valid_name(p: &str) -> bool {
151    !p.is_empty() && p.len() <= 100 && !p.starts_with('-') && p.chars().all(|c| c.is_ascii_alphanumeric() || "._+@/-".contains(c))
152}
153
154#[cfg(test)]
155mod tests {
156    use super::*;
157
158    #[test]
159    fn names_commands_and_warnings() {
160        assert!(valid_name("jq") && valid_name("ffmpeg@6") && valid_name("Git.Git") && valid_name("homebrew/cask/firefox"));
161        assert!(!valid_name("--force") && !valid_name("a b") && !valid_name("x;rm") && !valid_name(""));
162        let brew = SystemInstaller { kind: Kind::Brew, program: "/opt/homebrew/bin/brew".into() };
163        assert_eq!(brew.commands(&["jq".into(), "rg".into()]), vec![vec![OsString::from("install"), "jq".into(), "rg".into()]]);
164        let w = brew.warning(&["jq".into()]);
165        assert!(w.contains("SYSTEM-WIDE") && w.contains("/opt/homebrew") && w.contains("brew uninstall jq"), "{w}");
166        assert_eq!(brew.layer().path, vec![PathBuf::from("/opt/homebrew/bin")]);
167        let winget = SystemInstaller { kind: Kind::Winget, program: "winget".into() };
168        let cmds = winget.commands(&["jqlang.jq".into(), "Git.Git".into()]);
169        assert_eq!(cmds.len(), 2);
170        assert_eq!(cmds[1].last(), Some(&OsString::from("Git.Git")));
171        assert!(winget.warning(&["x".into()]).contains("winget uninstall x"));
172        assert!(winget.layer().is_empty());
173    }
174}