1use std::collections::{BTreeMap, BTreeSet};
32use std::path::{Path, PathBuf};
33
34use vitrify_core::CoreError;
35use vitrify_core::graph::Node;
36
37use crate::gate::{self, Ran};
38use crate::git::Git;
39
40pub trait Runner: Send + Sync {
43 fn run(&self, cmd: &str, dir: &Path) -> Ran;
44}
45
46pub struct ShellRunner;
49
50impl Runner for ShellRunner {
51 fn run(&self, cmd: &str, dir: &Path) -> Ran {
52 gate::run_command(cmd, dir)
53 }
54}
55
56impl<F> Runner for F
57where
58 F: Fn(&str, &Path) -> Ran + Send + Sync,
59{
60 fn run(&self, cmd: &str, dir: &Path) -> Ran {
61 self(cmd, dir)
62 }
63}
64
65pub trait Prepare: Send + Sync {
68 fn prepare(&self, commit: &str) -> Result<PathBuf, CoreError>;
69}
70
71#[derive(Debug, Clone)]
79pub struct PristineCheckout {
80 pub primary: Git,
82 pub path: PathBuf,
83}
84
85impl PristineCheckout {
86 pub fn new(primary: Git, path: impl Into<PathBuf>) -> PristineCheckout {
87 PristineCheckout {
88 primary,
89 path: path.into(),
90 }
91 }
92
93 fn reset(&self, commit: &str) -> Result<(), CoreError> {
94 let wt = self.primary.at(&self.path);
95 let _ = wt.merge_abort();
97 wt.reset_hard(commit).map_err(CoreError::from)?;
98 wt.clean_all().map_err(CoreError::from)
99 }
100
101 fn create(&self, commit: &str) -> Result<(), CoreError> {
102 if let Some(parent) = self.path.parent() {
103 fs_err::create_dir_all(parent).map_err(|e| CoreError::Io {
104 path: parent.to_path_buf(),
105 source: e,
106 })?;
107 }
108 self.primary
109 .worktree_add(&self.path, commit, true)
110 .map_err(CoreError::from)
111 }
112}
113
114impl Prepare for PristineCheckout {
115 fn prepare(&self, commit: &str) -> Result<PathBuf, CoreError> {
116 if self.path.join(".git").exists() && self.reset(commit).is_ok() {
117 return Ok(self.path.clone());
118 }
119 self.primary
124 .worktree_remove(&self.path)
125 .map_err(CoreError::from)?;
126 if self.path.exists() {
127 fs_err::remove_dir_all(&self.path).map_err(|e| CoreError::Io {
128 path: self.path.clone(),
129 source: e,
130 })?;
131 }
132 self.create(commit)?;
133 self.reset(commit)?;
134 Ok(self.path.clone())
135 }
136}
137
138#[derive(Debug, Clone, PartialEq, Eq)]
140pub struct OnBase {
141 pub row: String,
142 pub passed: bool,
143 pub output: String,
145}
146
147#[derive(Debug, Clone, Default, PartialEq, Eq)]
149pub struct Verdict {
150 pub broken: Vec<String>,
153 pub rotten_rows: Vec<String>,
155 pub rotten: BTreeMap<Node, Vec<String>>,
158 pub base_unusable: Option<String>,
161}
162
163impl Verdict {
164 pub fn batch_clean(&self) -> bool {
167 self.broken.is_empty()
168 }
169}
170
171pub fn classify(
177 failed: &[String],
178 rows: &BTreeMap<Node, Vec<String>>,
179 passed_on_base: &BTreeMap<String, bool>,
180) -> Verdict {
181 let mut out = Verdict::default();
182 let mut seen: BTreeSet<&str> = BTreeSet::new();
183 for row in failed {
184 if !seen.insert(row) {
185 continue;
186 }
187 if passed_on_base.get(row).copied().unwrap_or(true) {
188 out.broken.push(row.clone());
189 } else {
190 out.rotten_rows.push(row.clone());
191 }
192 }
193 for (node, unit_rows) in rows {
194 let mine: Vec<String> = out
195 .rotten_rows
196 .iter()
197 .filter(|r| unit_rows.contains(r))
198 .cloned()
199 .collect();
200 if !mine.is_empty() {
201 out.rotten.insert(node.clone(), mine);
202 }
203 }
204 out
205}
206
207#[derive(Debug, Clone, PartialEq, Eq)]
210pub enum Judged {
211 Done {
212 verdict: Verdict,
213 on_base: Vec<OnBase>,
214 },
215 Interrupted,
218}
219
220pub fn judge(
227 failed: &[String],
228 rows: &BTreeMap<Node, Vec<String>>,
229 base: &str,
230 setup: &[String],
231 prepare: &dyn Prepare,
232 runner: &dyn Runner,
233) -> Result<Judged, CoreError> {
234 let distinct: Vec<String> = {
235 let mut seen = BTreeSet::new();
236 failed
237 .iter()
238 .filter(|r| seen.insert(r.as_str()))
239 .cloned()
240 .collect()
241 };
242 if distinct.is_empty() {
243 return Ok(Judged::Done {
244 verdict: Verdict::default(),
245 on_base: Vec::new(),
246 });
247 }
248 let dir = prepare.prepare(base)?;
249 for cmd in setup {
250 let ran = runner.run(cmd, &dir);
251 if ran.interrupted {
252 return Ok(Judged::Interrupted);
253 }
254 if !ran.ok() {
255 let why = format!("`{cmd}` failed on the base (exit {})", ran.code);
256 let mut verdict = classify(&distinct, rows, &BTreeMap::new());
257 verdict.base_unusable = Some(why);
258 return Ok(Judged::Done {
259 verdict,
260 on_base: Vec::new(),
261 });
262 }
263 }
264 let mut on_base = Vec::new();
265 let mut passed: BTreeMap<String, bool> = BTreeMap::new();
266 for row in &distinct {
267 let ran = runner.run(row, &dir);
268 if ran.interrupted {
269 return Ok(Judged::Interrupted);
270 }
271 passed.insert(row.clone(), ran.ok());
272 on_base.push(OnBase {
273 row: row.clone(),
274 passed: ran.ok(),
275 output: ran.output,
276 });
277 }
278 Ok(Judged::Done {
279 verdict: classify(&distinct, rows, &passed),
280 on_base,
281 })
282}
283
284#[cfg(test)]
285mod tests {
286 use super::*;
287 use std::sync::Mutex;
288
289 fn ran(code: i32) -> Ran {
290 Ran {
291 code,
292 output: format!("exit {code}"),
293 interrupted: false,
294 }
295 }
296
297 fn rows() -> BTreeMap<Node, Vec<String>> {
298 let mut m = BTreeMap::new();
299 m.insert(
300 Node::new("api", "U-001"),
301 vec!["row-a".to_string(), "row-b".to_string()],
302 );
303 m.insert(Node::new("api", "U-002"), vec!["row-b".to_string()]);
304 m.insert(Node::new("core", "U-001"), vec!["row-c".to_string()]);
305 m
306 }
307
308 struct Fixed(Mutex<Vec<String>>);
310
311 impl Prepare for Fixed {
312 fn prepare(&self, commit: &str) -> Result<PathBuf, CoreError> {
313 self.0.lock().unwrap().push(commit.to_string());
314 Ok(PathBuf::from("/nowhere"))
315 }
316 }
317
318 struct Script {
321 failing: Vec<&'static str>,
322 interrupt: Option<&'static str>,
323 log: Mutex<Vec<String>>,
324 }
325
326 impl Runner for Script {
327 fn run(&self, cmd: &str, _dir: &Path) -> Ran {
328 self.log.lock().unwrap().push(cmd.to_string());
329 if self.interrupt == Some(cmd) {
330 return Ran {
331 code: -1,
332 output: String::new(),
333 interrupted: true,
334 };
335 }
336 ran(if self.failing.contains(&cmd) { 1 } else { 0 })
337 }
338 }
339
340 fn script(failing: &[&'static str]) -> Script {
341 Script {
342 failing: failing.to_vec(),
343 interrupt: None,
344 log: Mutex::new(Vec::new()),
345 }
346 }
347
348 #[test]
349 fn a_row_that_passes_on_the_base_is_the_batchs() {
350 let base: BTreeMap<String, bool> = [("row-a".to_string(), true)].into();
351 let v = classify(&["row-a".to_string()], &rows(), &base);
352 assert_eq!(v.broken, vec!["row-a"]);
353 assert!(v.rotten.is_empty());
354 assert!(!v.batch_clean());
355 }
356
357 #[test]
358 fn a_row_that_fails_on_the_base_makes_every_unit_it_belongs_to_rotten() {
359 let base: BTreeMap<String, bool> =
360 [("row-b".to_string(), false), ("row-c".to_string(), true)].into();
361 let v = classify(&["row-b".to_string(), "row-c".to_string()], &rows(), &base);
362 assert_eq!(v.broken, vec!["row-c"]);
363 assert_eq!(v.rotten_rows, vec!["row-b"]);
364 assert_eq!(
365 v.rotten.keys().cloned().collect::<Vec<_>>(),
366 vec![Node::new("api", "U-001"), Node::new("api", "U-002")]
367 );
368 assert_eq!(v.rotten[&Node::new("api", "U-001")], vec!["row-b"]);
369 }
370
371 #[test]
372 fn only_rotten_rows_leave_the_batch_clean() {
373 let base: BTreeMap<String, bool> = [("row-c".to_string(), false)].into();
374 let v = classify(&["row-c".to_string(), "row-c".to_string()], &rows(), &base);
375 assert!(v.batch_clean());
376 assert_eq!(v.rotten_rows, vec!["row-c"]);
377 assert_eq!(
378 v.rotten.keys().cloned().collect::<Vec<_>>(),
379 vec![Node::new("core", "U-001")]
380 );
381 }
382
383 #[test]
384 fn a_row_with_no_answer_from_the_base_is_blamed_on_the_batch() {
385 let v = classify(&["row-a".to_string()], &rows(), &BTreeMap::new());
386 assert_eq!(v.broken, vec!["row-a"]);
387 }
388
389 #[test]
390 fn judge_runs_setup_then_each_failed_row_once_on_the_base() {
391 let prep = Fixed(Mutex::new(Vec::new()));
392 let run = script(&["row-b"]);
393 let failed = vec![
394 "row-a".to_string(),
395 "row-b".to_string(),
396 "row-a".to_string(),
397 ];
398 let setup = vec!["bootstrap".to_string(), "build".to_string()];
399 let Judged::Done { verdict, on_base } =
400 judge(&failed, &rows(), "base1", &setup, &prep, &run).unwrap()
401 else {
402 panic!("interrupted");
403 };
404 assert_eq!(*prep.0.lock().unwrap(), vec!["base1"]);
405 assert_eq!(
406 *run.log.lock().unwrap(),
407 vec!["bootstrap", "build", "row-a", "row-b"]
408 );
409 assert_eq!(verdict.broken, vec!["row-a"]);
410 assert_eq!(verdict.rotten_rows, vec!["row-b"]);
411 assert_eq!(on_base.len(), 2);
412 assert!(on_base[0].passed && !on_base[1].passed);
413 }
414
415 #[test]
416 fn a_base_that_does_not_build_blames_the_batch() {
417 let prep = Fixed(Mutex::new(Vec::new()));
418 let run = script(&["build", "row-a"]);
419 let setup = vec!["build".to_string()];
420 let Judged::Done { verdict, .. } =
421 judge(&["row-a".to_string()], &rows(), "b", &setup, &prep, &run).unwrap()
422 else {
423 panic!("interrupted");
424 };
425 assert_eq!(verdict.broken, vec!["row-a"]);
426 assert!(verdict.base_unusable.unwrap().contains("`build` failed"));
427 assert_eq!(*run.log.lock().unwrap(), vec!["build"]);
428 }
429
430 #[test]
431 fn an_interrupt_decides_nothing() {
432 let prep = Fixed(Mutex::new(Vec::new()));
433 let mut run = script(&[]);
434 run.interrupt = Some("row-a");
435 let j = judge(&["row-a".to_string()], &rows(), "b", &[], &prep, &run).unwrap();
436 assert_eq!(j, Judged::Interrupted);
437 }
438
439 #[test]
440 fn nothing_failed_runs_nothing() {
441 let prep = Fixed(Mutex::new(Vec::new()));
442 let run = script(&[]);
443 let j = judge(&[], &rows(), "b", &["build".to_string()], &prep, &run).unwrap();
444 assert!(matches!(j, Judged::Done { verdict, .. } if verdict.batch_clean()));
445 assert!(prep.0.lock().unwrap().is_empty());
446 assert!(run.log.lock().unwrap().is_empty());
447 }
448}