Skip to main content

verctl_core/rules/
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;