Skip to main content

isothrum_runner/project/
platform.rs

1//! The host and hypervisor words Isothrum shares with its embedder: the computer's OS and CPU, a
2//! Vagrant provider (the hypervisor `vagrant up --provider` takes) and a cloud. Isothrum's own
3//! types, written as the tools and their users write them (`vmware_desktop`, `aws`).
4
5use serde::{Deserialize, Serialize};
6
7/// A host operating system.
8#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize, schemars::JsonSchema)]
9#[serde(rename_all = "lowercase")]
10pub enum HostOs {
11    /// Linux.
12    Linux,
13    /// macOS.
14    Macos,
15    /// Windows.
16    Windows,
17}
18
19/// A CPU architecture.
20#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize, schemars::JsonSchema)]
21#[serde(rename_all = "lowercase")]
22pub enum Arch {
23    /// x86-64.
24    Amd64,
25    /// 64-bit ARM.
26    Arm64,
27}
28
29/// A Vagrant provider: the hypervisor `vagrant up --provider` takes. Exhaustive: whoever detects
30/// or offers providers (`isothrum-machine`) fails to compile until a new one has its row.
31#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize, schemars::JsonSchema)]
32// Its TypeScript type (the `ts-rs` feature) is `VagrantProvider`.
33#[cfg_attr(feature = "ts-rs", derive(ts_rs::TS), ts(rename = "VagrantProvider"))]
34#[serde(rename_all = "snake_case")]
35pub enum Provider {
36    /// VirtualBox.
37    Virtualbox,
38    /// VMware Workstation or Fusion.
39    VmwareDesktop,
40    /// Hyper-V.
41    Hyperv,
42    /// Parallels Desktop.
43    Parallels,
44    /// libvirt (KVM).
45    Libvirt,
46    /// QEMU.
47    Qemu,
48    /// UTM.
49    Utm,
50    /// An ESXi server.
51    VmwareEsxi,
52}
53
54impl Provider {
55    /// Every provider, in the order they are offered.
56    pub const ALL: [Provider; 8] = [
57        Provider::Virtualbox,
58        Provider::VmwareDesktop,
59        Provider::Hyperv,
60        Provider::Parallels,
61        Provider::Libvirt,
62        Provider::Qemu,
63        Provider::Utm,
64        Provider::VmwareEsxi,
65    ];
66
67    /// The provider as `vagrant up --provider` takes it (`vmware_desktop`).
68    #[must_use]
69    pub const fn id(self) -> &'static str {
70        match self {
71            Provider::Virtualbox => "virtualbox",
72            Provider::VmwareDesktop => "vmware_desktop",
73            Provider::Hyperv => "hyperv",
74            Provider::Parallels => "parallels",
75            Provider::Libvirt => "libvirt",
76            Provider::Qemu => "qemu",
77            Provider::Utm => "utm",
78            Provider::VmwareEsxi => "vmware_esxi",
79        }
80    }
81
82    /// The plugin Vagrant runs it through; `None` for the providers Vagrant has built in.
83    #[must_use]
84    pub const fn plugin(self) -> Option<&'static str> {
85        match self {
86            Provider::Virtualbox | Provider::Hyperv => None,
87            Provider::VmwareDesktop => Some("vagrant-vmware-desktop"),
88            Provider::Parallels => Some("vagrant-parallels"),
89            Provider::Libvirt => Some("vagrant-libvirt"),
90            Provider::Qemu => Some("vagrant-qemu"),
91            Provider::Utm => Some("vagrant_utm"),
92            Provider::VmwareEsxi => Some("vagrant-vmware-esxi"),
93        }
94    }
95
96    /// Whether its VMs run on another computer (a server), not this one.
97    #[must_use]
98    pub const fn is_remote(self) -> bool {
99        matches!(self, Provider::VmwareEsxi)
100    }
101}
102
103/// A public cloud.
104#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize, schemars::JsonSchema)]
105#[serde(rename_all = "lowercase")]
106#[non_exhaustive]
107pub enum Cloud {
108    /// Amazon Web Services.
109    Aws,
110    /// Microsoft Azure.
111    Azure,
112    /// Google Cloud.
113    Gcp,
114    /// DigitalOcean.
115    Digitalocean,
116    /// Akamai Linode.
117    Linode,
118    /// Oracle Cloud Infrastructure.
119    Oci,
120}
121
122/// A port's transport protocol.
123#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize, schemars::JsonSchema)]
124#[serde(rename_all = "lowercase")]
125pub enum Protocol {
126    /// TCP.
127    #[default]
128    Tcp,
129    /// UDP.
130    Udp,
131}
132
133impl Protocol {
134    /// The protocol as the tools write it (`tcp`, `udp`), in any case; `None` for another word.
135    #[must_use]
136    pub fn parse(word: &str) -> Option<Protocol> {
137        if word.eq_ignore_ascii_case("tcp") {
138            Some(Protocol::Tcp)
139        } else if word.eq_ignore_ascii_case("udp") {
140            Some(Protocol::Udp)
141        } else {
142            None
143        }
144    }
145
146    /// The protocol as the tools write it.
147    #[must_use]
148    pub const fn as_str(self) -> &'static str {
149        match self {
150            Protocol::Tcp => "tcp",
151            Protocol::Udp => "udp",
152        }
153    }
154}
155
156impl std::fmt::Display for Protocol {
157    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
158        f.write_str(self.as_str())
159    }
160}
161
162/// A tool's version: `major.minor.patch`, with an optional pre-release (`2.17.0`, `1.0.0-rc.1`).
163/// Ordered as versions are (semver precedence): by the numbers, then a pre-release before the
164/// release it leads to, two pre-releases by their dot-separated fields (numbers as numbers,
165/// a number before text, fewer fields first when they tie).
166#[derive(Debug, Clone, PartialEq, Eq, Hash)]
167pub struct Version {
168    major: u64,
169    minor: u64,
170    patch: u64,
171    pre: Option<String>,
172}
173
174impl Version {
175    /// `major.minor.patch`, released.
176    #[must_use]
177    pub const fn new(major: u64, minor: u64, patch: u64) -> Version {
178        Version {
179            major,
180            minor,
181            patch,
182            pre: None,
183        }
184    }
185
186    /// The version `text` is exactly (three numbers joined by dots, then optionally `-` and a
187    /// pre-release of letters, digits, dots and dashes); `None` for anything else.
188    #[must_use]
189    pub fn parse(text: &str) -> Option<Version> {
190        let (core, pre) = match text.split_once('-') {
191            Some((core, pre)) => (core, Some(pre)),
192            None => (text, None),
193        };
194        let mut numbers = core.split('.').map(|n| {
195            if n.is_empty() || !n.bytes().all(|b| b.is_ascii_digit()) {
196                return None;
197            }
198            n.parse::<u64>().ok()
199        });
200        let (major, minor, patch) = (numbers.next()??, numbers.next()??, numbers.next()??);
201        if numbers.next().is_some() {
202            return None;
203        }
204        let pre = match pre {
205            None => None,
206            Some(p) if !p.is_empty() && p.chars().all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '-')) => Some(p.to_owned()),
207            Some(_) => return None,
208        };
209        Some(Version { major, minor, patch, pre })
210    }
211}
212
213impl std::fmt::Display for Version {
214    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
215        write!(f, "{}.{}.{}", self.major, self.minor, self.patch)?;
216        if let Some(pre) = &self.pre {
217            write!(f, "-{pre}")?;
218        }
219        Ok(())
220    }
221}
222
223impl Ord for Version {
224    fn cmp(&self, other: &Version) -> std::cmp::Ordering {
225        use std::cmp::Ordering;
226        (self.major, self.minor, self.patch)
227            .cmp(&(other.major, other.minor, other.patch))
228            .then_with(|| match (&self.pre, &other.pre) {
229                (None, None) => Ordering::Equal,
230                (None, Some(_)) => Ordering::Greater,
231                (Some(_), None) => Ordering::Less,
232                (Some(a), Some(b)) => pre_release_cmp(a, b),
233            })
234    }
235}
236
237impl PartialOrd for Version {
238    fn partial_cmp(&self, other: &Version) -> Option<std::cmp::Ordering> {
239        Some(self.cmp(other))
240    }
241}
242
243/// Two pre-releases, field by field: numbers as numbers, a number before text, text as ASCII,
244/// and fewer fields first when the fields they have tie.
245#[expect(clippy::many_single_char_names, reason = "the two sides of a comparison, field by field")]
246fn pre_release_cmp(a: &str, b: &str) -> std::cmp::Ordering {
247    use std::cmp::Ordering;
248    let mut xs = a.split('.');
249    let mut ys = b.split('.');
250    loop {
251        let order = match (xs.next(), ys.next()) {
252            (None, None) => return Ordering::Equal,
253            (None, Some(_)) => return Ordering::Less,
254            (Some(_), None) => return Ordering::Greater,
255            (Some(x), Some(y)) => match (x.parse::<u64>(), y.parse::<u64>()) {
256                (Ok(m), Ok(n)) => m.cmp(&n),
257                (Ok(_), Err(_)) => Ordering::Less,
258                (Err(_), Ok(_)) => Ordering::Greater,
259                (Err(_), Err(_)) => x.cmp(y),
260            },
261        };
262        if order != Ordering::Equal {
263            return order;
264        }
265    }
266}
267
268#[cfg(test)]
269mod tests {
270    use super::*;
271
272    #[test]
273    fn a_version_sorts_by_its_numbers_then_a_pre_release_first() {
274        let v = |s: &str| Version::parse(s).unwrap();
275        assert!(v("2.9.0") < v("2.14.0"));
276        assert!(v("10.0.0") > v("9.0.0"));
277        assert!(v("1.0.0-rc.1") < v("1.0.0"));
278        assert!(v("1.0.0-alpha") < v("1.0.0-alpha.1"));
279        assert!(v("1.0.0-alpha.9") < v("1.0.0-alpha.11"));
280        assert!(v("1.0.0-1") < v("1.0.0-alpha"));
281        assert_eq!(v("2.17.0-desktop.1").to_string(), "2.17.0-desktop.1");
282        for bad in ["1.0", "1.0.0-", "v1.0.0", "1..0", "1.0.0.0"] {
283            assert_eq!(Version::parse(bad), None, "{bad}");
284        }
285    }
286}