Skip to main content

verctl_core/
ci.rs

1//! Which machines run PR and push validation.
2//!
3//! A `ci` entry is one job; its `runners` name machines from `runners`, one
4//! check each. Write nothing and one `verify` job runs on `ubuntu-26.04`,
5//! which is what every repo in this family did before the section existed.
6//!
7//! GitHub needs `runs-on` before a job exists, so a job cannot read its own
8//! machine from verctl. A small `plan` job emits this matrix and the real jobs
9//! consume it, the same bootstrap the publish lane uses for assets.
10
11use std::path::Path;
12
13use anyhow::{Context, Result};
14use serde::Serialize;
15
16use crate::config::Config;
17use crate::{env, runners};
18
19const DEFAULT_JOB: &str = "verify";
20const DEFAULT_MACHINE: &str = "ubuntu-26.04";
21const DEFAULT_LABELS: &[&str] = &["ubuntu-26.04"];
22
23/// One row of a GitHub Actions `strategy.matrix`, and one check.
24#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
25pub struct CiJob {
26    /// The job as declared. Rows share it when the job fans out.
27    pub id: String,
28    /// The check name, unique across rows.
29    pub name: String,
30    /// The machine this row runs on, as declared.
31    pub machine: String,
32    /// Straight into `runs-on:`.
33    pub labels: Vec<String>,
34}
35
36/// A GitHub Actions `strategy.matrix`.
37#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
38pub struct Matrix {
39    /// One row per check.
40    pub include: Vec<CiJob>,
41}
42
43/// The validation jobs to run, as the workflow reads them.
44#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
45pub struct CiPlan {
46    /// The matrix the workflow fans out over.
47    pub matrix: Matrix,
48}
49
50/// Plan the jobs declared under `ci`, or one `verify` job when none is
51/// declared.
52///
53/// # Errors
54///
55/// Returns an error when a declared runner is invalid, or when a job names a
56/// machine that is missing, repeated, or not declared under `runners`.
57pub fn plan(config: &Config) -> Result<CiPlan> {
58    runners::declared(config)?;
59    let mut include = Vec::new();
60    if config.ci.is_empty() {
61        let resolved = machines(config, DEFAULT_JOB, None)?;
62        push(&mut include, DEFAULT_JOB, &resolved);
63        return Ok(CiPlan {
64            matrix: Matrix { include },
65        });
66    }
67    for (id, job) in &config.ci {
68        let resolved = machines(config, id, job.runners.as_ref())?;
69        push(&mut include, id, &resolved);
70    }
71    Ok(CiPlan {
72        matrix: Matrix { include },
73    })
74}
75
76fn machines(
77    config: &Config,
78    id: &str,
79    named: Option<&Vec<String>>,
80) -> Result<Vec<runners::Machine>> {
81    runners::of(config, "ci job", id, named, DEFAULT_MACHINE, DEFAULT_LABELS)
82}
83
84fn push(include: &mut Vec<CiJob>, id: &str, resolved: &[runners::Machine]) {
85    for machine in resolved {
86        include.push(CiJob {
87            id: id.to_owned(),
88            name: runners::check_name(id, &machine.name, resolved),
89            machine: machine.name.clone(),
90            labels: machine.labels.clone(),
91        });
92    }
93}
94
95/// Write `matrix` as a JSON line for `$GITHUB_OUTPUT`.
96///
97/// # Errors
98///
99/// Returns an error when the matrix cannot be encoded as JSON, or when the
100/// file at `path` cannot be opened or written.
101pub fn write_github_output(plan: &CiPlan, path: &Path) -> Result<()> {
102    let encoded = serde_json::to_string(&plan.matrix).context("encode matrix")?;
103    env::write_github_output(path, &format!("matrix={encoded}\n"))
104}
105
106#[cfg(test)]
107mod tests {
108    use std::fs;
109
110    use super::plan;
111    use crate::config::Config;
112
113    fn load(yaml: &str) -> Config {
114        Config::parse(yaml).expect("parse")
115    }
116
117    const PACKAGE: &str = indoc::indoc! {"
118        packages:
119          - name: verctl
120            path: Cargo.toml
121    "};
122
123    const REGISTRY: &str = indoc::indoc! {"
124        packages:
125          - name: verctl
126            path: Cargo.toml
127
128        runners:
129          linux:
130            labels: [ubuntu-26.04]
131          macos:
132            labels: [macos-latest]
133          big:
134            labels: [self-hosted, linux, x64]
135    "};
136
137    fn with(extra: &str) -> Config {
138        load(&format!("{REGISTRY}{extra}"))
139    }
140
141    #[test]
142    fn no_ci_section_is_one_verify_on_ubuntu_latest() {
143        let planned = plan(&load(PACKAGE)).unwrap();
144        assert_eq!(planned.matrix.include.len(), 1);
145        assert_eq!(planned.matrix.include[0].id, "verify");
146        assert_eq!(planned.matrix.include[0].name, "verify");
147        assert_eq!(planned.matrix.include[0].labels, ["ubuntu-26.04"]);
148    }
149
150    #[test]
151    fn a_job_with_no_runners_takes_the_default_machine() {
152        let planned = plan(&with("ci:\n  verify: {}\n")).unwrap();
153        assert_eq!(planned.matrix.include[0].labels, ["ubuntu-26.04"]);
154        assert_eq!(planned.matrix.include[0].name, "verify");
155    }
156
157    #[test]
158    fn one_machine_with_three_labels_is_one_check() {
159        let planned = plan(&with(indoc::indoc! {"
160            ci:
161              verify:
162                runners: [big]
163        "}))
164        .unwrap();
165        assert_eq!(planned.matrix.include.len(), 1);
166        assert_eq!(planned.matrix.include[0].name, "verify");
167        assert_eq!(
168            planned.matrix.include[0].labels,
169            ["self-hosted", "linux", "x64"]
170        );
171    }
172
173    #[test]
174    fn two_machines_fan_one_job_into_two_named_checks() {
175        let planned = plan(&with(indoc::indoc! {"
176            ci:
177              verify:
178                runners: [linux, macos]
179        "}))
180        .unwrap();
181        assert_eq!(planned.matrix.include.len(), 2);
182        assert!(planned.matrix.include.iter().all(|row| row.id == "verify"));
183        assert_eq!(
184            planned
185                .matrix
186                .include
187                .iter()
188                .map(|row| row.name.as_str())
189                .collect::<Vec<_>>(),
190            ["verify (linux)", "verify (macos)"]
191        );
192    }
193
194    #[test]
195    fn separate_jobs_stay_separate_checks() {
196        let planned = plan(&with(indoc::indoc! {"
197            ci:
198              audit:
199                runners: [linux]
200              verify:
201                runners: [macos]
202        "}))
203        .unwrap();
204        assert_eq!(
205            planned
206                .matrix
207                .include
208                .iter()
209                .map(|row| row.name.as_str())
210                .collect::<Vec<_>>(),
211            ["audit", "verify"]
212        );
213    }
214
215    #[test]
216    fn an_undeclared_machine_is_rejected() {
217        let err = plan(&with(indoc::indoc! {"
218            ci:
219              verify:
220                runners: [windows]
221        "}))
222        .unwrap_err();
223        let text = format!("{err:#}");
224        assert!(text.contains("not declared in runners"), "{text}");
225        assert!(text.contains("big, linux, macos"), "{text}");
226    }
227
228    #[test]
229    fn an_empty_runners_list_is_rejected() {
230        let err = plan(&with(indoc::indoc! {"
231            ci:
232              verify:
233                runners: []
234        "}))
235        .unwrap_err();
236        assert!(
237            format!("{err:#}").contains("at least one machine"),
238            "{err:#}"
239        );
240    }
241
242    #[test]
243    fn a_build_field_is_not_a_ci_field() {
244        let err = Config::parse(&format!(
245            "{REGISTRY}{}",
246            indoc::indoc! {"
247                ci:
248                  verify:
249                    triple: x86_64-unknown-linux-gnu
250            "}
251        ))
252        .unwrap_err();
253        assert!(format!("{err:#}").contains("triple"), "{err:#}");
254    }
255
256    #[test]
257    fn a_label_is_not_a_machine_name() {
258        let err = plan(&with(indoc::indoc! {"
259            ci:
260              verify:
261                runners: [ubuntu-26.04]
262        "}))
263        .unwrap_err();
264        assert!(
265            format!("{err:#}").contains("not declared in runners"),
266            "{err:#}"
267        );
268    }
269
270    #[test]
271    fn github_output_is_one_matrix_assignment() {
272        let planned = plan(&load(PACKAGE)).unwrap();
273        let root = tempfile::TempDir::new().unwrap();
274        let out = root.path().join("out");
275        super::write_github_output(&planned, &out).unwrap();
276        let text = fs::read_to_string(&out).unwrap();
277        let matrix_line = text
278            .lines()
279            .find(|line| line.starts_with("matrix="))
280            .unwrap();
281        let json: serde_json::Value =
282            serde_json::from_str(matrix_line.trim_start_matches("matrix=")).unwrap();
283        let first = &json["include"][0];
284        assert_eq!(first["id"], "verify");
285        assert_eq!(first["name"], "verify");
286        assert_eq!(first["labels"][0], "ubuntu-26.04");
287        assert_eq!(text.lines().count(), 1, "{text}");
288    }
289
290    #[test]
291    fn github_output_keeps_what_an_earlier_step_wrote() {
292        let planned = plan(&load(PACKAGE)).unwrap();
293        let root = tempfile::TempDir::new().unwrap();
294        let out = root.path().join("out");
295        fs::write(&out, "earlier=kept\n").unwrap();
296        super::write_github_output(&planned, &out).unwrap();
297        let text = fs::read_to_string(&out).unwrap();
298        assert!(text.starts_with("earlier=kept\n"), "{text}");
299        assert!(text.contains("matrix={"), "{text}");
300    }
301
302    #[test]
303    fn github_output_does_not_fuse_onto_an_unterminated_line() {
304        let planned = plan(&load(PACKAGE)).unwrap();
305        let root = tempfile::TempDir::new().unwrap();
306        let out = root.path().join("out");
307        fs::write(&out, "earlier=kept").unwrap();
308        super::write_github_output(&planned, &out).unwrap();
309        let text = fs::read_to_string(&out).unwrap();
310        let lines: Vec<&str> = text.lines().collect();
311        assert_eq!(lines[0], "earlier=kept");
312        assert!(lines[1].starts_with("matrix={"), "{text}");
313    }
314}