Skip to main content

isothrum_machine/install/
added.rs

1//! What an install added, and nothing more: before a plan runs, which of its items are there
2//! already ([`before`]); after it, which it added ([`Before::installed`]). An item is what a
3//! removal takes away again ([`Item`]): a Linux distribution's package, or the tool itself where
4//! it comes in one piece. An item that was there before the install is never among what it added,
5//! so a clean-up that removes only what an install added ([`super::record`]) never removes what
6//! someone else installed: a QEMU installed by hand stays when an install only added the programs
7//! its VMs need beside it ([`crate::providers::helpers`]).
8
9use std::collections::BTreeSet;
10
11use serde::{Deserialize, Serialize};
12
13use super::Dependency;
14use crate::context::Context;
15use crate::host::{Host, HostOs, LinuxPackages};
16
17/// What an install brings and a removal takes away again.
18#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
19#[serde(rename_all = "camelCase")]
20pub enum Item {
21    /// A package of the Linux distribution's package manager (apt or dnf), by its name. In a
22    /// tool's list ([`items`]) a name ending in `*` stands for every package it starts.
23    Package(String),
24    /// The tool itself, in one piece as its vendor's installer, Homebrew or winget brings it (an
25    /// app, a formula, a cask, a winget package, an MSI, the AWS CLI's own folder on Linux), there
26    /// as [`super::present`] finds it, its helpers aside.
27    Tool(Dependency),
28}
29
30/// The packages `dep`'s install through `packages` brings that its removal takes away, `name*`
31/// for every package that name starts: the tool's own and the programs its VMs need beside it
32/// ([`crate::providers::helpers`]); never what other tools share (the compiler, Ruby's headers,
33/// a kernel's headers), nor the vendor's repository. The install's metapackages (`qemu-system`,
34/// `libvirt-daemon-system`) pull in the packages with the binaries a check looks for
35/// (`qemu-system-x86_64`, `virsh`): those are its too, or the tool would still read installed.
36/// Empty where the tool isn't a package here (the AWS CLI's folder; a tool apt alone installs on
37/// a dnf distribution).
38#[must_use]
39pub fn packages(dep: Dependency, packages: LinuxPackages) -> Vec<String> {
40    let own: &[&str] = match (dep, packages) {
41        (Dependency::Docker, LinuxPackages::Apt) => &[
42            "docker-ce",
43            "docker-ce-cli",
44            "containerd.io",
45            "docker-buildx-plugin",
46            "docker-compose-plugin",
47            // The distribution's own, where Docker's repository serves no packages.
48            "docker.io",
49            "docker-compose-v2",
50            "docker-compose",
51        ],
52        (Dependency::Docker, LinuxPackages::Dnf) => &["docker-ce", "docker-ce-cli", "containerd.io", "docker-buildx-plugin", "docker-compose-plugin"],
53        (Dependency::Vagrant, _) => &["vagrant"],
54        (Dependency::Terraform, _) => &["terraform"],
55        (Dependency::Virtualbox, LinuxPackages::Apt) => &["virtualbox*"],
56        (Dependency::Virtualbox, LinuxPackages::Dnf) => &["VirtualBox", "akmod-VirtualBox", "kmod-VirtualBox*"],
57        (Dependency::Qemu, LinuxPackages::Apt) => &["qemu-system*", "qemu-utils"],
58        (Dependency::Qemu, LinuxPackages::Dnf) => &["qemu-kvm", "qemu-img"],
59        (Dependency::Libvirt, LinuxPackages::Apt) => &["libvirt-daemon*", "libvirt-clients", "virt-manager"],
60        (Dependency::Libvirt, LinuxPackages::Dnf) => &["libvirt", "libvirt-daemon-kvm", "virt-install", "virt-manager", "libvirt-devel"],
61        (Dependency::Azurecli, LinuxPackages::Apt) => &["azure-cli"],
62        (Dependency::Gcloud, LinuxPackages::Apt) => &["google-cloud-cli"],
63        // With `net-tools`, whose `netstat` vagrant-vmware-desktop reads the routing table with
64        // ([`crate::providers::needs::vmware_utility`]): its install brings it.
65        (Dependency::VmwareUtility, LinuxPackages::Apt) => &["vagrant-vmware-utility", "net-tools"],
66        (Dependency::Awscli | Dependency::Utm | Dependency::Wsl | Dependency::Hyperv, _)
67        | (Dependency::Azurecli | Dependency::Gcloud | Dependency::VmwareUtility, LinuxPackages::Dnf) => &[],
68    };
69    let helpers = dep
70        .hypervisor()
71        .map_or(&[][..], |provider| crate::providers::helpers(provider, HostOs::Linux))
72        .iter()
73        .map(|helper| helper.package(packages));
74    own.iter().copied().chain(helpers).map(str::to_owned).collect()
75}
76
77/// What `dep`'s install on `host` may add: its packages ([`packages`]) on a Linux distribution
78/// with apt or dnf, else the tool itself ([`Item::Tool`]).
79#[must_use]
80pub fn items(dep: Dependency, host: &Host) -> Vec<Item> {
81    let linux = host.packages.and_then(crate::host::Packages::linux).filter(|_| host.os == HostOs::Linux);
82    match linux {
83        Some(manager) if dep != Dependency::Awscli => packages(dep, manager).into_iter().map(Item::Package).collect(),
84        _ => vec![Item::Tool(dep)],
85    }
86}
87
88/// Whether the package `name` is one `pattern` stands for: the same name, or one it starts
89/// when it ends in `*`.
90pub(crate) fn matches(pattern: &str, name: &str) -> bool {
91    pattern.strip_suffix('*').map_or(pattern == name, |prefix| name.starts_with(prefix))
92}
93
94/// The packages the context's Linux package manager has installed, by name: dpkg's (apt) whose
95/// state is anything but "not installed" or "config files only", or rpm's (dnf). `None` when
96/// they can't be read.
97async fn installed_packages(cx: &Context, manager: LinuxPackages) -> Option<BTreeSet<String>> {
98    match manager {
99        LinuxPackages::Apt => {
100            let out = cx.read_ok("dpkg-query", &["-W", "-f", "${db:Status-Abbrev}\t${Package}\n"]).await.ok()?;
101            Some(
102                out.lines()
103                    .filter_map(|line| line.split_once('\t'))
104                    .filter(|(state, _)| !matches!(state.chars().nth(1), None | Some('n' | 'c')))
105                    .map(|(_, name)| name.trim().to_owned())
106                    .collect(),
107            )
108        }
109        LinuxPackages::Dnf => {
110            let out = cx.read_ok("rpm", &["-qa", "--qf", "%{NAME}\n"]).await.ok()?;
111            Some(out.lines().map(str::trim).filter(|n| !n.is_empty()).map(str::to_owned).collect())
112        }
113    }
114}
115
116/// Which of `dep`'s items ([`items`]) are on the context's host now, each package by its own
117/// name. `None` when that can't be told (the package manager's list unread, WSL, Hyper-V).
118pub async fn there(cx: &Context, dep: Dependency) -> Option<BTreeSet<Item>> {
119    let mut found = BTreeSet::new();
120    let mut installed = None;
121    for item in items(dep, &cx.host) {
122        match item {
123            Item::Package(pattern) => {
124                if installed.is_none() {
125                    let manager = cx.host.packages.and_then(crate::host::Packages::linux)?;
126                    installed = Some(installed_packages(cx, manager).await?);
127                }
128                let names = installed.iter().flatten().filter(|name| matches(&pattern, name));
129                found.extend(names.map(|name| Item::Package(name.clone())));
130            }
131            Item::Tool(tool) => {
132                if super::tool_found(cx, tool).await? {
133                    found.insert(Item::Tool(tool));
134                }
135            }
136        }
137    }
138    Some(found)
139}
140
141/// Which of a tool's items were there before its install ran ([`before`]).
142#[derive(Debug, Clone)]
143pub struct Before {
144    dependency: Dependency,
145    there: Option<BTreeSet<Item>>,
146}
147
148/// What of `dep`'s install is on the context's host before it runs: read before running its
149/// plan, then [`Before::installed`] after it.
150pub async fn before(cx: &Context, dep: Dependency) -> Before {
151    Before {
152        dependency: dep,
153        there: there(cx, dep).await,
154    }
155}
156
157/// What an install added: what a clean-up may remove again, and nothing else.
158#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
159#[serde(rename_all = "camelCase")]
160#[non_exhaustive]
161pub struct Installed {
162    /// The items missing before the install and there after it.
163    pub added: Vec<Item>,
164    /// The tool itself where it was missing before and isn't found yet: its installer left open
165    /// for its user to finish (a macOS cask), or `PATH` not read again yet. It counts as added
166    /// once a later check finds it ([`super::record::settle`]).
167    pub waiting: Vec<Item>,
168}
169
170impl Installed {
171    /// What an install that added `added` and left `waiting` reports.
172    #[must_use]
173    pub fn new(added: Vec<Item>, waiting: Vec<Item>) -> Installed {
174        Installed { added, waiting }
175    }
176
177    /// Whether it added nothing, nor left anything waiting.
178    #[must_use]
179    pub fn is_empty(&self) -> bool {
180        self.added.is_empty() && self.waiting.is_empty()
181    }
182}
183
184impl Before {
185    /// What the install added, read on the context's host after it ran: the items there now that
186    /// weren't before. Nothing when either can't be told: a record never claims what it can't
187    /// prove the install added.
188    pub async fn installed(self, cx: &Context) -> Installed {
189        let Some(before) = self.there else {
190            return Installed::default();
191        };
192        let Some(after) = there(cx, self.dependency).await else {
193            return Installed::default();
194        };
195        let added = after.difference(&before).cloned().collect();
196        let waiting = items(self.dependency, &cx.host)
197            .into_iter()
198            .filter(|item| matches!(item, Item::Tool(_)) && !before.contains(item) && !after.contains(item))
199            .collect();
200        Installed { added, waiting }
201    }
202}
203
204#[cfg(test)]
205mod tests;