use serde::{Deserialize, Serialize};
use crate::context::Context;
use crate::host::{ALL_OSES, Arch, HostOs};
use crate::providers::{Provider, ProviderRow};
pub mod added;
pub mod brew;
pub mod exit_codes;
pub mod interaction;
pub mod linux;
pub(crate) mod mac_image;
pub mod macos;
mod pkexec;
pub mod record;
pub mod root;
mod steps;
mod vmware_utility;
pub mod windows;
pub use added::{Before, Installed, Item, before, items, there};
pub use interaction::{BROADCOM_DOWNLOADS, Interaction, OVFTOOL_PAGE, Prompt, VMWARE_FUSION_PAGE, VMWARE_WORKSTATION_PAGE, VendorPage, interactions};
pub use mac_image::set_app_name;
pub use steps::{Agreement, NotServed, Note, Step, StepFailed, command_line, run_step, run_steps, step};
#[derive(Deserialize, Serialize, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
#[cfg_attr(any(test, feature = "ts-rs"), derive(ts_rs::TS))]
#[serde(rename_all = "lowercase")]
pub enum Dependency {
Docker,
Vagrant,
Terraform,
Virtualbox,
Qemu,
Utm,
Libvirt,
Awscli,
Azurecli,
Gcloud,
Wsl,
#[serde(rename = "vmware-utility")]
VmwareUtility,
Hyperv,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Runs {
On(&'static [HostOs]),
As(Provider),
}
pub type Probe = (&'static str, &'static [&'static str]);
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub struct ToolRow {
pub runs: Runs,
pub probe: Option<Probe>,
pub mac_app: Option<&'static str>,
pub winget: Option<&'static str>,
pub own_url: Option<&'static str>,
pub no_build: &'static [NoBuild],
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct NoBuild {
pub os: HostOs,
pub arch: Arch,
pub why: &'static str,
}
const VAGRANT_NO_BUILD: &[NoBuild] = &[NoBuild {
os: HostOs::Linux,
arch: Arch::Arm64,
why: "HashiCorp ships no Linux arm64 build, and the distribution's Vagrant is older than the 2.4.0 a run needs (an older one adds a box's x86_64 build on an arm64 computer)",
}];
const GCLOUD_NO_BUILD: &[NoBuild] = &[NoBuild {
os: HostOs::Windows,
arch: Arch::Arm64,
why: "Google ships no Windows on Arm build: its installer brings no Python there, which the CLI needs",
}];
impl Dependency {
pub const ALL: [Dependency; 13] = [
Dependency::Docker,
Dependency::Vagrant,
Dependency::Terraform,
Dependency::Virtualbox,
Dependency::Qemu,
Dependency::Utm,
Dependency::Libvirt,
Dependency::Awscli,
Dependency::Azurecli,
Dependency::Gcloud,
Dependency::Wsl,
Dependency::VmwareUtility,
Dependency::Hyperv,
];
#[must_use]
pub fn row(self) -> ToolRow {
const ANY: Runs = Runs::On(&ALL_OSES);
const fn row(runs: Runs, probe: Option<Probe>, winget: Option<&'static str>, own_url: Option<&'static str>) -> ToolRow {
ToolRow {
runs,
probe,
mac_app: None,
winget,
own_url,
no_build: &[],
}
}
match self {
Dependency::Docker => ToolRow {
mac_app: Some("/Applications/Docker.app"),
..row(
ANY,
Some(("docker", &["--version"])),
Some("Docker.DockerDesktop"),
Some("https://docs.docker.com/engine/install/"),
)
},
Dependency::Vagrant => ToolRow {
no_build: VAGRANT_NO_BUILD,
..row(
ANY,
Some(("vagrant", &["--version"])),
Some("Hashicorp.Vagrant"),
Some("https://developer.hashicorp.com/vagrant/install"),
)
},
Dependency::Terraform => row(ANY, Some(("terraform", &["version"])), Some("Hashicorp.Terraform"), None),
Dependency::Virtualbox => ToolRow {
mac_app: Some("/Applications/VirtualBox.app"),
..row(
Runs::As(Provider::Virtualbox),
None,
Some("Oracle.VirtualBox"),
Some("https://www.virtualbox.org/wiki/Linux_Downloads"),
)
},
Dependency::Qemu => row(Runs::As(Provider::Qemu), None, None, Some("https://www.qemu.org/download/")),
Dependency::Utm => ToolRow {
mac_app: Some("/Applications/UTM.app"),
..row(Runs::As(Provider::Utm), None, None, None)
},
Dependency::Libvirt => row(Runs::As(Provider::Libvirt), None, None, Some("https://libvirt.org/")),
Dependency::Awscli => row(ANY, Some(("aws", &["--version"])), Some("Amazon.AWSCLI"), None),
Dependency::Azurecli => row(ANY, Some(("az", &["version"])), Some("Microsoft.AzureCLI"), None),
Dependency::Gcloud => ToolRow {
no_build: GCLOUD_NO_BUILD,
..row(ANY, Some(("gcloud", &["--version"])), Some("Google.CloudSDK"), None)
},
Dependency::Wsl => row(Runs::On(&[HostOs::Windows]), None, None, None),
Dependency::VmwareUtility => row(ANY, None, None, Some("https://developer.hashicorp.com/vagrant/install/vmware")),
Dependency::Hyperv => row(Runs::As(Provider::Hyperv), None, None, None),
}
}
#[must_use]
pub fn of_hypervisor(provider: Provider) -> Option<Dependency> {
Dependency::ALL.into_iter().find(|d| d.hypervisor() == Some(provider))
}
#[must_use]
pub fn serves(self) -> Option<Provider> {
match self {
Dependency::VmwareUtility => Some(Provider::VmwareDesktop),
_ => None,
}
}
#[must_use]
pub fn hypervisor(self) -> Option<Provider> {
match self.row().runs {
Runs::As(provider) => Some(provider),
Runs::On(_) => None,
}
}
#[must_use]
pub fn no_build(self, os: HostOs, arch: Arch) -> Option<&'static str> {
self.row().no_build.iter().find(|n| n.os == os && n.arch == arch).map(|n| n.why)
}
#[must_use]
pub fn runs_on(self, os: HostOs) -> bool {
match self.row().runs {
Runs::On(oses) => oses.contains(&os),
Runs::As(provider) => ProviderRow::of(provider).oses.contains(&os),
}
}
pub(crate) fn runs_here(self, os: HostOs) -> Result<(), Refusal> {
if self.runs_on(os) {
Ok(())
} else {
Err(Refusal::NotHere { dependency: self, os })
}
}
}
#[must_use]
pub fn vagrant_plugin(plugin: &str) -> Option<Step> {
let named = (plugin.starts_with("vagrant-") || plugin.starts_with("vagrant_"))
&& plugin.len() <= 64
&& plugin.chars().all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_');
named.then(|| step("vagrant", &["plugin", "install", plugin]))
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Elevation {
Prompt,
Unattended {
root: bool,
},
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum NoElevation {
NoPromptNorSudo,
}
impl std::fmt::Display for NoElevation {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
NoElevation::NoPromptNorSudo => f.write_str(
"no administrator's step can run: sudo asks for a password, and no login session here can show the password prompt (an ssh session can't)",
),
}
}
}
impl std::error::Error for NoElevation {}
const MAC_LOGIN_SESSION: &str = "Aqua";
impl Elevation {
pub async fn here(cx: &Context, desktop: bool) -> Result<Elevation, NoElevation> {
if cx.host.os == HostOs::Windows {
return Ok(Elevation::Prompt);
}
if cx.read_ok("id", &["-u"]).await.is_ok_and(|uid| uid.trim() == "0") {
return Ok(Elevation::Unattended { root: true });
}
if cx.read_ok("sudo", &["-n", "true"]).await.is_ok() {
return Ok(Elevation::Unattended { root: false });
}
let session = match cx.host.os {
HostOs::Macos => cx.read_ok("launchctl", &["managername"]).await.is_ok_and(|m| m.trim() == MAC_LOGIN_SESSION),
_ => desktop,
};
if session { Ok(Elevation::Prompt) } else { Err(NoElevation::NoPromptNorSudo) }
}
#[must_use]
pub fn as_root(self, program: &str, args: &[String]) -> (String, Vec<String>) {
let all = |prefix: &[&str]| {
prefix
.iter()
.map(ToString::to_string)
.chain(std::iter::once(program.to_owned()))
.chain(args.iter().cloned())
.collect()
};
match self {
Elevation::Prompt => ("pkexec".into(), all(&[])),
Elevation::Unattended { root: true } => (program.to_owned(), args.to_vec()),
Elevation::Unattended { root: false } => ("sudo".into(), all(&["-n"])),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum Refusal {
NotHere {
dependency: Dependency,
os: HostOs,
},
WithoutPackages {
dependency: Dependency,
},
AptOnly {
dependency: Dependency,
},
NoHomebrew,
HomebrewNeeded,
NoVirtualboxImage,
WindowsFeature {
dependency: Dependency,
},
NotOnWindowsOnArm {
dependency: Dependency,
provider: Provider,
},
NoBuild {
dependency: Dependency,
os: HostOs,
arch: Arch,
why: &'static str,
},
PrivateFile(String),
NothingAdded {
dependency: Dependency,
},
}
impl std::fmt::Display for Refusal {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Refusal::NotHere { dependency, os } => write!(f, "{dependency:?} doesn't run on {}", crate::host::os_name(*os)),
Refusal::WithoutPackages { dependency } => write!(f, "{dependency:?}: this distribution has neither apt nor dnf"),
Refusal::AptOnly { dependency } => write!(f, "{dependency:?} installs through apt only"),
Refusal::NoHomebrew | Refusal::HomebrewNeeded => f.write_str("Homebrew isn't installed"),
Refusal::WindowsFeature { dependency } => write!(f, "{dependency:?} is turned off in Windows Features"),
Refusal::NotOnWindowsOnArm { dependency, .. } => write!(f, "{dependency:?} doesn't run on Windows on Arm"),
Refusal::NoBuild { dependency, os, arch, why } => write!(f, "{dependency:?} isn't offered on {} {arch:?}: {why}", crate::host::os_name(*os)),
Refusal::NoVirtualboxImage => f.write_str("VirtualBox's installer image is needed to run its uninstaller"),
Refusal::PrivateFile(why) => write!(f, "a root step's private file couldn't be written: {why}"),
Refusal::NothingAdded { dependency } => write!(f, "nothing of {dependency:?} was added by an install, so nothing of it is removed"),
}
}
}
impl std::error::Error for Refusal {}
pub fn plan(dep: Dependency, host: &crate::host::Host, user: Option<&str>, elevation: Elevation) -> Result<Vec<Step>, Refusal> {
let mut steps = os_plan(dep, host, user, elevation)?;
if let Some(last) = steps.last_mut() {
last.interactions = interactions(dep, host, elevation, user);
}
Ok(steps)
}
fn os_plan(dep: Dependency, host: &crate::host::Host, user: Option<&str>, elevation: Elevation) -> Result<Vec<Step>, Refusal> {
dep.runs_here(host.os)?;
match host.os {
HostOs::Macos => macos::install(dep, host.packages, host.arch, elevation),
HostOs::Windows => windows::install(dep, host.arch),
HostOs::Linux => {
let root = linux::Root::with_this_proxy(elevation);
linux::install(dep, host.packages, host.arch, user, &root)
}
}
}
pub fn removal(dep: Dependency, host: &crate::host::Host, added: &[Item], elevation: Elevation, virtualbox: Option<&str>) -> Result<Vec<Step>, Refusal> {
dep.runs_here(host.os)?;
match host.os {
HostOs::Linux => {
let root = linux::Root::with_this_proxy(elevation);
linux::uninstall(dep, host.packages, added, &root)
}
_ if !added.contains(&Item::Tool(dep)) => Err(Refusal::NothingAdded { dependency: dep }),
HostOs::Macos => macos::uninstall(dep, host.packages, virtualbox),
HostOs::Windows => windows::uninstall(dep),
}
}
pub async fn present(cx: &Context, dep: Dependency) -> Option<bool> {
let found = tool_found(cx, dep).await?;
match dep.hypervisor() {
Some(provider) if found => Some(crate::providers::helper::missing(cx, provider).await.is_none()),
_ => Some(found),
}
}
pub(crate) async fn tool_found(cx: &Context, dep: Dependency) -> Option<bool> {
if dep == Dependency::VmwareUtility {
return Some(crate::providers::vmware_utility(&cx.host).await != crate::providers::UtilityState::Missing);
}
let row = dep.row();
let mac_app = row.mac_app.filter(|_| cx.host.os == HostOs::Macos);
if let Some(app) = mac_app
.and_then(|a| std::path::Path::new(a).file_name())
.map(|a| cx.host.devices.applications.join(a))
&& app.exists()
{
return Some(mac_image::complete(cx, &app).await);
}
let probe = dep
.hypervisor()
.map_or(row.probe, |provider| crate::providers::hypervisor_probe(provider, cx.host.arch));
match probe {
Some((program, args)) => Some(cx.read_ok(program, args).await.is_ok()),
None if mac_app.is_some() => Some(false),
None => None,
}
}
#[cfg(test)]
mod tests;