Skip to main content

verctl_core/
runners.rs

1//! Machines: declared once under `runners`, named by every job.
2//!
3//! A runner is one machine, and `labels` is how GitHub finds it.
4//! GitHub matches every label at once, so `["self-hosted", "linux", "x64"]`
5//! is a single machine carrying three labels.
6//! Nothing here resolves a *label*.
7//! Verctl has no way to learn which machines carry which, so labels pass
8//! through as written.
9//!
10//! A runner *name*, by contrast, resolves here or fails here. It never reaches
11//! GitHub. Only its labels do.
12
13use std::collections::{BTreeMap, BTreeSet};
14
15use anyhow::{Result, bail, ensure};
16
17use crate::config::{Config, Runner};
18
19/// A machine after resolution: the name it was declared under, and the labels
20/// that go straight into `runs-on:`.
21#[derive(Debug, Clone, PartialEq, Eq)]
22pub struct Machine {
23    /// The name the machine was declared under.
24    pub name: String,
25    /// Straight into `runs-on:`.
26    pub labels: Vec<String>,
27}
28
29/// Check every declared machine before any job names one, so a broken
30/// `runners` entry fails even when nothing uses it yet.
31///
32/// # Errors
33///
34/// Returns an error when a runner has no labels, an empty label, or a repeated
35/// label.
36pub fn declared(config: &Config) -> Result<()> {
37    for (name, runner) in &config.runners {
38        validate(name, runner)?;
39    }
40    Ok(())
41}
42
43fn validate(name: &str, runner: &Runner) -> Result<()> {
44    ensure!(
45        !runner.labels.is_empty(),
46        "runner {name:?}: labels must name at least one label"
47    );
48    let mut seen = BTreeSet::new();
49    for label in &runner.labels {
50        ensure!(
51            !label.trim().is_empty(),
52            "runner {name:?}: labels has an empty label"
53        );
54        ensure!(
55            seen.insert(label.as_str()),
56            "runner {name:?}: label {label:?} is repeated"
57        );
58    }
59    Ok(())
60}
61
62/// The machines a job named. `None` (field omitted) takes `default_labels`
63/// under the name `default_name`.
64///
65/// # Errors
66///
67/// Returns an error when `named` is present but empty or names a machine
68/// twice. It also fails for a machine that is not declared or that fails the
69/// label checks of [`declared`].
70pub fn of(
71    config: &Config,
72    kind: &str,
73    job: &str,
74    named: Option<&Vec<String>>,
75    default_name: &str,
76    default_labels: &[&str],
77) -> Result<Vec<Machine>> {
78    let Some(named) = named else {
79        return Ok(vec![Machine {
80            name: default_name.to_owned(),
81            labels: default_labels
82                .iter()
83                .map(|label| (*label).to_owned())
84                .collect(),
85        }]);
86    };
87    ensure!(
88        !named.is_empty(),
89        "{kind} {job:?}: runners must name at least one machine"
90    );
91    let mut machines = Vec::new();
92    let mut seen = BTreeSet::new();
93    for name in named {
94        ensure!(
95            seen.insert(name.as_str()),
96            "{kind} {job:?}: machine {name:?} is named twice"
97        );
98        machines.push(one(config, kind, job, name)?);
99    }
100    Ok(machines)
101}
102
103/// One machine by name. An undeclared name cannot be guessed at: verctl would
104/// be inventing a label GitHub has never seen.
105///
106/// # Errors
107///
108/// Returns an error when `name` is not declared under `runners`, or when its
109/// labels are empty, contain an empty label, or repeat one.
110pub fn one(config: &Config, kind: &str, job: &str, name: &str) -> Result<Machine> {
111    let Some(runner) = config.runners.get(name) else {
112        bail!(
113            "{kind} {job:?}: machine {name:?} is not declared in runners ({})",
114            declared_names(&config.runners)
115        );
116    };
117    validate(name, runner)?;
118    Ok(Machine {
119        name: name.to_owned(),
120        labels: runner.labels.clone(),
121    })
122}
123
124fn declared_names(runners: &BTreeMap<String, Runner>) -> String {
125    if runners.is_empty() {
126        return "none declared".to_owned();
127    }
128    format!(
129        "declared: {}",
130        runners.keys().cloned().collect::<Vec<_>>().join(", ")
131    )
132}
133
134/// The check name for `job` on `machine` within `machines`. One machine needs
135/// no disambiguation; several would land as same-named checks, each hiding the
136/// others.
137#[must_use]
138pub fn check_name(job: &str, machine: &str, machines: &[Machine]) -> String {
139    if machines.len() > 1 {
140        format!("{job} ({machine})")
141    } else {
142        job.to_owned()
143    }
144}
145
146#[cfg(test)]
147mod tests {
148    use std::slice;
149
150    use ctl_core::input::Input;
151
152    use super::{Machine, check_name, declared, of, one};
153    use crate::config::Config;
154
155    fn load(yaml: &str) -> Config {
156        Config::parse(yaml).expect("parse")
157    }
158
159    /// Shape only. The rules below are the ones `declared` owns, so a fixture
160    /// that breaks one must reach it rather than stopping at the boundary.
161    fn raw(yaml: &str) -> Config {
162        Input::new(".ctl/ver.yaml", yaml).parse().expect("parse")
163    }
164
165    const REGISTRY: &str = indoc::indoc! {"
166        packages:
167          - name: verctl
168            path: Cargo.toml
169
170        runners:
171          linux:
172            labels: [ubuntu-26.04]
173          big:
174            labels: [self-hosted, linux, x64]
175    "};
176
177    fn named(names: &[&str]) -> Vec<String> {
178        names.iter().map(|name| (*name).to_owned()).collect()
179    }
180
181    #[test]
182    fn omitted_takes_the_default_machine() {
183        let machines = of(
184            &load(REGISTRY),
185            "ci job",
186            "verify",
187            None,
188            "hosted",
189            &["ubuntu-26.04"],
190        )
191        .unwrap();
192        assert_eq!(
193            machines,
194            [Machine {
195                name: "hosted".to_owned(),
196                labels: vec!["ubuntu-26.04".to_owned()],
197            }]
198        );
199    }
200
201    #[test]
202    fn labels_reach_the_caller_verbatim_and_in_order() {
203        let machines = of(
204            &load(REGISTRY),
205            "ci job",
206            "verify",
207            Some(&named(&["big"])),
208            "hosted",
209            &[],
210        )
211        .unwrap();
212        assert_eq!(machines[0].labels, ["self-hosted", "linux", "x64"]);
213    }
214
215    #[test]
216    fn one_machine_with_three_labels_is_one_check() {
217        let machines = of(
218            &load(REGISTRY),
219            "ci job",
220            "verify",
221            Some(&named(&["big"])),
222            "hosted",
223            &[],
224        )
225        .unwrap();
226        assert_eq!(machines.len(), 1);
227    }
228
229    #[test]
230    fn two_machines_are_two_checks() {
231        let machines = of(
232            &load(REGISTRY),
233            "ci job",
234            "verify",
235            Some(&named(&["linux", "big"])),
236            "hosted",
237            &[],
238        )
239        .unwrap();
240        assert_eq!(machines.len(), 2);
241    }
242
243    #[test]
244    fn an_undeclared_machine_names_the_declared_ones() {
245        let err = one(&load(REGISTRY), "ci job", "verify", "macos").unwrap_err();
246        let text = format!("{err:#}");
247        assert!(text.contains("not declared in runners"), "{text}");
248        assert!(text.contains("declared: big, linux"), "{text}");
249    }
250
251    #[test]
252    fn an_empty_registry_says_so_rather_than_listing_nothing() {
253        let config = load(indoc::indoc! {"
254            packages:
255              - name: verctl
256                path: Cargo.toml
257        "});
258        let err = one(&config, "ci job", "verify", "linux").unwrap_err();
259        assert!(format!("{err:#}").contains("none declared"), "{err:#}");
260    }
261
262    #[test]
263    fn an_empty_runners_list_is_not_a_default() {
264        let err = of(
265            &load(REGISTRY),
266            "ci job",
267            "verify",
268            Some(&Vec::new()),
269            "hosted",
270            &["ubuntu-26.04"],
271        )
272        .unwrap_err();
273        assert!(
274            format!("{err:#}").contains("at least one machine"),
275            "{err:#}"
276        );
277    }
278
279    #[test]
280    fn naming_one_machine_twice_is_rejected() {
281        let err = of(
282            &load(REGISTRY),
283            "ci job",
284            "verify",
285            Some(&named(&["linux", "linux"])),
286            "hosted",
287            &[],
288        )
289        .unwrap_err();
290        assert!(format!("{err:#}").contains("named twice"), "{err:#}");
291    }
292
293    #[test]
294    fn a_machine_without_labels_is_rejected_even_when_unused() {
295        let config = raw(indoc::indoc! {"
296            packages:
297              - name: verctl
298                path: Cargo.toml
299            runners:
300              broken:
301                labels: []
302        "});
303        let err = declared(&config).unwrap_err();
304        assert!(format!("{err:#}").contains("at least one label"), "{err:#}");
305    }
306
307    #[test]
308    fn a_blank_label_is_rejected() {
309        let config = load(indoc::indoc! {r#"
310            packages:
311              - name: verctl
312                path: Cargo.toml
313            runners:
314              broken:
315                labels: ["  "]
316        "#});
317        let err = declared(&config).unwrap_err();
318        assert!(format!("{err:#}").contains("empty label"), "{err:#}");
319    }
320
321    #[test]
322    fn a_repeated_label_inside_one_machine_is_rejected() {
323        let config = load(indoc::indoc! {"
324            packages:
325              - name: verctl
326                path: Cargo.toml
327            runners:
328              broken:
329                labels: [linux, linux]
330        "});
331        let err = declared(&config).unwrap_err();
332        assert!(format!("{err:#}").contains("repeated"), "{err:#}");
333    }
334
335    #[test]
336    fn a_bare_label_list_is_not_a_machine() {
337        let err = Config::parse(indoc::indoc! {"
338            packages:
339              - name: verctl
340                path: Cargo.toml
341            runners:
342              linux: [ubuntu-26.04]
343        "})
344        .unwrap_err();
345        assert!(
346            format!("{err:#}").contains(".ctl/ver.yaml:5:10: expected a mapping, found a sequence"),
347            "{err:#}"
348        );
349    }
350
351    #[test]
352    fn only_a_fanned_out_job_carries_its_machine_in_the_name() {
353        let linux = Machine {
354            name: "linux".into(),
355            labels: vec!["ubuntu-26.04".into()],
356        };
357        let macos = Machine {
358            name: "macos".into(),
359            labels: vec!["macos-27".into()],
360        };
361        assert_eq!(
362            check_name("verify", "linux", slice::from_ref(&linux)),
363            "verify"
364        );
365        assert_eq!(
366            check_name("verify", "linux", &[linux, macos]),
367            "verify (linux)"
368        );
369    }
370}