1use std::path::Path;
21
22use vitrify_core::audit::{self, Finding};
23use vitrify_core::journal::{self, Event};
24use vitrify_core::model::{self, Instance, UtcTime};
25use vitrify_core::{CoreError, ledger, yamlish};
26
27use super::rows::{self, Commands};
28use crate::cmd;
29use crate::gate;
30use crate::git::Git;
31
32#[derive(Debug, Clone, PartialEq, Eq)]
34pub struct CommandResult {
35 pub passed: bool,
36 pub interrupted: bool,
38 pub output: String,
39}
40
41pub trait Runner {
45 fn run(&self, cmd: &str, cwd: &Path) -> CommandResult;
46
47 fn run_rows(&self, rows: &[String], cwd: &Path) -> Vec<CommandResult> {
49 rows.iter().map(|r| self.run(r, cwd)).collect()
50 }
51}
52
53impl<F: Fn(&str, &Path) -> CommandResult> Runner for F {
54 fn run(&self, cmd: &str, cwd: &Path) -> CommandResult {
55 self(cmd, cwd)
56 }
57}
58
59pub struct ShRunner;
61
62impl Runner for ShRunner {
63 fn run(&self, cmd: &str, cwd: &Path) -> CommandResult {
64 let ran = gate::run_command(cmd, cwd);
65 CommandResult {
66 passed: ran.ok(),
67 interrupted: ran.interrupted,
68 output: ran.output,
69 }
70 }
71}
72
73#[derive(Debug, Clone, PartialEq, Eq)]
75pub struct Failure {
76 pub command: String,
77 pub output: String,
78}
79
80#[derive(Debug, Clone, PartialEq, Eq)]
82pub struct UnitResult {
83 pub unit: String,
84 pub passed: bool,
86 pub failures: Vec<Failure>,
88}
89
90#[derive(Debug, Clone, PartialEq, Eq)]
92pub struct SuiteResult {
93 pub command: String,
94 pub passed: bool,
95 pub output: String,
96}
97
98#[derive(Debug, Clone, PartialEq, Eq)]
100pub struct Report {
101 pub commit: String,
103 pub units: Vec<UnitResult>,
105 pub skipped: Vec<String>,
107 pub suite: Option<SuiteResult>,
109 pub broken: Option<Failure>,
111 pub interrupted: bool,
113}
114
115#[derive(Debug, Clone, Default, PartialEq, Eq)]
117pub struct Edits {
118 pub commit: String,
120 pub verified: Vec<String>,
122 pub suite_pass: bool,
124}
125
126impl Edits {
127 pub fn is_empty(&self) -> bool {
129 self.verified.is_empty() && !self.suite_pass
130 }
131}
132
133impl Report {
134 pub fn edits(&self) -> Edits {
137 if self.interrupted {
138 return Edits {
139 commit: short(&self.commit).to_string(),
140 ..Default::default()
141 };
142 }
143 Edits {
144 commit: short(&self.commit).to_string(),
145 verified: self
146 .units
147 .iter()
148 .filter(|u| u.passed)
149 .map(|u| u.unit.clone())
150 .collect(),
151 suite_pass: self.suite.as_ref().is_some_and(|s| s.passed),
152 }
153 }
154}
155
156fn short(sha: &str) -> &str {
157 &sha[..7.min(sha.len())]
158}
159
160pub fn run(
166 lane: &Git,
167 commit: &str,
168 sdd_rel: &Path,
169 units: &[String],
170 runner: &dyn Runner,
171) -> Result<Report, CoreError> {
172 let full = lane
173 .resolve_commit(commit)
174 .map_err(CoreError::from)?
175 .ok_or_else(|| CoreError::refusal(1, format!("error: {commit} names no commit")))?;
176 lane.reset_hard(&full).map_err(CoreError::from)?;
177 lane.clean_all().map_err(CoreError::from)?;
178 let inst = Instance::load(cmd::resolve_sdd_in(&lane.dir, sdd_rel)?)?;
179 let tables = rows::tables(&inst)?;
180 let commands = Commands::of(&inst)?;
181 let selection = rows::for_recheck(&tables, units, commands.test.as_deref());
182
183 let mut report = Report {
184 commit: full,
185 units: Vec::new(),
186 skipped: units
187 .iter()
188 .filter(|u| !selection.units.contains(u))
189 .cloned()
190 .collect(),
191 suite: None,
192 broken: None,
193 interrupted: false,
194 };
195 let failed_all = |report: &mut Report| {
196 report.units = selection
197 .units
198 .iter()
199 .map(|u| UnitResult {
200 unit: u.clone(),
201 passed: false,
202 failures: Vec::new(),
203 })
204 .collect();
205 };
206 if selection.units.is_empty() && selection.test.is_none() {
207 return Ok(report);
208 }
209
210 for cmd in [&commands.bootstrap, &commands.build].into_iter().flatten() {
212 let ran = runner.run(cmd, &lane.dir);
213 if ran.interrupted {
214 report.interrupted = true;
215 failed_all(&mut report);
216 return Ok(report);
217 }
218 if !ran.passed {
219 report.broken = Some(Failure {
220 command: cmd.clone(),
221 output: ran.output,
222 });
223 failed_all(&mut report);
224 return Ok(report);
225 }
226 }
227
228 let results = runner.run_rows(&selection.rows, &lane.dir);
229 let result_of = |row: &str| -> Option<&CommandResult> {
230 let i = selection.rows.iter().position(|r| r == row)?;
231 results.get(i)
232 };
233 report.interrupted = results.iter().any(|r| r.interrupted);
234 for unit in &selection.units {
235 let table = tables
236 .iter()
237 .find(|t| &t.unit == unit)
238 .map(|t| t.rows.as_slice())
239 .unwrap_or_default();
240 let mut failures = Vec::new();
241 let mut passed = true;
242 for row in table {
243 match result_of(row) {
244 Some(r) if r.passed => {}
245 Some(r) => {
246 passed = false;
247 failures.push(Failure {
248 command: row.clone(),
249 output: r.output.clone(),
250 });
251 }
252 None => passed = false,
254 }
255 }
256 report.units.push(UnitResult {
257 unit: unit.clone(),
258 passed,
259 failures,
260 });
261 }
262 if report.interrupted {
263 return Ok(report);
264 }
265
266 if let Some(test) = &selection.test {
267 let ran = runner.run(test, &lane.dir);
268 if ran.interrupted {
269 report.interrupted = true;
270 return Ok(report);
271 }
272 report.suite = Some(SuiteResult {
273 command: test.clone(),
274 passed: ran.passed,
275 output: ran.output,
276 });
277 }
278 Ok(report)
279}
280
281fn append_event(inst: &Instance, mut event: Event) -> Result<(), CoreError> {
283 let handle = inst.handle();
284 let (events, _) = journal::read(&handle)?;
285 event.seq = events.last().map(|e| e.seq).unwrap_or(0) + 1;
286 if event.at.is_empty() {
287 event.at = UtcTime::now().format();
288 }
289 if event.sdd.is_empty() {
290 event.sdd = inst.meta.get_str_or("version", "0.0.0").to_string();
291 }
292 journal::append_line(&handle, &journal::render_line(&event))?;
293 Ok(())
294}
295
296pub fn apply(inst: &Instance, root: &Path, edits: &Edits) -> Result<Vec<Finding>, CoreError> {
308 if edits.is_empty() {
309 return Ok(Vec::new());
310 }
311 let stamp = model::render_stamp(
312 &UtcTime::now().format_date(),
313 inst.meta.get_str_or("version", "0.0.0"),
314 &edits.commit,
315 );
316 let handle = inst.handle();
317 for uid in &edits.verified {
318 let Some(unit) = inst.unit(uid) else {
319 continue;
320 };
321 if unit.meta.get_str_or("status", "Draft") != "Verified" {
322 continue;
323 }
324 model::rewrite_unit_meta(&handle, unit, |inner| {
325 yamlish::set_scalar_in_place(inner, "verified", &stamp)
326 })?;
327 append_event(
328 inst,
329 Event {
330 event: "verified".to_string(),
331 unit: Some(uid.clone()),
332 actor: Some(journal::RECHECK_ACTOR.to_string()),
333 commit: Some(edits.commit.clone()),
334 ..Default::default()
335 },
336 )?;
337 }
338 let stamped = Instance::load(handle)?;
339 ledger::regen(&stamped, &UtcTime::now().format_date())?;
340 let (findings, _) = audit::run(
341 &stamped,
342 root,
343 &cmd::audit_options(
344 audit::Options {
345 skip_rotten: true,
346 ..Default::default()
347 },
348 root,
349 &stamped,
350 ),
351 &gate::ShRunner,
352 UtcTime::now(),
353 )?;
354 if !findings.is_empty() {
355 return Ok(findings);
356 }
357 append_event(
358 &stamped,
359 Event {
360 event: "audit".to_string(),
361 actor: Some("audit".to_string()),
362 findings: Some(0),
363 suite: edits.suite_pass.then(|| journal::SUITE_PASS.to_string()),
364 commit: Some(edits.commit.clone()),
365 ..Default::default()
366 },
367 )?;
368 Ok(Vec::new())
369}