1use 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#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
25pub struct CiJob {
26 pub id: String,
28 pub name: String,
30 pub machine: String,
32 pub labels: Vec<String>,
34}
35
36#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
38pub struct Matrix {
39 pub include: Vec<CiJob>,
41}
42
43#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
45pub struct CiPlan {
46 pub matrix: Matrix,
48}
49
50pub 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
95pub 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();
154 assert_eq!(planned.matrix.include[0].labels, ["ubuntu-26.04"]);
155 assert_eq!(planned.matrix.include[0].name, "verify");
156 }
157
158 #[test]
159 fn one_machine_with_three_labels_is_one_check() {
160 let planned = plan(&with(indoc::indoc! {"
161 ci:
162 verify:
163 runners: [big]
164 "}))
165 .unwrap();
166 assert_eq!(planned.matrix.include.len(), 1);
167 assert_eq!(planned.matrix.include[0].name, "verify");
168 assert_eq!(
169 planned.matrix.include[0].labels,
170 ["self-hosted", "linux", "x64"]
171 );
172 }
173
174 #[test]
175 fn two_machines_fan_one_job_into_two_named_checks() {
176 let planned = plan(&with(indoc::indoc! {"
177 ci:
178 verify:
179 runners: [linux, macos]
180 "}))
181 .unwrap();
182 assert_eq!(planned.matrix.include.len(), 2);
183 assert!(planned.matrix.include.iter().all(|row| row.id == "verify"));
184 assert_eq!(
185 planned
186 .matrix
187 .include
188 .iter()
189 .map(|row| row.name.as_str())
190 .collect::<Vec<_>>(),
191 ["verify (linux)", "verify (macos)"]
192 );
193 }
194
195 #[test]
196 fn separate_jobs_stay_separate_checks() {
197 let planned = plan(&with(indoc::indoc! {"
198 ci:
199 audit:
200 runners: [linux]
201 verify:
202 runners: [macos]
203 "}))
204 .unwrap();
205 assert_eq!(
206 planned
207 .matrix
208 .include
209 .iter()
210 .map(|row| row.name.as_str())
211 .collect::<Vec<_>>(),
212 ["audit", "verify"]
213 );
214 }
215
216 #[test]
217 fn an_undeclared_machine_is_rejected() {
218 let err = plan(&with(indoc::indoc! {"
219 ci:
220 verify:
221 runners: [windows]
222 "}))
223 .unwrap_err();
224 let text = format!("{err:#}");
225 assert!(text.contains("not declared in runners"), "{text}");
226 assert!(text.contains("big, linux, macos"), "{text}");
227 }
228
229 #[test]
230 fn an_empty_runners_list_is_rejected() {
231 let err = plan(&with(indoc::indoc! {"
232 ci:
233 verify:
234 runners: []
235 "}))
236 .unwrap_err();
237 assert!(
238 format!("{err:#}").contains("at least one machine"),
239 "{err:#}"
240 );
241 }
242
243 #[test]
244 fn a_build_field_is_not_a_ci_field() {
245 let err = Config::parse(&format!(
246 "{REGISTRY}{}",
247 indoc::indoc! {"
248 ci:
249 verify:
250 triple: x86_64-unknown-linux-gnu
251 "}
252 ))
253 .unwrap_err();
254 assert!(format!("{err:#}").contains("triple"), "{err:#}");
255 }
256
257 #[test]
258 fn a_label_is_not_a_machine_name() {
259 let err = plan(&with(indoc::indoc! {"
260 ci:
261 verify:
262 runners: [ubuntu-26.04]
263 "}))
264 .unwrap_err();
265 assert!(
266 format!("{err:#}").contains("not declared in runners"),
267 "{err:#}"
268 );
269 }
270
271 #[test]
272 fn github_output_is_one_matrix_assignment() {
273 let planned = plan(&load(PACKAGE)).unwrap();
274 let root = tempfile::TempDir::new().unwrap();
275 let out = root.path().join("out");
276 super::write_github_output(&planned, &out).unwrap();
277 let text = fs::read_to_string(&out).unwrap();
278 let matrix_line = text
279 .lines()
280 .find(|line| line.starts_with("matrix="))
281 .unwrap();
282 let json: serde_json::Value =
283 serde_json::from_str(matrix_line.trim_start_matches("matrix=")).unwrap();
284 let first = &json["include"][0];
285 assert_eq!(first["id"], "verify");
286 assert_eq!(first["name"], "verify");
287 assert_eq!(first["labels"][0], "ubuntu-26.04");
288 assert_eq!(text.lines().count(), 1, "{text}");
289 }
290
291 #[test]
292 fn github_output_keeps_what_an_earlier_step_wrote() {
293 let planned = plan(&load(PACKAGE)).unwrap();
294 let root = tempfile::TempDir::new().unwrap();
295 let out = root.path().join("out");
296 fs::write(&out, "earlier=kept\n").unwrap();
297 super::write_github_output(&planned, &out).unwrap();
298 let text = fs::read_to_string(&out).unwrap();
299 assert!(text.starts_with("earlier=kept\n"), "{text}");
300 assert!(text.contains("matrix={"), "{text}");
301 }
302
303 #[test]
304 fn github_output_does_not_fuse_onto_an_unterminated_line() {
305 let planned = plan(&load(PACKAGE)).unwrap();
306 let root = tempfile::TempDir::new().unwrap();
307 let out = root.path().join("out");
308 fs::write(&out, "earlier=kept").unwrap();
309 super::write_github_output(&planned, &out).unwrap();
310 let text = fs::read_to_string(&out).unwrap();
311 let lines: Vec<&str> = text.lines().collect();
312 assert_eq!(lines[0], "earlier=kept");
313 assert!(lines[1].starts_with("matrix={"), "{text}");
314 }
315}