Skip to main content

isothrum_runner/
tool_output.rs

1//! What the host's tools say of themselves, read in one place for the runner and the
2//! machine-setup backend (`isothrum-machine`): the version a tool prints, in Isoloom's order, the
3//! plugins `vagrant plugin list --machine-readable` lists, and the error a
4//! machine-readable Vagrant call failed with.
5
6use isoloom_manifest::Version;
7
8/// The version `text` says (what a tool prints: `Vagrant 2.4.1`, `v2.29.1`, `1.0.0-rc.1`), as
9/// Isoloom's [`Version`], so versions compare in its order (a pre-release before its release):
10/// its first word that is one, else its first `<major>.<minor>[.<patch>]` (`2.3.8.dev` is 2.3.8, a
11/// missing patch 0). `None` when it says none: nothing is held back then. The one reading of a
12/// version for the runner's tool probes and `isothrum-machine`'s minimums.
13#[must_use]
14pub fn version_found(text: &str) -> Option<Version> {
15    text.split(|c: char| c.is_whitespace() || matches!(c, ',' | '(' | ')'))
16        .map(|w| w.strip_prefix('v').unwrap_or(w))
17        .find_map(|w| Version::parse(w).ok())
18        .or_else(|| {
19            // Isoloom's Version is made from its text alone.
20            let (major, minor, patch) = numbers_in(text)?;
21            Version::parse(&format!("{major}.{minor}.{patch}")).ok()
22        })
23}
24
25/// The first `<major>.<minor>[.<patch>]` in `text` (`Docker Compose version 2.17`,
26/// `2.3.8.dev`), its suffix dropped and a missing patch 0.
27fn numbers_in(text: &str) -> Option<(u64, u64, u64)> {
28    text.split(|c: char| !(c.is_ascii_digit() || c == '.')).find_map(|word| {
29        let mut parts = word.split('.').filter(|p| !p.is_empty()).map(str::parse::<u64>);
30        let major = parts.next()?.ok()?;
31        let minor = parts.next()?.ok()?;
32        let patch = parts.next().and_then(Result::ok).unwrap_or(0);
33        Some((major, minor, patch))
34    })
35}
36
37/// Each plugin `vagrant plugin list --machine-readable` names (its `plugin-name` lines), with its
38/// version when a `plugin-version` line gives one (`0.12.2%!(VAGRANT_COMMA) global`: the version
39/// before Vagrant's escaped comma).
40#[must_use]
41pub fn vagrant_plugins(out: &str) -> Vec<(String, Option<String>)> {
42    let lines: Vec<(&str, &str, &str)> = out.lines().filter_map(vagrant_fields).collect();
43    let version = |name: &str| {
44        lines
45            .iter()
46            .find(|(target, kind, _)| *target == name && *kind == "plugin-version")
47            .and_then(|(_, _, data)| {
48                let v = data.split("%!(VAGRANT_COMMA)").next().unwrap_or_default().trim();
49                (!v.is_empty()).then(|| v.to_owned())
50            })
51    };
52    lines
53        .iter()
54        .filter(|(_, kind, data)| *kind == "plugin-name" && !data.is_empty())
55        .map(|(_, _, name)| ((*name).to_owned(), version(name)))
56        .collect()
57}
58
59/// The error a Vagrant call printed as its `--machine-readable` `error-exit` record among `stdout`
60/// (its last, when there are more): its message as Vagrant words it for a person, followed by
61/// its class (`… because it is locked! … (Vagrant::Errors::MachineLocked)`). With
62/// `--machine-readable`, Vagrant prints its error there, on standard output, and nothing of it on
63/// standard error.
64pub(crate) fn vagrant_error(stdout: &[String]) -> Option<String> {
65    let data = stdout
66        .iter()
67        .rev()
68        .filter_map(|line| vagrant_fields(line))
69        .find_map(|(_, kind, data)| (kind == "error-exit").then_some(data))?;
70    let (class, message) = data.split_once(',').unwrap_or((data, ""));
71    let (class, message) = (unescape(class), unescape(message));
72    match (class.trim(), message.trim()) {
73        ("", "") => None,
74        (class, "") => Some(class.to_owned()),
75        ("", message) => Some(message.to_owned()),
76        (class, message) => Some(format!("{message} ({class})")),
77    }
78}
79
80/// A `--machine-readable` field as Vagrant wrote it, its escapes undone: a comma written as
81/// `%!(VAGRANT_COMMA)`, a line break as `\n`, a carriage return as `\r`.
82fn unescape(field: &str) -> String {
83    field.replace("%!(VAGRANT_COMMA)", ",").replace("\\r", "").replace("\\n", "\n")
84}
85
86/// One line of Vagrant's `--machine-readable` output: its target, type and data (the rest of the
87/// line). Lines are `timestamp,target,type,data…`; Vagrant writes a comma in a field as
88/// `%!(VAGRANT_COMMA)`, so the data is kept whole as printed.
89pub(crate) fn vagrant_fields(line: &str) -> Option<(&str, &str, &str)> {
90    let mut parts = line.trim_end_matches('\r').splitn(4, ',');
91    let (_ts, target, kind, data) = (parts.next()?, parts.next()?, parts.next()?, parts.next()?);
92    Some((target, kind, data))
93}
94
95#[cfg(test)]
96mod tests {
97    use super::*;
98
99    /// A version as each tool prints it, compared in Isoloom's order: by its numbers (a missing
100    /// patch 0), a pre-release before its release.
101    #[test]
102    fn versions_are_read_from_what_a_tool_prints_in_isoloom_s_order() {
103        let v = |text: &str| version_found(text).unwrap();
104        let parsed = |text: &str| Version::parse(text).unwrap();
105        assert_eq!(v("5.5.1"), parsed("5.5.1"));
106        assert_eq!(v("Vagrant 2.4.1"), parsed("2.4.1"));
107        assert_eq!(v("v2.29.1-desktop.1"), parsed("2.29.1-desktop.1"));
108        assert_eq!(v("Docker Compose version 2.17"), parsed("2.17.0"));
109        assert_eq!(v("2.3.8.dev"), parsed("2.3.8"), "a suffix that isn't a pre-release is dropped");
110        assert_eq!(version_found("no version here"), None);
111        assert!(v("2.16.9") < v("2.17.0"));
112        assert!(v("4.7") > v("4.6.5"), "a missing part is 0");
113        assert!(v("4.7.5") > v("4.6.5") && v("4.6.5") >= v("4.6.5"));
114        assert!(v("0.1.6") < v("0.2.0"));
115        assert!(v("0.2.0-beta") < v("0.2.0"), "a pre-release comes before its release");
116    }
117
118    #[test]
119    fn plugins_are_read_by_name_with_their_versions() {
120        // As Vagrant 2.4 prints them (a `ui` line repeats the human list).
121        let out = "1794305819,,ui,info,vagrant-qemu (0.7.0%!(VAGRANT_COMMA) global)\n\
122                   1794305819,,plugin-name,vagrant-qemu\n\
123                   1794305819,vagrant-qemu,plugin-version,0.7.0%!(VAGRANT_COMMA) global\n\
124                   1794305819,,plugin-name,vagrant-vmware-esxi\r\n\
125                   1794305819,,plugin-name,vagrant_utm\n\
126                   1794305819,vagrant_utm,plugin-version,0.2.0\n";
127        assert_eq!(
128            vagrant_plugins(out),
129            [
130                ("vagrant-qemu".to_owned(), Some("0.7.0".to_owned())),
131                ("vagrant-vmware-esxi".to_owned(), None),
132                ("vagrant_utm".to_owned(), Some("0.2.0".to_owned())),
133            ]
134        );
135        assert_eq!(vagrant_plugins(""), Vec::<(String, Option<String>)>::new());
136    }
137
138    fn lines(text: &str) -> Vec<String> {
139        text.lines().map(str::to_owned).collect()
140    }
141
142    #[test]
143    fn a_machine_readable_error_is_read_whole_with_its_class() {
144        // As Vagrant 2.4.9 prints it on libvirt while another process holds the machine's lock.
145        let said = "Vagrant can't use the requested machine because it is locked! This\\nmeans that another Vagrant \
146                    process is currently reading or modifying\\nthe machine.\\n\\nName: probe\\nProvider: libvirt";
147        let out = lines(&format!(
148            "1794342958,,ui,error,{said}\n1794342958,,error-exit,Vagrant::Errors::MachineLocked,{said}\n"
149        ));
150        assert_eq!(
151            vagrant_error(&out).as_deref(),
152            Some(
153                "Vagrant can't use the requested machine because it is locked! This\nmeans that another Vagrant \
154                 process is currently reading or modifying\nthe machine.\n\nName: probe\nProvider: libvirt \
155                 (Vagrant::Errors::MachineLocked)"
156            )
157        );
158        let commas = lines("1,,error-exit,Vagrant::Errors::VagrantError,a%!(VAGRANT_COMMA) b\\r\\n");
159        assert_eq!(vagrant_error(&commas).as_deref(), Some("a, b (Vagrant::Errors::VagrantError)"));
160        assert_eq!(
161            vagrant_error(&lines("1,,error-exit,Vagrant::Errors::X,")).as_deref(),
162            Some("Vagrant::Errors::X")
163        );
164        assert_eq!(vagrant_error(&lines("1,web,state,running\n==> web: up")), None);
165        assert_eq!(vagrant_error(&lines("1,,error-exit,")), None);
166    }
167}