1use std::path::Path;
32
33use crate::check::Outcome;
34use crate::hooks::common::{fail, hl, ok, repo_root, warn};
35use crate::manifest::{normalize_command, tree_gates, TreeGate};
36
37pub const WORKFLOW_DIRS: &[&str] = &[".github/workflows", ".forgejo/workflows"];
39
40#[derive(Debug, Clone, PartialEq, Eq)]
42pub struct Problem {
43 pub file: String,
44 pub line: usize,
45 pub what: String,
46}
47
48impl std::fmt::Display for Problem {
49 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
50 if self.line == 0 {
51 write!(f, "{}: {}", self.file, self.what)
52 } else {
53 write!(f, "{}:{}: {}", self.file, self.line, self.what)
54 }
55 }
56}
57
58#[derive(Debug, Default)]
60struct Step {
61 line: usize,
62 keys: Vec<(String, String, usize)>,
65 text: String,
68}
69
70#[derive(Debug, Clone, Copy, PartialEq, Eq)]
72enum Inherited {
73 ShellBash,
75 Other(InheritKey),
77}
78
79#[derive(Debug, Clone, Copy, PartialEq, Eq)]
81enum InheritKey {
82 Env,
83 Defaults,
84}
85
86impl InheritKey {
87 fn as_str(self) -> &'static str {
88 match self {
89 InheritKey::Env => "env",
90 InheritKey::Defaults => "defaults",
91 }
92 }
93}
94
95#[derive(Debug, Default)]
96struct Job {
97 inherits: Vec<(usize, Inherited)>,
99 steps: Vec<Step>,
100}
101
102#[derive(Debug, Default)]
103struct Workflow {
104 inherits: Vec<(usize, Inherited)>,
106 jobs: Vec<Job>,
107 stray: Vec<usize>,
109}
110
111fn indent_of(line: &str) -> usize {
112 line.len() - line.trim_start_matches(' ').len()
113}
114
115fn key_of(s: &str) -> Option<(&str, &str)> {
117 let (k, v) = s.split_once(':')?;
118 let ok = !k.is_empty()
119 && k.chars()
120 .all(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '_' | '.'));
121 (ok && (v.is_empty() || v.starts_with(' '))).then(|| (k, v.trim()))
122}
123
124fn mentions_tree(line: &str) -> bool {
125 line.contains("'tree-") || line.contains("\"tree-")
126}
127
128fn classify(lines: &[&str], idx: usize) -> Inherited {
132 let key_line = lines[idx];
133 if key_of(key_line.trim()).map(|(k, _)| k) != Some("defaults") {
134 return Inherited::Other(InheritKey::Env);
135 }
136 let level = indent_of(key_line);
137 let body: Vec<&str> = lines[idx + 1..]
138 .iter()
139 .map(|l| (indent_of(l), l.trim()))
140 .filter(|(_, t)| !t.is_empty() && !t.starts_with('#'))
141 .take_while(|(ind, _)| *ind > level)
142 .map(|(_, t)| t)
143 .collect();
144 let bash = ["shell: bash", "shell: 'bash'", "shell: \"bash\""];
145 match body.as_slice() {
146 ["run:", shell] if bash.contains(shell) => Inherited::ShellBash,
147 _ => Inherited::Other(InheritKey::Defaults),
148 }
149}
150
151fn is_simple(command: &str) -> bool {
154 !command.contains(['|', ';', '&', '>', '<', '`', '(', ')']) && !command.contains("$(")
155}
156
157fn read_workflow(text: &str) -> Workflow {
158 let all: Vec<&str> = text.lines().collect();
159 let mut wf = Workflow::default();
160 let mut in_jobs = false;
161 let mut job_indent: Option<usize> = None;
162 let mut job_key_indent: Option<usize> = None;
163 let mut steps_indent: Option<usize> = None;
164 let mut dash_indent: Option<usize> = None;
165 for (i, raw) in text.lines().enumerate() {
166 let lineno = i + 1;
167 let trimmed = raw.trim();
168 if trimmed.is_empty() || trimmed.starts_with('#') {
169 continue;
170 }
171 let ind = indent_of(raw);
172 if ind == 0 {
173 in_jobs = false;
174 job_indent = None;
175 job_key_indent = None;
176 steps_indent = None;
177 dash_indent = None;
178 if let Some((k, _)) = key_of(trimmed) {
179 if k == "jobs" {
180 in_jobs = true;
181 } else if k == "env" || k == "defaults" {
182 wf.inherits.push((lineno, classify(&all, i)));
183 }
184 }
185 if mentions_tree(raw) {
186 wf.stray.push(lineno);
187 }
188 continue;
189 }
190 if !in_jobs {
191 if mentions_tree(raw) {
192 wf.stray.push(lineno);
193 }
194 continue;
195 }
196 let ji = *job_indent.get_or_insert(ind);
197 if ind <= ji {
198 job_key_indent = None;
200 steps_indent = None;
201 dash_indent = None;
202 wf.jobs.push(Job::default());
203 if mentions_tree(raw) {
204 wf.stray.push(lineno);
205 }
206 continue;
207 }
208 let Some(job) = wf.jobs.last_mut() else {
209 if mentions_tree(raw) {
210 wf.stray.push(lineno);
211 }
212 continue;
213 };
214 let jki = *job_key_indent.get_or_insert(ind);
215 if ind <= jki {
216 steps_indent = None;
218 dash_indent = None;
219 if let Some((k, _)) = key_of(trimmed) {
220 if k == "steps" {
221 steps_indent = Some(ind);
222 } else if k == "env" || k == "defaults" {
223 job.inherits.push((lineno, classify(&all, i)));
224 }
225 }
226 if mentions_tree(raw) {
227 wf.stray.push(lineno);
228 }
229 continue;
230 }
231 if steps_indent.is_none() {
232 if mentions_tree(raw) {
233 wf.stray.push(lineno);
234 }
235 continue;
236 }
237 if let Some(item) = trimmed
238 .strip_prefix("- ")
239 .or((trimmed == "-").then_some(""))
240 {
241 let di = *dash_indent.get_or_insert(ind);
242 if ind == di {
243 let mut step = Step {
244 line: lineno,
245 ..Step::default()
246 };
247 step.text.push_str(raw);
248 step.text.push('\n');
249 if let Some((k, v)) = key_of(item) {
250 step.keys.push((k.to_string(), v.to_string(), lineno));
251 }
252 job.steps.push(step);
253 continue;
254 }
255 }
256 let Some(step) = job.steps.last_mut() else {
257 if mentions_tree(raw) {
258 wf.stray.push(lineno);
259 }
260 continue;
261 };
262 step.text.push_str(raw);
263 step.text.push('\n');
264 if Some(ind) == dash_indent.map(|d| d + 2) {
266 if let Some((k, v)) = key_of(trimmed) {
267 step.keys.push((k.to_string(), v.to_string(), lineno));
268 }
269 }
270 }
271 wf
272}
273
274fn referenced(text: &str) -> Vec<String> {
276 let mut out: Vec<String> = Vec::new();
277 for quote in ['\'', '"'] {
278 let needle = format!("{quote}tree-");
279 let mut rest = text;
280 while let Some(i) = rest.find(&needle) {
281 let after = &rest[i + needle.len()..];
282 let end = after.find(quote).unwrap_or(after.len());
283 let name = &after[..end];
284 if !name.is_empty() && !out.iter().any(|n| n == name) {
285 out.push(name.to_string());
286 }
287 rest = &after[end..];
288 }
289 }
290 out
291}
292
293fn scalar(raw: &str) -> Result<String, &'static str> {
295 let v = raw.trim();
296 if v.is_empty() || v.starts_with('|') || v.starts_with('>') {
297 return Err("a block scalar — write the command on one line");
298 }
299 if v.starts_with('&') || v.starts_with('*') {
300 return Err("an anchor or alias");
301 }
302 let value = if let Some(inner) = v.strip_prefix('"') {
303 let Some(inner) = inner.strip_suffix('"') else {
304 return Err("an unterminated quoted scalar");
305 };
306 if inner.contains(['\\', '"']) {
307 return Err("a quoted scalar with escapes");
308 }
309 inner.to_string()
310 } else if let Some(inner) = v.strip_prefix('\'') {
311 let Some(inner) = inner.strip_suffix('\'') else {
312 return Err("an unterminated quoted scalar");
313 };
314 if inner.contains('\'') {
315 return Err("a quoted scalar with escapes");
316 }
317 inner.to_string()
318 } else {
319 if v.contains(" #") || v.contains(": ") || v.starts_with(['{', '[', '!', '%', '@', '`']) {
320 return Err("a plain scalar YAML may read differently — quote it");
321 }
322 v.to_string()
323 };
324 if value.contains("${{") {
325 return Err("`${{ }}` interpolation");
326 }
327 Ok(value)
328}
329
330pub fn check_texts(
332 manifest: &str,
333 gates: &[TreeGate],
334 workflows: &[(String, String)],
335) -> Vec<Problem> {
336 let mut problems = Vec::new();
337 let mut seen: Vec<&str> = Vec::new();
338 for (file, text) in workflows {
339 let wf = read_workflow(text);
340 for line in &wf.stray {
341 problems.push(Problem {
342 file: file.clone(),
343 line: *line,
344 what: "a tree gate referenced outside a step — only a step may be skipped on one"
345 .into(),
346 });
347 }
348 for job in &wf.jobs {
349 for step in &job.steps {
350 let names = referenced(&step.text);
351 if names.is_empty() {
352 continue;
353 }
354 let at = |what: String| Problem {
355 file: file.clone(),
356 line: step.line,
357 what,
358 };
359 if names.len() > 1 {
360 problems.push(at(format!(
361 "one step is gated on several tree gates ({}) — a gate proves one command",
362 names.join(", ")
363 )));
364 continue;
365 }
366 let name = &names[0];
367 let Some(gate) = gates.iter().find(|g| &g.name == name) else {
368 problems.push(at(format!("`tree-{name}` is not declared in {manifest}")));
369 continue;
370 };
371 seen.push(&gate.name);
372 let inherited: Vec<(usize, Inherited)> =
373 wf.inherits.iter().chain(&job.inherits).copied().collect();
374 if let Some((l, _)) = inherited
375 .iter()
376 .find(|(_, k)| matches!(k, Inherited::Other(_)))
377 {
378 problems.push(Problem {
379 file: file.clone(),
380 line: *l,
381 what: format!(
382 "`tree-{name}` is skipped in a job that inherits `env:` or \
383 `defaults:` — they change what `run:` does; move them onto \
384 the steps that need them"
385 ),
386 });
387 continue;
388 }
389 if let Some((l, _)) = inherited.first() {
390 if !is_simple(&gate.normalized()) {
391 problems.push(Problem {
392 file: file.clone(),
393 line: *l,
394 what: format!(
395 "`tree-{name}` inherits `shell: bash`, which is accepted only \
396 for a simple command — this one has a pipe, list, \
397 redirection or substitution"
398 ),
399 });
400 continue;
401 }
402 }
403 let mut run = None;
404 let mut bad = None;
405 for (k, v, l) in &step.keys {
406 match k.as_str() {
407 "run" => run = Some((v, *l)),
408 "env" | "shell" => {
409 bad = Some(format!("a step-level `{k}:` changes what `run:` does"))
410 }
411 "working-directory" => match (scalar(v), &gate.cwd) {
412 (Ok(dir), Some(cwd))
413 if dir.trim_end_matches('/').trim_start_matches("./")
414 == cwd.as_str() => {}
415 _ => {
416 bad = Some(
417 "`working-directory:` differs from the gate's `cwd=`".into(),
418 )
419 }
420 },
421 _ => {}
422 }
423 }
424 if bad.is_none() && gate.cwd.is_some() {
425 let has_wd = step.keys.iter().any(|(k, _, _)| k == "working-directory");
426 if !has_wd {
427 bad = Some(format!(
428 "the gate runs in `{}` (cwd=) but the step has no \
429 `working-directory:`",
430 gate.cwd.as_deref().unwrap_or("")
431 ));
432 }
433 }
434 if let Some(why) = bad {
435 problems.push(at(format!("`tree-{name}`: {why}")));
436 continue;
437 }
438 let Some((raw, line)) = run else {
439 problems.push(at(format!("`tree-{name}` gates a step with no `run:`")));
440 continue;
441 };
442 match scalar(raw) {
443 Err(why) => problems.push(Problem {
444 file: file.clone(),
445 line,
446 what: format!("`tree-{name}`: `run:` is {why}"),
447 }),
448 Ok(value) => {
449 let got = normalize_command(&value);
450 let want = gate.normalized();
451 if got != want {
452 problems.push(Problem {
453 file: file.clone(),
454 line,
455 what: format!(
456 "`tree-{name}` runs `{got}` here but `{want}` in {manifest}:{}",
457 gate.lineno
458 ),
459 });
460 }
461 }
462 }
463 }
464 }
465 }
466 for gate in gates {
467 if !seen.contains(&gate.name.as_str()) {
468 problems.push(Problem {
469 file: manifest.into(),
470 line: gate.lineno,
471 what: format!(
472 "`tree-{}` is declared but no workflow step is skipped on it",
473 gate.name
474 ),
475 });
476 }
477 }
478 problems
479}
480
481pub const BUILTIN_TEST_GATES: &[&str] = &[
483 "pre-push-cargo-test",
484 "pre-push-go-test",
485 "pre-push-pytest",
486 "pre-push-run-tests-js",
487];
488
489const NOISE: &[&str] = &["-q", "--quiet", "-v", "--verbose"];
491
492fn builtin_matches(gate: &str, command: &str) -> bool {
507 if !is_simple(command) {
508 return false;
509 }
510 let tokens: Vec<&str> = command
511 .split_whitespace()
512 .filter(|t| !NOISE.contains(t))
513 .collect();
514 match gate {
515 "pre-push-cargo-test" => {
516 tokens.starts_with(&["cargo", "test"])
517 && tokens[2..]
518 .iter()
519 .all(|t| matches!(*t, "--workspace" | "--all-features"))
520 }
521 "pre-push-go-test" => tokens == ["go", "test", "./..."],
522 "pre-push-pytest" => {
523 let rest: Vec<&str> = match tokens.as_slice() {
524 ["uv", "run", rest @ ..] => rest
525 .iter()
526 .copied()
527 .filter(|t| !matches!(*t, "--no-sync" | "--frozen"))
528 .collect(),
529 ["python" | "python3", "-m", rest @ ..] => rest.to_vec(),
530 other => other.to_vec(),
531 };
532 rest == ["pytest"]
533 }
534 "pre-push-run-tests-js" => {
535 let script = match tokens.as_slice() {
536 ["npm" | "pnpm" | "yarn", "test"] => Some("test"),
537 ["npm" | "pnpm", "run", s] => Some(*s),
538 ["pnpm" | "yarn", s] => Some(*s),
539 _ => None,
540 };
541 matches!(script, Some("typecheck" | "test:unit" | "test"))
542 }
543 _ => false,
544 }
545}
546
547fn skipped_builtin(text: &str) -> Option<&'static str> {
551 if !text.contains("!contains(") {
552 return None;
553 }
554 BUILTIN_TEST_GATES
555 .iter()
556 .copied()
557 .find(|g| text.contains(&format!("'{g}'")) || text.contains(&format!("\"{g}\"")))
558}
559
560pub fn builtin_drift_texts(workflows: &[(String, String)]) -> Vec<Problem> {
566 let mut problems = Vec::new();
567 for (file, text) in workflows {
568 let wf = read_workflow(text);
569 for job in &wf.jobs {
570 for step in &job.steps {
571 let Some(gate) = skipped_builtin(&step.text) else {
572 continue;
573 };
574 let at = |line: usize, what: String| Problem {
575 file: file.clone(),
576 line,
577 what: format!(
578 "`{gate}` {what} — CI skips this step on a signature of a \
579 different command"
580 ),
581 };
582 let inherited: Vec<(usize, Inherited)> =
583 wf.inherits.iter().chain(&job.inherits).copied().collect();
584 if let Some((l, key)) = inherited.iter().find_map(|(l, k)| match k {
585 Inherited::Other(key) => Some((l, key.as_str())),
586 Inherited::ShellBash => None,
587 }) {
588 let if_line = step
591 .keys
592 .iter()
593 .find(|(k, _, _)| k == "if")
594 .map_or(step.line, |(_, _, l)| *l);
595 problems.push(at(
596 if_line,
597 format!(
598 "is skipped by this step's `if:`, but the step inherits \
599 `{key}:` from line {l} (move it onto the other steps \
600 that need it, or drop the `if:`)"
601 ),
602 ));
603 continue;
604 }
605 let mut run = None;
606 let mut bad = None;
607 for (k, v, l) in &step.keys {
608 match k.as_str() {
609 "run" => run = Some((v, *l)),
610 "env" | "shell" | "working-directory" => {
611 bad = Some((*l, format!("gates a step with its own `{k}:`")))
612 }
613 _ => {}
614 }
615 }
616 if let Some((l, why)) = bad {
617 problems.push(at(l, why));
618 continue;
619 }
620 let Some((raw, line)) = run else {
621 problems.push(at(step.line, "gates a step with no `run:`".into()));
622 continue;
623 };
624 match scalar(raw) {
625 Err(why) => problems.push(at(line, format!("gates a `run:` that is {why}"))),
626 Ok(value) => {
627 let got = normalize_command(&value);
628 if !builtin_matches(gate, &got) {
629 problems.push(at(line, format!("gates `{got}`")));
630 }
631 }
632 }
633 }
634 }
635 }
636 problems
637}
638
639pub fn builtin_drift(root: &Path) -> Vec<Problem> {
641 builtin_drift_texts(&read_workflows(root))
642}
643
644fn read_workflows(root: &Path) -> Vec<(String, String)> {
646 let mut workflows = Vec::new();
647 for dir in WORKFLOW_DIRS {
648 let Ok(entries) = std::fs::read_dir(root.join(dir)) else {
649 continue;
650 };
651 let mut paths: Vec<_> = entries
652 .filter_map(Result::ok)
653 .map(|e| e.path())
654 .filter(|p| matches!(p.extension().and_then(|e| e.to_str()), Some("yml" | "yaml")))
655 .collect();
656 paths.sort();
657 for p in paths {
658 if let Ok(text) = std::fs::read_to_string(&p) {
659 let rel = p.strip_prefix(root).unwrap_or(&p).display().to_string();
660 workflows.push((rel, text));
661 }
662 }
663 }
664 workflows
665}
666
667pub fn check_repo(root: &Path) -> Vec<Problem> {
669 let Ok(manifest) = std::fs::read_to_string(root.join(crate::manifest::manifest_name(root)))
670 else {
671 return Vec::new();
672 };
673 let gates = tree_gates(&manifest);
674 if gates.is_empty() {
675 return Vec::new();
676 }
677 check_texts(
678 crate::manifest::manifest_name(root),
679 &gates,
680 &read_workflows(root),
681 )
682}
683
684pub fn run(settings: &crate::config::Settings) -> Outcome {
688 let root = repo_root();
689 let root = Path::new(&root);
690 let drift = builtin_drift(root);
691 for p in &drift {
692 warn(&crate::ui::sanitize(&p.to_string()));
693 }
694 let declares = std::fs::read_to_string(root.join(crate::manifest::manifest_name(root)))
695 .map(|t| !tree_gates(&t).is_empty())
696 .unwrap_or(false);
697 let problems = if declares {
698 check_repo(root)
699 } else {
700 Vec::new()
701 };
702 if problems.is_empty() {
703 return match (declares, drift.is_empty()) {
704 (_, false) => Outcome::Warned,
705 (true, true) => {
706 ok(settings, "tree gates match their CI steps");
707 Outcome::Passed
708 }
709 (false, true) => Outcome::Inert,
710 };
711 }
712 for p in &problems {
713 eprintln!(" {}", crate::ui::sanitize(&p.to_string()));
714 }
715 fail(&format!(
716 "{} tree-gate parity problem(s) — fix the workflow or the {} line; run {} to re-check",
717 problems.len(),
718 crate::manifest::manifest_name(root),
719 hl(concat!(crate::bin!(), " tree-parity"))
720 ));
721 Outcome::Failed
722}
723
724#[cfg(test)]
725mod tests {
726 use super::*;
727
728 fn drift(step_run: &str) -> Vec<Problem> {
729 let text = format!(
730 "name: ci\non:\n push:\njobs:\n test:\n runs-on: ubuntu-latest\n steps:\n - id: attest\n uses: greenharness/greensummit@v2\n - if: ${{{{ !contains(fromJSON(steps.attest.outputs.gates || '[]'), 'pre-push-cargo-test') }}}}\n {step_run}\n"
731 );
732 builtin_drift_texts(&[(".github/workflows/ci.yaml".into(), text)])
733 }
734
735 #[test]
739 fn an_inherited_env_is_reported_at_each_gated_step() {
740 let gate = "if: ${{ !contains(fromJSON(steps.attest.outputs.gates), 'pre-push-go-test') }}";
741 let text = format!(
742 "name: ci\non:\n push:\nenv:\n REGISTRY: ghcr.io\njobs:\n test:\n runs-on: ubuntu-latest\n steps:\n - id: attest\n uses: greenharness/greensummit@v2\n - name: unit\n {gate}\n run: go test ./...\n - name: again\n {gate}\n run: go test ./...\n"
743 );
744 let problems = builtin_drift_texts(&[(".github/workflows/ci.yaml".into(), text)]);
745 assert_eq!(
746 problems
747 .iter()
748 .map(|problem| problem.line)
749 .collect::<Vec<_>>(),
750 [13, 16],
751 "{problems:?}"
752 );
753 for one in &problems {
754 assert!(
755 one.what.contains(
756 "`pre-push-go-test` is skipped by this step's `if:`, but the step inherits `env:` from line 4 (move it onto the other steps that need it, or drop the `if:`)"
757 ),
758 "{problems:?}"
759 );
760 }
761
762 let text = format!(
763 "name: ci\non:\n push:\njobs:\n web:\n runs-on: ubuntu-latest\n defaults:\n run:\n working-directory: web\n steps:\n - id: attest\n uses: greenharness/greensummit@v2\n - {gate}\n run: go test ./...\n"
764 );
765 let problems = builtin_drift_texts(&[(".github/workflows/ci.yaml".into(), text)]);
766 assert_eq!(problems.len(), 1, "{problems:?}");
767 assert_eq!(problems[0].line, 13, "{problems:?}");
768 assert!(
769 problems[0]
770 .what
771 .contains("inherits `defaults:` from line 7"),
772 "{problems:?}"
773 );
774 }
775
776 #[test]
779 fn a_builtin_gate_step_is_compared_with_the_local_command() {
780 assert_eq!(drift("run: cargo test"), vec![]);
781 assert_eq!(
782 drift("run: cargo test --workspace --all-features -q"),
783 vec![]
784 );
785 let locked = drift("run: cargo test --workspace --locked");
786 assert_eq!(locked.len(), 1, "{locked:?}");
787 assert!(locked[0].what.contains("pre-push-cargo-test"), "{locked:?}");
788 assert_eq!(drift("run: make test").len(), 1);
789 assert_eq!(
790 drift("run: |\n cargo test").len(),
791 1,
792 "a block scalar differs"
793 );
794 assert_eq!(
795 drift("run: cargo test\n env:\n X: 1").len(),
796 1
797 );
798 }
799
800 #[test]
801 fn the_builtin_equivalences() {
802 assert!(builtin_matches("pre-push-go-test", "go test ./..."));
803 assert!(!builtin_matches("pre-push-go-test", "go test -race ./..."));
804 assert!(builtin_matches(
805 "pre-push-pytest",
806 "uv run --no-sync pytest"
807 ));
808 assert!(builtin_matches("pre-push-pytest", "python -m pytest -q"));
809 assert!(!builtin_matches(
810 "pre-push-pytest",
811 "uv run pytest --cov-fail-under=80"
812 ));
813 assert!(builtin_matches(
814 "pre-push-run-tests-js",
815 "pnpm run test:unit"
816 ));
817 assert!(builtin_matches("pre-push-run-tests-js", "npm test"));
818 assert!(!builtin_matches("pre-push-run-tests-js", "pnpm coverage"));
819 assert!(!builtin_matches(
820 "pre-push-cargo-test",
821 "cargo test | tee log"
822 ));
823 }
824
825 #[test]
827 fn a_step_run_when_attested_is_not_a_skipped_one() {
828 assert_eq!(
829 skipped_builtin("if: ${{ contains(fromJSON(x), 'pre-push-cargo-test') }}"),
830 None
831 );
832 assert_eq!(
833 skipped_builtin("if: ${{ !contains(fromJSON(x), 'pre-push-cargo-test') }}"),
834 Some("pre-push-cargo-test")
835 );
836 }
837
838 fn gates(text: &str) -> Vec<TreeGate> {
839 let g = tree_gates(text);
840 assert!(!g.is_empty(), "no gate parsed from {text:?}");
841 g
842 }
843
844 fn check(manifest: &str, workflow: &str) -> Vec<Problem> {
845 check_texts(
846 crate::manifest::MANIFEST,
847 &gates(manifest),
848 &[(
849 ".forgejo/workflows/ci.yaml".to_string(),
850 workflow.to_string(),
851 )],
852 )
853 }
854
855 const ESLINT: &str = "tree eslint eslint * attest npm run lint -- {cache}";
856
857 fn wf(step_run: &str) -> String {
858 format!(
859 "name: ci\non:\n push:\njobs:\n checks:\n runs-on: ubuntu-latest\n steps:\n - uses: actions/checkout@v4\n - id: attest\n uses: greenharness/greensummit@v2\n - name: Lint\n if: ${{{{ !contains(fromJSON(steps.attest.outputs.gates || '[]'), 'tree-eslint') }}}}\n {step_run}\n"
860 )
861 }
862
863 #[test]
864 fn parity_matching_run_passes() {
865 assert_eq!(check(ESLINT, &wf("run: npm run lint")), vec![]);
866 }
867
868 #[test]
869 fn parity_quoted_run_passes() {
870 assert_eq!(check(ESLINT, &wf("run: 'npm run lint'")), vec![]);
871 }
872
873 #[test]
874 fn parity_drifted_run_fails() {
875 let p = check(ESLINT, &wf("run: npm run lint -- --max-warnings 0"));
876 assert_eq!(p.len(), 1, "{p:?}");
877 assert!(p[0]
878 .what
879 .contains("runs `npm run lint -- --max-warnings 0` here"));
880 }
881
882 #[test]
883 fn parity_block_scalar_rejected() {
884 let p = check(ESLINT, &wf("run: |\n npm run lint"));
885 assert_eq!(p.len(), 1, "{p:?}");
886 assert!(p[0].what.contains("block scalar"));
887 }
888
889 #[test]
890 fn parity_anchor_rejected() {
891 let p = check(ESLINT, &wf("run: *lint"));
892 assert!(p[0].what.contains("anchor"), "{p:?}");
893 }
894
895 #[test]
896 fn parity_interpolation_rejected() {
897 let p = check(ESLINT, &wf("run: npm run ${{ matrix.task }}"));
898 assert!(p[0].what.contains("interpolation"), "{p:?}");
899 }
900
901 #[test]
902 fn parity_step_env_rejected() {
903 let p = check(
904 ESLINT,
905 &wf("env:\n CI: '1'\n run: npm run lint"),
906 );
907 assert!(p[0].what.contains("step-level `env:`"), "{p:?}");
908 }
909
910 #[test]
911 fn parity_step_shell_rejected() {
912 let p = check(ESLINT, &wf("shell: bash\n run: npm run lint"));
913 assert!(p[0].what.contains("step-level `shell:`"), "{p:?}");
914 }
915
916 #[test]
917 fn parity_undeclared_working_directory_rejected() {
918 let p = check(
919 ESLINT,
920 &wf("working-directory: web\n run: npm run lint"),
921 );
922 assert!(p[0].what.contains("working-directory"), "{p:?}");
923 }
924
925 #[test]
926 fn parity_declared_cwd_passes() {
927 let p = check(
928 "tree eslint eslint * attest cwd=web npm run lint",
929 &wf("working-directory: web\n run: npm run lint"),
930 );
931 assert_eq!(p, vec![]);
932 }
933
934 #[test]
935 fn parity_cwd_without_working_directory_rejected() {
936 let p = check(
937 "tree eslint eslint * attest cwd=web npm run lint",
938 &wf("run: npm run lint"),
939 );
940 assert!(p[0].what.contains("no `working-directory:`"), "{p:?}");
941 }
942
943 #[test]
944 fn parity_job_env_rejected() {
945 let w = wf("run: npm run lint").replace(
946 " runs-on: ubuntu-latest\n",
947 " runs-on: ubuntu-latest\n env:\n NODE_ENV: test\n",
948 );
949 let p = check(ESLINT, &w);
950 assert!(p[0].what.contains("inherits"), "{p:?}");
951 }
952
953 #[test]
954 fn parity_job_defaults_rejected() {
955 let w = wf("run: npm run lint").replace(
956 " runs-on: ubuntu-latest\n",
957 " runs-on: ubuntu-latest\n defaults:\n run:\n working-directory: web\n",
958 );
959 let p = check(ESLINT, &w);
960 assert!(p[0].what.contains("inherits"), "{p:?}");
961 }
962
963 #[test]
964 fn parity_workflow_shell_bash_accepted_for_a_simple_command() {
965 let w = wf("run: npm run lint")
966 .replace("jobs:\n", "defaults:\n run:\n shell: bash\njobs:\n");
967 assert_eq!(check(ESLINT, &w), vec![]);
968 }
969
970 #[test]
971 fn parity_job_shell_bash_accepted_for_a_simple_command() {
972 let w = wf("run: npm run lint").replace(
973 " runs-on: ubuntu-latest\n",
974 " runs-on: ubuntu-latest\n defaults:\n run:\n shell: bash\n",
975 );
976 assert_eq!(check(ESLINT, &w), vec![]);
977 }
978
979 #[test]
980 fn parity_shell_bash_rejected_for_a_pipeline() {
981 let w = wf("run: npm run lint | tee lint.log")
982 .replace("jobs:\n", "defaults:\n run:\n shell: bash\njobs:\n");
983 let p = check(
984 "tree eslint eslint * attest npm run lint | tee lint.log",
985 &w,
986 );
987 assert!(p[0].what.contains("simple command"), "{p:?}");
988 }
989
990 #[test]
991 fn parity_other_shell_rejected() {
992 let w =
993 wf("run: npm run lint").replace("jobs:\n", "defaults:\n run:\n shell: sh\njobs:\n");
994 let p = check(ESLINT, &w);
995 assert!(p[0].what.contains("inherits `env:` or"), "{p:?}");
996 }
997
998 #[test]
999 fn parity_shell_bash_plus_working_directory_rejected() {
1000 let w = wf("run: npm run lint").replace(
1001 "jobs:\n",
1002 "defaults:\n run:\n shell: bash\n working-directory: web\njobs:\n",
1003 );
1004 let p = check(ESLINT, &w);
1005 assert!(p[0].what.contains("inherits `env:` or"), "{p:?}");
1006 }
1007
1008 #[test]
1009 fn parity_workflow_env_still_rejected_beside_shell_bash() {
1010 let w = wf("run: npm run lint").replace(
1011 "jobs:\n",
1012 "defaults:\n run:\n shell: bash\nenv:\n CI: '1'\njobs:\n",
1013 );
1014 let p = check(ESLINT, &w);
1015 assert!(p[0].what.contains("inherits `env:` or"), "{p:?}");
1016 }
1017
1018 #[test]
1019 fn parity_undeclared_gate_rejected() {
1020 let p = check(
1021 "tree prettier prettier * attest npx prettier --check .",
1022 &wf("run: npm run lint"),
1023 );
1024 assert!(
1025 p.iter()
1026 .any(|p| p.what.contains("`tree-eslint` is not declared")),
1027 "{p:?}"
1028 );
1029 assert!(
1030 p.iter().any(|p| p.what.contains("no workflow step")),
1031 "{p:?}"
1032 );
1033 }
1034
1035 #[test]
1036 fn parity_declared_gate_without_step_rejected() {
1037 let p = check(
1038 ESLINT,
1039 "name: ci\njobs:\n a:\n steps:\n - run: true\n",
1040 );
1041 assert_eq!(p.len(), 1, "{p:?}");
1042 assert!(p[0].what.contains("no workflow step is skipped on it"));
1043 }
1044
1045 #[test]
1046 fn parity_job_level_reference_rejected() {
1047 let w = "name: ci\njobs:\n lint:\n if: ${{ !contains(fromJSON(needs.a.outputs.gates), 'tree-eslint') }}\n steps:\n - run: npm run lint\n";
1048 let p = check(ESLINT, w);
1049 assert!(p.iter().any(|p| p.what.contains("outside a step")), "{p:?}");
1050 }
1051
1052 #[test]
1053 fn parity_two_gates_on_one_step_rejected() {
1054 let w = wf("run: npm run lint").replace(
1055 "'tree-eslint') }}",
1056 "'tree-eslint') && !contains(fromJSON(steps.attest.outputs.gates), 'tree-prettier') }}",
1057 );
1058 let p = check(
1059 "tree eslint eslint * attest npm run lint\ntree prettier prettier * attest npx prettier --check .",
1060 &w,
1061 );
1062 let several = p
1063 .iter()
1064 .find(|p| p.what.contains("several tree gates"))
1065 .unwrap_or_else(|| panic!("{p:?}"));
1066 assert_eq!(several.line, 11, "{several:?}");
1069 }
1070}