isothrum_machine/install/macos.rs
1//! Installs and removals on macOS: the vendors' own disk images and packages for the apps and the
2//! AWS CLI (Homebrew downloads the apps', the AWS CLI's comes from Amazon; then they are checked
3//! and installed as an administrator, with nothing left for the user to finish:
4//! `super::mac_image`), HashiCorp's signed package for VMware's utility, or Homebrew's formulae.
5//! A removal of what came from a vendor's package runs as its uninstaller does, through macOS's
6//! administrator prompt.
7//!
8//! A tool whose vendor ships a signed build installs from it rather than from a formula Homebrew
9//! may build here: on an Intel Mac Homebrew has no bottles any more (its Tier 3), so every formula
10//! builds from source there, which takes long and can fail (the AWS CLI's `aws-c-s3` did).
11//! Per tool:
12//!
13//! - Docker Desktop, Vagrant, VirtualBox, UTM: their vendor's disk image or package.
14//! - The AWS CLI: Amazon's package (`mac_image::AWS_CLI`), on both CPUs.
15//! - VMware's utility: HashiCorp's package.
16//! - Terraform: HashiCorp's tap, whose formula installs HashiCorp's own build (its checksum
17//! pinned): nothing is built on either CPU.
18//! - QEMU: Homebrew's formula, as no vendor ships a macOS build. An Intel Mac builds it from
19//! source, which its step says ([`Note::BuildsFromSource`]); a failed build fails the install.
20//! - The Azure CLI, the Google Cloud CLI: Homebrew's casks of their vendor's builds (their only
21//! macOS ones). Their Python is a formula, built from source on an Intel Mac that lacks it.
22
23use crate::context::Context;
24use crate::host::{Arch, HostOs, Packages};
25use crate::install::steps::{Note, Step, step};
26use crate::install::{Dependency, Elevation, Refusal, mac_image, vmware_utility};
27
28/// Homebrew's path, when the host has it; why not, as `refusal` says, else.
29fn homebrew(packages: Option<Packages>, refusal: Refusal) -> Result<&'static str, Refusal> {
30 match packages {
31 Some(Packages::Homebrew(brew)) => Ok(brew),
32 _ => Err(refusal),
33 }
34}
35
36/// A step that runs `script` with `sh -c`, `note` said before it.
37fn sh(script: &str, note: Note) -> Step {
38 let mut step = step("sh", &["-c", script]);
39 step.note = Some(note);
40 step
41}
42
43/// The install of `dep` on macOS: Homebrew's formulae, or a vendor's disk image or package
44/// (Homebrew downloads it), installed as an administrator `elevation`'s way (macOS's password
45/// prompt, else `sudo -n`); VMware's utility from HashiCorp's own package, on this Mac's CPU
46/// `arch`.
47///
48/// # Errors
49///
50/// [`Refusal::NotHere`] for what doesn't run on macOS, [`Refusal::NoHomebrew`] without Homebrew.
51pub fn install(dep: Dependency, packages: Option<Packages>, arch: Arch, elevation: Elevation) -> Result<Vec<Step>, Refusal> {
52 dep.runs_here(HostOs::Macos)?;
53 // The vendors' own packages, downloaded from them: need no Homebrew.
54 match dep {
55 Dependency::VmwareUtility => return Ok(vec![vmware_utility::mac_install(arch, elevation)]),
56 Dependency::Awscli => return Ok(vec![mac_image::install(None, dep, &mac_image::AWS_CLI, elevation)?]),
57 _ => {}
58 }
59 let brew = homebrew(packages, Refusal::NoHomebrew)?;
60 let vendor = |vendor: &mac_image::Vendor| mac_image::install(Some(brew), dep, vendor, elevation).map(|step| vec![step]);
61 Ok(match dep {
62 // The apps and Vagrant: their vendor's disk image or package, as an administrator (Docker
63 // Desktop's brings the docker CLI and Compose).
64 Dependency::Docker => vendor(&mac_image::DOCKER)?,
65 Dependency::Vagrant => vendor(&mac_image::VAGRANT)?,
66 Dependency::Virtualbox => vendor(&mac_image::VIRTUALBOX)?,
67 Dependency::Utm => vendor(&mac_image::UTM)?,
68 // A formula (no administrator); its tap's full name since core dropped it.
69 Dependency::Terraform => vec![step(brew, &["install", "hashicorp/tap/terraform"])],
70 // A formula. Homebrew is updated first so an outdated one learns this macOS (it otherwise
71 // refuses every install with "unknown or unsupported macOS version: :dunno"), but that
72 // update never blocks the install: it runs best-effort, then the install with auto-update
73 // off. A real problem (an outdated Homebrew or Xcode, a root-owned lock) surfaces from the
74 // install as `StepFailed::Homebrew`. On an Intel Mac, which Homebrew has no bottles for,
75 // it builds from source: its note says so.
76 Dependency::Qemu => vec![sh(
77 &format!("'{brew}' update || echo 'Homebrew was not updated; continuing with the install.'\nHOMEBREW_NO_AUTO_UPDATE=1 '{brew}' install qemu"),
78 match arch {
79 Arch::Amd64 => Note::BuildsFromSource(dep),
80 Arch::Arm64 => Note::QemuUpdatingHomebrewFirst,
81 },
82 )],
83 Dependency::Libvirt | Dependency::Wsl | Dependency::Hyperv | Dependency::VmwareUtility | Dependency::Awscli => {
84 return Err(Refusal::NotHere {
85 dependency: dep,
86 os: HostOs::Macos,
87 });
88 }
89 // Microsoft's prebuilt cask instead of the `azure-cli` formula: on recent macOS the
90 // formula has no bottle and builds its whole tree (llvm, rust) from source, which takes
91 // about an hour. The cask is a signed download; its third-party tap needs trusting.
92 Dependency::Azurecli => {
93 let mut cask = step(brew, &["install", "--cask", "azure-cli-preview"]);
94 cask.note = Some(Note::AzureCliCask);
95 vec![
96 step(brew, &["tap", "azure/azure-cli"]),
97 // `brew trust` exists from Homebrew 7 only; an older Homebrew needs no trust and
98 // must not fail here ("Unknown command"). On 7, an untrusted tap still fails at
99 // the install step with Homebrew's own message.
100 sh(&format!("'{brew}' trust azure/azure-cli 2>/dev/null || true"), Note::TrustingAzureTap),
101 cask,
102 ]
103 }
104 Dependency::Gcloud => vec![step(brew, &["install", "--cask", "google-cloud-sdk"])],
105 })
106}
107
108/// A shell script run with macOS's administrator prompt (the same dialog an installer shows).
109fn admin(script: &str, dep: Dependency, name: &str) -> Step {
110 let quoted = |text: &str| text.replace('\\', "\\\\").replace('"', "\\\"");
111 let prompt = quoted(&mac_image::admin_prompt(&format!("remove {name}"), "remove it"));
112 let mut step = step(
113 "osascript",
114 &[
115 "-e",
116 &format!("do shell script \"{}\" with prompt \"{prompt}\" with administrator privileges", quoted(script)),
117 ],
118 );
119 step.note = Some(Note::Removing(dep));
120 step
121}
122
123/// VirtualBox's own uninstaller, run as an administrator, only ever from the installer disk image
124/// Homebrew downloaded (`image`, attached here, then detached). Never from whatever volume happens
125/// to be mounted as `/Volumes/VirtualBox*`: anyone can mount a disk image with that name and a
126/// `VirtualBox_Uninstall.tool` of their own, which would then run as root.
127fn virtualbox_uninstall(image: &str) -> String {
128 format!(
129 "m=$(hdiutil attach -nobrowse -noautoopen '{image}' | awk -F'\\t' '/\\/Volumes\\//{{print $NF; exit}}'); [ -n \"$m\" ] || exit 3; \
130 \"$m/VirtualBox_Uninstall.tool\" --unattended; s=$?; hdiutil detach -quiet \"$m\"; exit $s"
131 )
132}
133
134/// The macOS removal of HashiCorp's VMware utility, as the package's own `uninstall.tool` does it:
135/// the service, then its folder.
136const VMWARE_UTILITY_REMOVAL: &str = "/opt/vagrant-vmware-desktop/bin/vagrant-vmware-utility service uninstall; rm -rf /opt/vagrant-vmware-desktop && (pkgutil --forget com.vagrant.vagrant-vmware-utility || true)";
137
138/// The macOS removal of the AWS CLI Amazon's package installed, as Amazon's guide has it: its
139/// folder, and its links in `/usr/local/bin` only where they point into it (never another `aws`),
140/// then the package's receipt.
141const AWS_CLI_REMOVAL: &str = "for l in /usr/local/bin/aws /usr/local/bin/aws_completer; do case \"$(readlink \"$l\")\" in /usr/local/aws-cli/*) rm -f \"$l\" ;; esac; done; rm -rf /usr/local/aws-cli && (pkgutil --forget com.amazon.aws.cli2 || true)";
142
143/// The removal of `dep` on macOS: Homebrew's own packages, or the vendor's uninstaller. Only
144/// Homebrew's packages (and VirtualBox's installer image, which Homebrew keeps:
145/// [`virtualbox_image`]) need Homebrew: a tool installed from its vendor's package is removed
146/// without it.
147///
148/// # Errors
149///
150/// [`Refusal::NotHere`], [`Refusal::HomebrewNeeded`], or [`Refusal::NoVirtualboxImage`] for
151/// VirtualBox without its installer image.
152pub fn uninstall(dep: Dependency, packages: Option<Packages>, virtualbox: Option<&str>) -> Result<Vec<Step>, Refusal> {
153 let brew = || homebrew(packages, Refusal::HomebrewNeeded);
154 Ok(match dep {
155 Dependency::Terraform => vec![step(brew()?, &["uninstall", "hashicorp/tap/terraform"])],
156 Dependency::Qemu => vec![step(brew()?, &["uninstall", "qemu"])],
157 Dependency::Awscli => vec![admin(AWS_CLI_REMOVAL, dep, "the AWS CLI")],
158 Dependency::Gcloud => vec![step(brew()?, &["uninstall", "--cask", "google-cloud-sdk"])],
159 Dependency::Azurecli => vec![step(brew()?, &["uninstall", "--cask", "azure-cli-preview"])],
160 // Installed from the vendors' own packages: removed the way their uninstallers do.
161 Dependency::Vagrant => vec![admin(
162 "rm -rf /opt/vagrant /usr/local/bin/vagrant && pkgutil --forget com.vagrant.vagrant || true",
163 dep,
164 "Vagrant",
165 )],
166 Dependency::Virtualbox => {
167 brew()?;
168 let image = virtualbox.ok_or(Refusal::NoVirtualboxImage)?;
169 vec![admin(&virtualbox_uninstall(image), dep, "VirtualBox")]
170 }
171 Dependency::Docker => {
172 let mut uninstaller = step("/Applications/Docker.app/Contents/MacOS/uninstall", &[]);
173 uninstaller.note = Some(Note::Removing(dep));
174 vec![uninstaller]
175 }
176 Dependency::Utm => vec![step(
177 "osascript",
178 &["-e", "tell application \"Finder\" to delete POSIX file \"/Applications/UTM.app\""],
179 )],
180 Dependency::VmwareUtility => vec![admin(VMWARE_UTILITY_REMOVAL, dep, "the Vagrant VMware Utility")],
181 Dependency::Libvirt | Dependency::Wsl | Dependency::Hyperv => {
182 return Err(Refusal::NotHere {
183 dependency: dep,
184 os: HostOs::Macos,
185 });
186 }
187 })
188}
189
190/// Why VirtualBox's installer image can't be had.
191#[derive(Debug, Clone, PartialEq, Eq)]
192#[non_exhaustive]
193pub enum ImageMissing {
194 /// Homebrew didn't say where it is (or named no `.dmg` a script can quote).
195 Unsaid,
196 /// Homebrew named this path, and nothing is there.
197 NotThere(String),
198 /// Homebrew's `fetch` or `--cache` failed: why.
199 Failed(super::StepFailed),
200}
201
202/// The VirtualBox installer image, from `brew --cache --cask virtualbox`'s output: a `.dmg` path
203/// the administrator's script can quote.
204fn virtualbox_image_from(out: &str) -> Option<String> {
205 let path = out.trim();
206 // Homebrew names it `….dmg`, in lower case: anything else isn't its installer image.
207 let is_dmg = std::path::Path::new(path).extension().is_some_and(|e| e == "dmg");
208 (!path.is_empty() && is_dmg && !path.contains(['\'', '"', '\n'])).then(|| path.to_owned())
209}
210
211/// The VirtualBox installer image Homebrew (`brew`) has, fetched again first as the user: Homebrew
212/// drops the download once the cask moves on, which it does often. Run before the administrator's
213/// step: as root, `~` isn't the user's home.
214///
215/// # Errors
216///
217/// [`ImageMissing`]: why there is none.
218pub async fn virtualbox_image(cx: &Context, brew: &str, on_line: &mut (dyn FnMut(&str) + Send)) -> Result<String, ImageMissing> {
219 super::run_steps(cx, &[step(brew, &["fetch", "--cask", "virtualbox"])], on_line)
220 .await
221 .map_err(ImageMissing::Failed)?;
222 let out = cx
223 .read_ok(brew, &["--cache", "--cask", "virtualbox"])
224 .await
225 .map_err(|why| ImageMissing::Failed(super::StepFailed::NotStarted(why)))?;
226 let image = virtualbox_image_from(&out).ok_or(ImageMissing::Unsaid)?;
227 if !std::path::Path::new(&image).is_file() {
228 return Err(ImageMissing::NotThere(image));
229 }
230 Ok(image)
231}
232
233#[cfg(test)]
234mod tests;