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