1use vitrify_core::CoreError;
23use vitrify_core::model::{self, Instance};
24
25use crate::gate;
26
27#[derive(Debug, Clone, PartialEq, Eq)]
29pub struct UnitTable {
30 pub unit: String,
31 pub verified: bool,
33 pub rows: Vec<String>,
35}
36
37pub fn tables(inst: &Instance) -> Result<Vec<UnitTable>, CoreError> {
39 inst.units
40 .iter()
41 .map(|u| {
42 Ok(UnitTable {
43 unit: u.unit.clone(),
44 verified: u.meta.get_str_or("status", "Draft") == "Verified",
45 rows: gate::verification_table(inst, u)?,
46 })
47 })
48 .collect()
49}
50
51#[derive(Debug, Clone, Default, PartialEq, Eq)]
58pub struct Commands {
59 pub bootstrap: Option<String>,
60 pub build: Option<String>,
61 pub test: Option<String>,
62 pub lint: Option<String>,
63}
64
65impl Commands {
66 pub fn parse(core_text: &str) -> Commands {
68 let mut out = Commands::default();
69 for line in commands_lines(core_text) {
70 let Some(rest) = line.trim_start().strip_prefix("- ") else {
71 continue;
72 };
73 let Some((name, value)) = rest.split_once(':') else {
74 continue;
75 };
76 let cmd = value
77 .split('`')
78 .nth(1)
79 .map(str::trim)
80 .filter(|c| !c.is_empty())
81 .map(str::to_string);
82 match name.trim().to_lowercase().as_str() {
83 "bootstrap" => out.bootstrap = cmd,
84 "build" => out.build = cmd,
85 "test" => out.test = cmd,
86 "lint" => out.lint = cmd,
87 _ => {}
88 }
89 }
90 out
91 }
92
93 pub fn of(inst: &Instance) -> Result<Commands, CoreError> {
95 Ok(Commands::parse(&model::read_text(&inst.file)?))
96 }
97}
98
99fn heading(line: &str) -> Option<(usize, &str)> {
101 let level = line.bytes().take_while(|&b| b == b'#').count();
102 if !(1..=6).contains(&level) {
103 return None;
104 }
105 let rest = &line[level..];
106 if !(rest.is_empty() || rest.starts_with(' ') || rest.starts_with('\t')) {
107 return None;
108 }
109 Some((level, rest.trim().trim_end_matches('#').trim_end()))
110}
111
112fn commands_lines(core_text: &str) -> Vec<&str> {
116 let mut out = Vec::new();
117 let mut fence: Option<&str> = None;
118 let mut at = 0;
120 for line in core_text.lines() {
121 let trimmed = line.trim_start();
122 if let Some(open) = fence {
123 if trimmed.starts_with(open) {
124 fence = None;
125 }
126 if at == 2 {
127 out.push(line);
128 }
129 continue;
130 }
131 if trimmed.starts_with("```") || trimmed.starts_with("~~~") {
132 fence = Some(&trimmed[..3]);
133 if at == 2 {
134 out.push(line);
135 }
136 continue;
137 }
138 if let Some((level, text)) = heading(line) {
139 at = match at {
140 0 if level == 2 && text == "Technology Decisions" => 1,
141 1 if level <= 2 => 3,
142 1 if level == 3 && text == "Commands" => 2,
143 2 if level <= 3 => 3,
144 other => other,
145 };
146 if at == 3 {
147 break;
148 }
149 continue;
150 }
151 if at == 2 {
152 out.push(line);
153 }
154 }
155 out
156}
157
158#[derive(Debug, Clone, Default, PartialEq, Eq)]
160pub struct Selection {
161 pub units: Vec<String>,
163 pub rows: Vec<String>,
165 pub test: Option<String>,
168}
169
170impl Selection {
171 fn take(&mut self, tables: &[UnitTable], unit: &str) {
173 if self.units.iter().any(|u| u == unit) {
174 return;
175 }
176 let Some(t) = tables.iter().find(|t| t.unit == unit) else {
177 return;
178 };
179 self.units.push(t.unit.clone());
180 for row in &t.rows {
181 if !self.rows.contains(row) {
182 self.rows.push(row.clone());
183 }
184 }
185 }
186
187 pub fn is_empty(&self) -> bool {
189 self.rows.is_empty() && self.test.is_none()
190 }
191}
192
193fn is_verified(tables: &[UnitTable], unit: &str) -> bool {
195 tables.iter().any(|t| t.unit == unit && t.verified)
196}
197
198pub fn for_gate(
202 tables: &[UnitTable],
203 merged: &[String],
204 dirty: &[String],
205 test: Option<&str>,
206) -> Selection {
207 let mut sel = Selection::default();
208 for unit in merged {
209 sel.take(tables, unit);
210 }
211 match test {
212 Some(test) => {
213 for unit in dirty {
214 if is_verified(tables, unit) {
215 sel.take(tables, unit);
216 }
217 }
218 sel.test = Some(test.to_string());
219 }
220 None => {
221 for t in tables.iter().filter(|t| t.verified) {
222 sel.take(tables, &t.unit);
223 }
224 }
225 }
226 sel
227}
228
229pub fn for_preflight(tables: &[UnitTable], dirty: &[String]) -> Selection {
232 let mut sel = Selection::default();
233 for unit in dirty {
234 if is_verified(tables, unit) {
235 sel.take(tables, unit);
236 }
237 }
238 sel
239}
240
241pub fn for_recheck(tables: &[UnitTable], dirty: &[String], test: Option<&str>) -> Selection {
244 let mut sel = for_preflight(tables, dirty);
245 sel.test = test.map(str::to_string);
246 sel
247}
248
249#[cfg(test)]
250mod tests {
251 use super::*;
252
253 fn t(unit: &str, verified: bool, rows: &[&str]) -> UnitTable {
254 UnitTable {
255 unit: unit.into(),
256 verified,
257 rows: rows.iter().map(|r| r.to_string()).collect(),
258 }
259 }
260
261 fn ids(v: &[&str]) -> Vec<String> {
262 v.iter().map(|s| s.to_string()).collect()
263 }
264
265 fn sdd() -> Vec<UnitTable> {
268 vec![
269 t("U-001", false, &["test -f a", "check shared"]),
270 t("U-002", true, &["test -f b"]),
271 t("U-003", true, &["check shared", "test -f c"]),
272 t("U-004", false, &["test -f d"]),
273 ]
274 }
275
276 #[test]
277 fn a_gate_runs_the_merged_and_the_dirty_rows_then_the_suite() {
278 let sel = for_gate(
279 &sdd(),
280 &ids(&["U-001"]),
281 &ids(&["U-003", "U-004"]),
282 Some("make test"),
283 );
284 assert_eq!(sel.units, ids(&["U-001", "U-003"]));
285 assert_eq!(sel.rows, ids(&["test -f a", "check shared", "test -f c"]));
287 assert_eq!(sel.test.as_deref(), Some("make test"));
288 }
289
290 #[test]
291 fn a_gate_with_nothing_dirty_runs_the_merged_rows_and_the_suite() {
292 let sel = for_gate(&sdd(), &ids(&["U-004"]), &[], Some("make test"));
293 assert_eq!(sel.units, ids(&["U-004"]));
294 assert_eq!(sel.rows, ids(&["test -f d"]));
295 assert_eq!(sel.test.as_deref(), Some("make test"));
296 }
297
298 #[test]
299 fn without_a_test_command_a_gate_runs_every_verified_unit() {
300 let sel = for_gate(&sdd(), &ids(&["U-001"]), &[], None);
302 assert_eq!(sel.units, ids(&["U-001", "U-002", "U-003"]));
303 assert_eq!(
304 sel.rows,
305 ids(&["test -f a", "check shared", "test -f b", "test -f c"])
306 );
307 assert_eq!(sel.test, None);
308 }
309
310 #[test]
311 fn a_merged_unit_listed_dirty_too_is_taken_once() {
312 let sel = for_gate(
313 &sdd(),
314 &ids(&["U-002"]),
315 &ids(&["U-002", "U-003"]),
316 Some("t"),
317 );
318 assert_eq!(sel.units, ids(&["U-002", "U-003"]));
319 assert_eq!(sel.rows, ids(&["test -f b", "check shared", "test -f c"]));
320 }
321
322 #[test]
323 fn a_preflight_runs_dirty_verified_rows_only() {
324 let sel = for_preflight(&sdd(), &ids(&["U-003", "U-004", "U-009"]));
325 assert_eq!(sel.units, ids(&["U-003"]));
326 assert_eq!(sel.rows, ids(&["check shared", "test -f c"]));
327 assert_eq!(sel.test, None);
328 assert!(for_preflight(&sdd(), &[]).is_empty());
329 }
330
331 #[test]
332 fn a_recheck_runs_dirty_rows_then_the_suite() {
333 let sel = for_recheck(&sdd(), &ids(&["U-003", "U-002"]), Some("t"));
334 assert_eq!(sel.units, ids(&["U-003", "U-002"]));
336 assert_eq!(sel.rows, ids(&["check shared", "test -f c", "test -f b"]));
337 assert_eq!(sel.test.as_deref(), Some("t"));
338 let none = for_recheck(&sdd(), &[], Some("t"));
339 assert!(none.rows.is_empty());
340 assert!(!none.is_empty());
341 assert!(for_recheck(&sdd(), &[], None).is_empty());
342 }
343
344 #[test]
345 fn commands_parse_the_commands_section() {
346 let text = "# x\n\n## Technology Decisions\n\nT.\n\n### Commands\n\n- Bootstrap: `npm ci`\n- Build: ``\n- Test: `npm test` (whole suite)\n\n## Next\n\n- Lint: `nope`\n";
347 let c = Commands::parse(text);
348 assert_eq!(c.bootstrap.as_deref(), Some("npm ci"));
349 assert_eq!(c.build, None);
350 assert_eq!(c.test.as_deref(), Some("npm test"));
351 assert_eq!(c.lint, None);
352 }
353
354 const SINGLE: &str = "# s\n\n## Ground Rules\n\n### Commands\n\n- Lint: `ground`\n\n## Technology Decisions\n\nT.\n\n### Tools\n\n- Build: `tools`\n\n### Commands\n\n- Bootstrap: `true`\n- Build: `make`\n- Test: `make test`\n\n```sh\n# Commands\n- Lint: `fenced`\n```\n\n#### Notes\n\n- Lint: `cargo clippy`\n\n### Commands\n\n- Build: `second`\n\n## Work Units\n\n### U-001 — a\n\n#### Commands\n\n- Build: `rm -rf /tmp/x`\n\n# Commands\n\n- Test: `evil`\n";
357
358 #[test]
359 fn a_commands_heading_outside_section_5_is_not_read() {
360 let c = Commands::parse(SINGLE);
361 assert_eq!(c.build.as_deref(), Some("make"));
364 assert_eq!(c.test.as_deref(), Some("make test"));
365 assert_eq!(c.bootstrap.as_deref(), Some("true"));
366 assert_eq!(c.lint.as_deref(), Some("cargo clippy"));
368 }
369
370 #[test]
371 fn the_first_commands_under_technology_decisions_wins() {
372 assert_eq!(Commands::parse(SINGLE).build.as_deref(), Some("make"));
374 assert_eq!(
376 Commands::parse("# x\n\n### Commands\n\n- Build: `make`\n"),
377 Commands::default()
378 );
379 assert_eq!(
381 Commands::parse("## Technology Decisions\n\n## Commands\n\n- Build: `make`\n"),
382 Commands::default()
383 );
384 }
385
386 #[test]
387 fn every_fixture_and_the_example_parse_their_commands() {
388 fn walk(dir: &std::path::Path, out: &mut Vec<std::path::PathBuf>) {
391 let mut entries: Vec<_> = std::fs::read_dir(dir)
392 .unwrap()
393 .map(|e| e.unwrap().path())
394 .collect();
395 entries.sort();
396 for p in entries {
397 if p.is_dir() {
398 walk(&p, out);
399 } else if p.extension().is_some_and(|e| e == "md") {
400 out.push(p);
401 }
402 }
403 }
404 let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures");
405 let mut files = Vec::new();
406 walk(&root, &mut files);
407 let mut seen = 0;
408 for f in files {
409 let text = model::read_text(&f).unwrap();
410 if !text.lines().any(|l| l == "### Commands") {
411 continue;
412 }
413 seen += 1;
414 let c = Commands::parse(&text);
415 assert!(
416 c.bootstrap.is_some() && c.build.is_some() && c.test.is_some() && c.lint.is_some(),
417 "{}: {c:?}",
418 f.display()
419 );
420 }
421 assert!(seen > 20, "{seen} fixtures");
422 let calc = model::read_text(&root.join("example/specs/calc/sdd.md")).unwrap();
423 assert_eq!(
424 Commands::parse(&calc).test.as_deref(),
425 Some("python3 -m unittest discover -s tests -t .")
426 );
427 }
428}