Skip to main content

greengate_runtime/hooks/
tree_parity.rs

1//! pre-commit-tree-parity — a CI step skipped on `tree-<name>` must run exactly
2//! that gate's command (ADR-0024, `ci.skip-needs-the-same-command`).
3//!
4//! An attestation names a gate, and a gate is worth only the command behind
5//! it. If a workflow's gated `run:` drifts from the `tree` line in
6//! `amont.conf`, CI keeps skipping a step whose command nobody proved. This
7//! check compares the two on every commit that touches either, and CI runs it
8//! too (`amont tree-parity`, never skipped), so a `--no-verify` drift still
9//! fails.
10//!
11//! amont has no dependencies, so this is not a YAML parser. It reads the one
12//! shape workflow files take — `jobs:` → a job → `steps:` → `- ` items — line
13//! by line, and **fails closed**: anything it cannot read with certainty on a
14//! gated step is a problem, never a guess. That covers:
15//!
16//! - a block scalar;
17//! - an anchor or alias;
18//! - a quoted form with escapes;
19//! - `${{ }}` interpolation;
20//! - a step-level `env:` or `shell:`, or a `working-directory:` the gate does
21//!   not declare as `cwd=`;
22//! - any `env:` or `defaults:` a gated step would inherit from its job or its
23//!   workflow — with one exception: an inherited `defaults: run: shell: bash`
24//!   is accepted when the gated command has no pipe, list, redirection or
25//!   substitution, because bash's `-e` and `pipefail` cannot change the verdict
26//!   of a simple command (a decision of the person, 2026-09-30: the fleet sets
27//!   it workflow-wide on purpose).
28//!
29//! A gate that needs one of these does not attest.
30
31use 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
37/// Where workflows live, per forge.
38pub const WORKFLOW_DIRS: &[&str] = &[".github/workflows", ".forgejo/workflows"];
39
40/// One thing wrong, where it is.
41#[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/// A step, as far as parity needs to see one.
59#[derive(Debug, Default)]
60struct Step {
61    line: usize,
62    /// `(key, raw value after the colon, line)` for keys at the step's own
63    /// indentation — never nested ones.
64    keys: Vec<(String, String, usize)>,
65    /// Every line of the step, for finding `tree-` references wherever the
66    /// `if:` puts them (a block scalar included).
67    text: String,
68}
69
70/// What a job or a workflow hands down to its steps.
71#[derive(Debug, Clone, Copy, PartialEq, Eq)]
72enum Inherited {
73    /// `defaults:` holding exactly `run:` → `shell: bash`.
74    ShellBash,
75    /// Any `env:`, or any other `defaults:`.
76    Other,
77}
78
79#[derive(Debug, Default)]
80struct Job {
81    /// `env:` or `defaults:` at the job's own level, with their lines.
82    inherits: Vec<(usize, Inherited)>,
83    steps: Vec<Step>,
84}
85
86#[derive(Debug, Default)]
87struct Workflow {
88    /// `env:` or `defaults:` at the top level.
89    inherits: Vec<(usize, Inherited)>,
90    jobs: Vec<Job>,
91    /// `tree-` references on lines that belong to no step.
92    stray: Vec<usize>,
93}
94
95fn indent_of(line: &str) -> usize {
96    line.len() - line.trim_start_matches(' ').len()
97}
98
99/// `key: value` → `(key, value)`; `None` when the line is not a mapping key.
100fn key_of(s: &str) -> Option<(&str, &str)> {
101    let (k, v) = s.split_once(':')?;
102    let ok = !k.is_empty()
103        && k.chars()
104            .all(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '_' | '.'));
105    (ok && (v.is_empty() || v.starts_with(' '))).then(|| (k, v.trim()))
106}
107
108fn mentions_tree(line: &str) -> bool {
109    line.contains("'tree-") || line.contains("\"tree-")
110}
111
112/// What the `env:`/`defaults:` key on line `idx` (0-based) hands down.
113/// `defaults:` whose body is exactly `run:` → `shell: bash` is the one shape
114/// that may be accepted; everything else is `Other`.
115fn classify(lines: &[&str], idx: usize) -> Inherited {
116    let key_line = lines[idx];
117    if key_of(key_line.trim()).map(|(k, _)| k) != Some("defaults") {
118        return Inherited::Other;
119    }
120    let level = indent_of(key_line);
121    let body: Vec<&str> = lines[idx + 1..]
122        .iter()
123        .map(|l| (indent_of(l), l.trim()))
124        .filter(|(_, t)| !t.is_empty() && !t.starts_with('#'))
125        .take_while(|(ind, _)| *ind > level)
126        .map(|(_, t)| t)
127        .collect();
128    let bash = ["shell: bash", "shell: 'bash'", "shell: \"bash\""];
129    match body.as_slice() {
130        ["run:", shell] if bash.contains(shell) => Inherited::ShellBash,
131        _ => Inherited::Other,
132    }
133}
134
135/// Whether bash's `-e`/`pipefail` could change this command's verdict: a
136/// pipe, a list, a redirection, a substitution or a subshell.
137fn is_simple(command: &str) -> bool {
138    !command.contains(['|', ';', '&', '>', '<', '`', '(', ')']) && !command.contains("$(")
139}
140
141fn read_workflow(text: &str) -> Workflow {
142    let all: Vec<&str> = text.lines().collect();
143    let mut wf = Workflow::default();
144    let mut in_jobs = false;
145    let mut job_indent: Option<usize> = None;
146    let mut job_key_indent: Option<usize> = None;
147    let mut steps_indent: Option<usize> = None;
148    let mut dash_indent: Option<usize> = None;
149    for (i, raw) in text.lines().enumerate() {
150        let lineno = i + 1;
151        let trimmed = raw.trim();
152        if trimmed.is_empty() || trimmed.starts_with('#') {
153            continue;
154        }
155        let ind = indent_of(raw);
156        if ind == 0 {
157            in_jobs = false;
158            job_indent = None;
159            job_key_indent = None;
160            steps_indent = None;
161            dash_indent = None;
162            if let Some((k, _)) = key_of(trimmed) {
163                if k == "jobs" {
164                    in_jobs = true;
165                } else if k == "env" || k == "defaults" {
166                    wf.inherits.push((lineno, classify(&all, i)));
167                }
168            }
169            if mentions_tree(raw) {
170                wf.stray.push(lineno);
171            }
172            continue;
173        }
174        if !in_jobs {
175            if mentions_tree(raw) {
176                wf.stray.push(lineno);
177            }
178            continue;
179        }
180        let ji = *job_indent.get_or_insert(ind);
181        if ind <= ji {
182            // A new job header (or something at the jobs level).
183            job_key_indent = None;
184            steps_indent = None;
185            dash_indent = None;
186            wf.jobs.push(Job::default());
187            if mentions_tree(raw) {
188                wf.stray.push(lineno);
189            }
190            continue;
191        }
192        let Some(job) = wf.jobs.last_mut() else {
193            if mentions_tree(raw) {
194                wf.stray.push(lineno);
195            }
196            continue;
197        };
198        let jki = *job_key_indent.get_or_insert(ind);
199        if ind <= jki {
200            // A job-level key ends any steps list.
201            steps_indent = None;
202            dash_indent = None;
203            if let Some((k, _)) = key_of(trimmed) {
204                if k == "steps" {
205                    steps_indent = Some(ind);
206                } else if k == "env" || k == "defaults" {
207                    job.inherits.push((lineno, classify(&all, i)));
208                }
209            }
210            if mentions_tree(raw) {
211                wf.stray.push(lineno);
212            }
213            continue;
214        }
215        if steps_indent.is_none() {
216            if mentions_tree(raw) {
217                wf.stray.push(lineno);
218            }
219            continue;
220        }
221        if let Some(item) = trimmed
222            .strip_prefix("- ")
223            .or((trimmed == "-").then_some(""))
224        {
225            let di = *dash_indent.get_or_insert(ind);
226            if ind == di {
227                let mut step = Step {
228                    line: lineno,
229                    ..Step::default()
230                };
231                step.text.push_str(raw);
232                step.text.push('\n');
233                if let Some((k, v)) = key_of(item) {
234                    step.keys.push((k.to_string(), v.to_string(), lineno));
235                }
236                job.steps.push(step);
237                continue;
238            }
239        }
240        let Some(step) = job.steps.last_mut() else {
241            if mentions_tree(raw) {
242                wf.stray.push(lineno);
243            }
244            continue;
245        };
246        step.text.push_str(raw);
247        step.text.push('\n');
248        // A key at the step's own indentation (dash + 2).
249        if Some(ind) == dash_indent.map(|d| d + 2) {
250            if let Some((k, v)) = key_of(trimmed) {
251                step.keys.push((k.to_string(), v.to_string(), lineno));
252            }
253        }
254    }
255    wf
256}
257
258/// The `tree-<name>` tokens a step's text references.
259fn referenced(text: &str) -> Vec<String> {
260    let mut out: Vec<String> = Vec::new();
261    for quote in ['\'', '"'] {
262        let needle = format!("{quote}tree-");
263        let mut rest = text;
264        while let Some(i) = rest.find(&needle) {
265            let after = &rest[i + needle.len()..];
266            let end = after.find(quote).unwrap_or(after.len());
267            let name = &after[..end];
268            if !name.is_empty() && !out.iter().any(|n| n == name) {
269                out.push(name.to_string());
270            }
271            rest = &after[end..];
272        }
273    }
274    out
275}
276
277/// A single-line scalar's value, or why it cannot be read with certainty.
278fn scalar(raw: &str) -> Result<String, &'static str> {
279    let v = raw.trim();
280    if v.is_empty() || v.starts_with('|') || v.starts_with('>') {
281        return Err("a block scalar — write the command on one line");
282    }
283    if v.starts_with('&') || v.starts_with('*') {
284        return Err("an anchor or alias");
285    }
286    let value = if let Some(inner) = v.strip_prefix('"') {
287        let Some(inner) = inner.strip_suffix('"') else {
288            return Err("an unterminated quoted scalar");
289        };
290        if inner.contains(['\\', '"']) {
291            return Err("a quoted scalar with escapes");
292        }
293        inner.to_string()
294    } else if let Some(inner) = v.strip_prefix('\'') {
295        let Some(inner) = inner.strip_suffix('\'') else {
296            return Err("an unterminated quoted scalar");
297        };
298        if inner.contains('\'') {
299            return Err("a quoted scalar with escapes");
300        }
301        inner.to_string()
302    } else {
303        if v.contains(" #") || v.contains(": ") || v.starts_with(['{', '[', '!', '%', '@', '`']) {
304            return Err("a plain scalar YAML may read differently — quote it");
305        }
306        v.to_string()
307    };
308    if value.contains("${{") {
309        return Err("`${{ }}` interpolation");
310    }
311    Ok(value)
312}
313
314/// Every problem in `workflows` (path, text) against `gates`.
315pub fn check_texts(
316    manifest: &str,
317    gates: &[TreeGate],
318    workflows: &[(String, String)],
319) -> Vec<Problem> {
320    let mut problems = Vec::new();
321    let mut seen: Vec<&str> = Vec::new();
322    for (file, text) in workflows {
323        let wf = read_workflow(text);
324        for line in &wf.stray {
325            problems.push(Problem {
326                file: file.clone(),
327                line: *line,
328                what: "a tree gate referenced outside a step — only a step may be skipped on one"
329                    .into(),
330            });
331        }
332        for job in &wf.jobs {
333            for step in &job.steps {
334                let names = referenced(&step.text);
335                if names.is_empty() {
336                    continue;
337                }
338                let at = |what: String| Problem {
339                    file: file.clone(),
340                    line: step.line,
341                    what,
342                };
343                if names.len() > 1 {
344                    problems.push(at(format!(
345                        "one step is gated on several tree gates ({}) — a gate proves one command",
346                        names.join(", ")
347                    )));
348                    continue;
349                }
350                let name = &names[0];
351                let Some(gate) = gates.iter().find(|g| &g.name == name) else {
352                    problems.push(at(format!("`tree-{name}` is not declared in {manifest}")));
353                    continue;
354                };
355                seen.push(&gate.name);
356                let inherited: Vec<(usize, Inherited)> =
357                    wf.inherits.iter().chain(&job.inherits).copied().collect();
358                if let Some((l, _)) = inherited.iter().find(|(_, k)| *k == Inherited::Other) {
359                    problems.push(Problem {
360                        file: file.clone(),
361                        line: *l,
362                        what: format!(
363                            "`tree-{name}` is skipped in a job that inherits `env:` or \
364                             `defaults:` — they change what `run:` does; move them onto \
365                             the steps that need them"
366                        ),
367                    });
368                    continue;
369                }
370                if let Some((l, _)) = inherited.first() {
371                    if !is_simple(&gate.normalized()) {
372                        problems.push(Problem {
373                            file: file.clone(),
374                            line: *l,
375                            what: format!(
376                                "`tree-{name}` inherits `shell: bash`, which is accepted only \
377                                 for a simple command — this one has a pipe, list, \
378                                 redirection or substitution"
379                            ),
380                        });
381                        continue;
382                    }
383                }
384                let mut run = None;
385                let mut bad = None;
386                for (k, v, l) in &step.keys {
387                    match k.as_str() {
388                        "run" => run = Some((v, *l)),
389                        "env" | "shell" => {
390                            bad = Some(format!("a step-level `{k}:` changes what `run:` does"))
391                        }
392                        "working-directory" => match (scalar(v), &gate.cwd) {
393                            (Ok(dir), Some(cwd))
394                                if dir.trim_end_matches('/').trim_start_matches("./")
395                                    == cwd.as_str() => {}
396                            _ => {
397                                bad = Some(
398                                    "`working-directory:` differs from the gate's `cwd=`".into(),
399                                )
400                            }
401                        },
402                        _ => {}
403                    }
404                }
405                if bad.is_none() && gate.cwd.is_some() {
406                    let has_wd = step.keys.iter().any(|(k, _, _)| k == "working-directory");
407                    if !has_wd {
408                        bad = Some(format!(
409                            "the gate runs in `{}` (cwd=) but the step has no \
410                             `working-directory:`",
411                            gate.cwd.as_deref().unwrap_or("")
412                        ));
413                    }
414                }
415                if let Some(why) = bad {
416                    problems.push(at(format!("`tree-{name}`: {why}")));
417                    continue;
418                }
419                let Some((raw, line)) = run else {
420                    problems.push(at(format!("`tree-{name}` gates a step with no `run:`")));
421                    continue;
422                };
423                match scalar(raw) {
424                    Err(why) => problems.push(Problem {
425                        file: file.clone(),
426                        line,
427                        what: format!("`tree-{name}`: `run:` is {why}"),
428                    }),
429                    Ok(value) => {
430                        let got = normalize_command(&value);
431                        let want = gate.normalized();
432                        if got != want {
433                            problems.push(Problem {
434                                file: file.clone(),
435                                line,
436                                what: format!(
437                                    "`tree-{name}` runs `{got}` here but `{want}` in {manifest}:{}",
438                                    gate.lineno
439                                ),
440                            });
441                        }
442                    }
443                }
444            }
445        }
446    }
447    for gate in gates {
448        if !seen.contains(&gate.name.as_str()) {
449            problems.push(Problem {
450                file: manifest.into(),
451                line: gate.lineno,
452                what: format!(
453                    "`tree-{}` is declared but no workflow step is skipped on it",
454                    gate.name
455                ),
456            });
457        }
458    }
459    problems
460}
461
462/// The built-in test gates a CI step may be skipped on (#288).
463pub const BUILTIN_TEST_GATES: &[&str] = &[
464    "pre-push-cargo-test",
465    "pre-push-go-test",
466    "pre-push-pytest",
467    "pre-push-run-tests-js",
468];
469
470/// Flags that change what a run prints, never its verdict.
471const NOISE: &[&str] = &["-q", "--quiet", "-v", "--verbose"];
472
473/// Whether `command` runs what the built-in `gate` runs locally, under the
474/// stated equivalences (#288, the t03 survey):
475///
476/// - `pre-push-cargo-test`: `cargo test`, with `--workspace` and
477///   `--all-features` optional (the local gate passes both; a single-package
478///   repository is the same suite without them).
479/// - `pre-push-go-test`: `go test ./...`.
480/// - `pre-push-pytest`: `pytest`, bare, as `python -m pytest`, or under
481///   `uv run` with `--no-sync` or `--frozen`.
482/// - `pre-push-run-tests-js`: one of the scripts the local gate runs
483///   (`typecheck`, `test:unit`, `test`), through npm, pnpm or yarn.
484///
485/// `-q`/`-v` are ignored everywhere. Anything else differs: a coverage
486/// floor, `-race`, `--locked`, a package subset, a `make` target, a pipe.
487fn builtin_matches(gate: &str, command: &str) -> bool {
488    if !is_simple(command) {
489        return false;
490    }
491    let tokens: Vec<&str> = command
492        .split_whitespace()
493        .filter(|t| !NOISE.contains(t))
494        .collect();
495    match gate {
496        "pre-push-cargo-test" => {
497            tokens.starts_with(&["cargo", "test"])
498                && tokens[2..]
499                    .iter()
500                    .all(|t| matches!(*t, "--workspace" | "--all-features"))
501        }
502        "pre-push-go-test" => tokens == ["go", "test", "./..."],
503        "pre-push-pytest" => {
504            let rest: Vec<&str> = match tokens.as_slice() {
505                ["uv", "run", rest @ ..] => rest
506                    .iter()
507                    .copied()
508                    .filter(|t| !matches!(*t, "--no-sync" | "--frozen"))
509                    .collect(),
510                ["python" | "python3", "-m", rest @ ..] => rest.to_vec(),
511                other => other.to_vec(),
512            };
513            rest == ["pytest"]
514        }
515        "pre-push-run-tests-js" => {
516            let script = match tokens.as_slice() {
517                ["npm" | "pnpm" | "yarn", "test"] => Some("test"),
518                ["npm" | "pnpm", "run", s] => Some(*s),
519                ["pnpm" | "yarn", s] => Some(*s),
520                _ => None,
521            };
522            matches!(script, Some("typecheck" | "test:unit" | "test"))
523        }
524        _ => false,
525    }
526}
527
528/// The built-in test gate a step is skipped on (`!contains(…, '<gate>')`),
529/// if any. A step that runs only WHEN attested (`contains(…)` without `!`)
530/// reports the skip and is not one.
531fn skipped_builtin(text: &str) -> Option<&'static str> {
532    if !text.contains("!contains(") {
533        return None;
534    }
535    BUILTIN_TEST_GATES
536        .iter()
537        .copied()
538        .find(|g| text.contains(&format!("'{g}'")) || text.contains(&format!("\"{g}\"")))
539}
540
541/// Every CI step skipped on a built-in test gate whose command is not that
542/// gate's (#288). Reported at warn severity: about 25 repositories differ
543/// today, and a blocking check would stop their commits on upgrade. The same
544/// fail-closed reading as the tree gates: what cannot be read with certainty
545/// differs.
546pub fn builtin_drift_texts(workflows: &[(String, String)]) -> Vec<Problem> {
547    let mut problems = Vec::new();
548    for (file, text) in workflows {
549        let wf = read_workflow(text);
550        for job in &wf.jobs {
551            for step in &job.steps {
552                let Some(gate) = skipped_builtin(&step.text) else {
553                    continue;
554                };
555                let at = |line: usize, what: String| Problem {
556                    file: file.clone(),
557                    line,
558                    what: format!(
559                        "`{gate}` {what} — CI skips this step on a signature of a \
560                         different command"
561                    ),
562                };
563                let inherited: Vec<(usize, Inherited)> =
564                    wf.inherits.iter().chain(&job.inherits).copied().collect();
565                if let Some((l, _)) = inherited.iter().find(|(_, k)| *k == Inherited::Other) {
566                    problems.push(at(
567                        *l,
568                        "is skipped in a job that inherits `env:` or `defaults:`".into(),
569                    ));
570                    continue;
571                }
572                let mut run = None;
573                let mut bad = None;
574                for (k, v, l) in &step.keys {
575                    match k.as_str() {
576                        "run" => run = Some((v, *l)),
577                        "env" | "shell" | "working-directory" => {
578                            bad = Some((*l, format!("gates a step with its own `{k}:`")))
579                        }
580                        _ => {}
581                    }
582                }
583                if let Some((l, why)) = bad {
584                    problems.push(at(l, why));
585                    continue;
586                }
587                let Some((raw, line)) = run else {
588                    problems.push(at(step.line, "gates a step with no `run:`".into()));
589                    continue;
590                };
591                match scalar(raw) {
592                    Err(why) => problems.push(at(line, format!("gates a `run:` that is {why}"))),
593                    Ok(value) => {
594                        let got = normalize_command(&value);
595                        if !builtin_matches(gate, &got) {
596                            problems.push(at(line, format!("gates `{got}`")));
597                        }
598                    }
599                }
600            }
601        }
602    }
603    problems
604}
605
606/// [`builtin_drift_texts`] over `root`'s workflows.
607pub fn builtin_drift(root: &Path) -> Vec<Problem> {
608    builtin_drift_texts(&read_workflows(root))
609}
610
611/// Every workflow file under `root`, as (relative path, text), sorted.
612fn read_workflows(root: &Path) -> Vec<(String, String)> {
613    let mut workflows = Vec::new();
614    for dir in WORKFLOW_DIRS {
615        let Ok(entries) = std::fs::read_dir(root.join(dir)) else {
616            continue;
617        };
618        let mut paths: Vec<_> = entries
619            .filter_map(Result::ok)
620            .map(|e| e.path())
621            .filter(|p| matches!(p.extension().and_then(|e| e.to_str()), Some("yml" | "yaml")))
622            .collect();
623        paths.sort();
624        for p in paths {
625            if let Ok(text) = std::fs::read_to_string(&p) {
626                let rel = p.strip_prefix(root).unwrap_or(&p).display().to_string();
627                workflows.push((rel, text));
628            }
629        }
630    }
631    workflows
632}
633
634/// Read `root`'s manifest and workflows, and compare them.
635pub fn check_repo(root: &Path) -> Vec<Problem> {
636    let Ok(manifest) = std::fs::read_to_string(root.join(crate::manifest::manifest_name(root)))
637    else {
638        return Vec::new();
639    };
640    let gates = tree_gates(&manifest);
641    if gates.is_empty() {
642        return Vec::new();
643    }
644    check_texts(
645        crate::manifest::manifest_name(root),
646        &gates,
647        &read_workflows(root),
648    )
649}
650
651/// The pre-commit check. A built-in test gate's drift warns (#288); a tree
652/// gate's blocks. `Inert` when there is neither a tree gate nor a step
653/// skipped on a built-in one.
654pub fn run(settings: &crate::config::Settings) -> Outcome {
655    let root = repo_root();
656    let root = Path::new(&root);
657    let drift = builtin_drift(root);
658    for p in &drift {
659        warn(&crate::ui::sanitize(&p.to_string()));
660    }
661    let declares = std::fs::read_to_string(root.join(crate::manifest::manifest_name(root)))
662        .map(|t| !tree_gates(&t).is_empty())
663        .unwrap_or(false);
664    let problems = if declares {
665        check_repo(root)
666    } else {
667        Vec::new()
668    };
669    if problems.is_empty() {
670        return match (declares, drift.is_empty()) {
671            (_, false) => Outcome::Warned,
672            (true, true) => {
673                ok(settings, "tree gates match their CI steps");
674                Outcome::Passed
675            }
676            (false, true) => Outcome::Inert,
677        };
678    }
679    for p in &problems {
680        eprintln!("  {}", crate::ui::sanitize(&p.to_string()));
681    }
682    fail(&format!(
683        "{} tree-gate parity problem(s) — fix the workflow or the {} line; run {} to re-check",
684        problems.len(),
685        crate::manifest::manifest_name(root),
686        hl(concat!(crate::bin!(), " tree-parity"))
687    ));
688    Outcome::Failed
689}
690
691#[cfg(test)]
692mod tests {
693    use super::*;
694
695    fn drift(step_run: &str) -> Vec<Problem> {
696        let text = format!(
697            "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"
698        );
699        builtin_drift_texts(&[(".github/workflows/ci.yaml".into(), text)])
700    }
701
702    /// #288: a step skipped on a built-in test gate must run that gate's
703    /// command, under the stated equivalences.
704    #[test]
705    fn a_builtin_gate_step_is_compared_with_the_local_command() {
706        assert_eq!(drift("run: cargo test"), vec![]);
707        assert_eq!(
708            drift("run: cargo test --workspace --all-features -q"),
709            vec![]
710        );
711        let locked = drift("run: cargo test --workspace --locked");
712        assert_eq!(locked.len(), 1, "{locked:?}");
713        assert!(locked[0].what.contains("pre-push-cargo-test"), "{locked:?}");
714        assert_eq!(drift("run: make test").len(), 1);
715        assert_eq!(
716            drift("run: |\n          cargo test").len(),
717            1,
718            "a block scalar differs"
719        );
720        assert_eq!(
721            drift("run: cargo test\n        env:\n          X: 1").len(),
722            1
723        );
724    }
725
726    #[test]
727    fn the_builtin_equivalences() {
728        assert!(builtin_matches("pre-push-go-test", "go test ./..."));
729        assert!(!builtin_matches("pre-push-go-test", "go test -race ./..."));
730        assert!(builtin_matches(
731            "pre-push-pytest",
732            "uv run --no-sync pytest"
733        ));
734        assert!(builtin_matches("pre-push-pytest", "python -m pytest -q"));
735        assert!(!builtin_matches(
736            "pre-push-pytest",
737            "uv run pytest --cov-fail-under=80"
738        ));
739        assert!(builtin_matches(
740            "pre-push-run-tests-js",
741            "pnpm run test:unit"
742        ));
743        assert!(builtin_matches("pre-push-run-tests-js", "npm test"));
744        assert!(!builtin_matches("pre-push-run-tests-js", "pnpm coverage"));
745        assert!(!builtin_matches(
746            "pre-push-cargo-test",
747            "cargo test | tee log"
748        ));
749    }
750
751    /// A step that runs only when attested reports the skip; it is not one.
752    #[test]
753    fn a_step_run_when_attested_is_not_a_skipped_one() {
754        assert_eq!(
755            skipped_builtin("if: ${{ contains(fromJSON(x), 'pre-push-cargo-test') }}"),
756            None
757        );
758        assert_eq!(
759            skipped_builtin("if: ${{ !contains(fromJSON(x), 'pre-push-cargo-test') }}"),
760            Some("pre-push-cargo-test")
761        );
762    }
763
764    fn gates(text: &str) -> Vec<TreeGate> {
765        let g = tree_gates(text);
766        assert!(!g.is_empty(), "no gate parsed from {text:?}");
767        g
768    }
769
770    fn check(manifest: &str, workflow: &str) -> Vec<Problem> {
771        check_texts(
772            crate::manifest::MANIFEST,
773            &gates(manifest),
774            &[(
775                ".forgejo/workflows/ci.yaml".to_string(),
776                workflow.to_string(),
777            )],
778        )
779    }
780
781    const ESLINT: &str = "tree eslint eslint * attest npm run lint -- {cache}";
782
783    fn wf(step_run: &str) -> String {
784        format!(
785            "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"
786        )
787    }
788
789    #[test]
790    fn parity_matching_run_passes() {
791        assert_eq!(check(ESLINT, &wf("run: npm run lint")), vec![]);
792    }
793
794    #[test]
795    fn parity_quoted_run_passes() {
796        assert_eq!(check(ESLINT, &wf("run: 'npm run lint'")), vec![]);
797    }
798
799    #[test]
800    fn parity_drifted_run_fails() {
801        let p = check(ESLINT, &wf("run: npm run lint -- --max-warnings 0"));
802        assert_eq!(p.len(), 1, "{p:?}");
803        assert!(p[0]
804            .what
805            .contains("runs `npm run lint -- --max-warnings 0` here"));
806    }
807
808    #[test]
809    fn parity_block_scalar_rejected() {
810        let p = check(ESLINT, &wf("run: |\n          npm run lint"));
811        assert_eq!(p.len(), 1, "{p:?}");
812        assert!(p[0].what.contains("block scalar"));
813    }
814
815    #[test]
816    fn parity_anchor_rejected() {
817        let p = check(ESLINT, &wf("run: *lint"));
818        assert!(p[0].what.contains("anchor"), "{p:?}");
819    }
820
821    #[test]
822    fn parity_interpolation_rejected() {
823        let p = check(ESLINT, &wf("run: npm run ${{ matrix.task }}"));
824        assert!(p[0].what.contains("interpolation"), "{p:?}");
825    }
826
827    #[test]
828    fn parity_step_env_rejected() {
829        let p = check(
830            ESLINT,
831            &wf("env:\n          CI: '1'\n        run: npm run lint"),
832        );
833        assert!(p[0].what.contains("step-level `env:`"), "{p:?}");
834    }
835
836    #[test]
837    fn parity_step_shell_rejected() {
838        let p = check(ESLINT, &wf("shell: bash\n        run: npm run lint"));
839        assert!(p[0].what.contains("step-level `shell:`"), "{p:?}");
840    }
841
842    #[test]
843    fn parity_undeclared_working_directory_rejected() {
844        let p = check(
845            ESLINT,
846            &wf("working-directory: web\n        run: npm run lint"),
847        );
848        assert!(p[0].what.contains("working-directory"), "{p:?}");
849    }
850
851    #[test]
852    fn parity_declared_cwd_passes() {
853        let p = check(
854            "tree eslint eslint * attest cwd=web npm run lint",
855            &wf("working-directory: web\n        run: npm run lint"),
856        );
857        assert_eq!(p, vec![]);
858    }
859
860    #[test]
861    fn parity_cwd_without_working_directory_rejected() {
862        let p = check(
863            "tree eslint eslint * attest cwd=web npm run lint",
864            &wf("run: npm run lint"),
865        );
866        assert!(p[0].what.contains("no `working-directory:`"), "{p:?}");
867    }
868
869    #[test]
870    fn parity_job_env_rejected() {
871        let w = wf("run: npm run lint").replace(
872            "    runs-on: ubuntu-latest\n",
873            "    runs-on: ubuntu-latest\n    env:\n      NODE_ENV: test\n",
874        );
875        let p = check(ESLINT, &w);
876        assert!(p[0].what.contains("inherits"), "{p:?}");
877    }
878
879    #[test]
880    fn parity_job_defaults_rejected() {
881        let w = wf("run: npm run lint").replace(
882            "    runs-on: ubuntu-latest\n",
883            "    runs-on: ubuntu-latest\n    defaults:\n      run:\n        working-directory: web\n",
884        );
885        let p = check(ESLINT, &w);
886        assert!(p[0].what.contains("inherits"), "{p:?}");
887    }
888
889    #[test]
890    fn parity_workflow_shell_bash_accepted_for_a_simple_command() {
891        let w = wf("run: npm run lint")
892            .replace("jobs:\n", "defaults:\n  run:\n    shell: bash\njobs:\n");
893        assert_eq!(check(ESLINT, &w), vec![]);
894    }
895
896    #[test]
897    fn parity_job_shell_bash_accepted_for_a_simple_command() {
898        let w = wf("run: npm run lint").replace(
899            "    runs-on: ubuntu-latest\n",
900            "    runs-on: ubuntu-latest\n    defaults:\n      run:\n        shell: bash\n",
901        );
902        assert_eq!(check(ESLINT, &w), vec![]);
903    }
904
905    #[test]
906    fn parity_shell_bash_rejected_for_a_pipeline() {
907        let w = wf("run: npm run lint | tee lint.log")
908            .replace("jobs:\n", "defaults:\n  run:\n    shell: bash\njobs:\n");
909        let p = check(
910            "tree eslint eslint * attest npm run lint | tee lint.log",
911            &w,
912        );
913        assert!(p[0].what.contains("simple command"), "{p:?}");
914    }
915
916    #[test]
917    fn parity_other_shell_rejected() {
918        let w =
919            wf("run: npm run lint").replace("jobs:\n", "defaults:\n  run:\n    shell: sh\njobs:\n");
920        let p = check(ESLINT, &w);
921        assert!(p[0].what.contains("inherits `env:` or"), "{p:?}");
922    }
923
924    #[test]
925    fn parity_shell_bash_plus_working_directory_rejected() {
926        let w = wf("run: npm run lint").replace(
927            "jobs:\n",
928            "defaults:\n  run:\n    shell: bash\n    working-directory: web\njobs:\n",
929        );
930        let p = check(ESLINT, &w);
931        assert!(p[0].what.contains("inherits `env:` or"), "{p:?}");
932    }
933
934    #[test]
935    fn parity_workflow_env_still_rejected_beside_shell_bash() {
936        let w = wf("run: npm run lint").replace(
937            "jobs:\n",
938            "defaults:\n  run:\n    shell: bash\nenv:\n  CI: '1'\njobs:\n",
939        );
940        let p = check(ESLINT, &w);
941        assert!(p[0].what.contains("inherits `env:` or"), "{p:?}");
942    }
943
944    #[test]
945    fn parity_undeclared_gate_rejected() {
946        let p = check(
947            "tree prettier prettier * attest npx prettier --check .",
948            &wf("run: npm run lint"),
949        );
950        assert!(
951            p.iter()
952                .any(|p| p.what.contains("`tree-eslint` is not declared")),
953            "{p:?}"
954        );
955        assert!(
956            p.iter().any(|p| p.what.contains("no workflow step")),
957            "{p:?}"
958        );
959    }
960
961    #[test]
962    fn parity_declared_gate_without_step_rejected() {
963        let p = check(
964            ESLINT,
965            "name: ci\njobs:\n  a:\n    steps:\n      - run: true\n",
966        );
967        assert_eq!(p.len(), 1, "{p:?}");
968        assert!(p[0].what.contains("no workflow step is skipped on it"));
969    }
970
971    #[test]
972    fn parity_job_level_reference_rejected() {
973        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";
974        let p = check(ESLINT, w);
975        assert!(p.iter().any(|p| p.what.contains("outside a step")), "{p:?}");
976    }
977
978    #[test]
979    fn parity_two_gates_on_one_step_rejected() {
980        let w = wf("run: npm run lint").replace(
981            "'tree-eslint') }}",
982            "'tree-eslint') && !contains(fromJSON(steps.attest.outputs.gates), 'tree-prettier') }}",
983        );
984        let p = check(
985            "tree eslint eslint * attest npm run lint\ntree prettier prettier * attest npx prettier --check .",
986            &w,
987        );
988        let several = p
989            .iter()
990            .find(|p| p.what.contains("several tree gates"))
991            .unwrap_or_else(|| panic!("{p:?}"));
992        // The problem names the step's own line (`- name: Lint`), where the
993        // reader has to look.
994        assert_eq!(several.line, 11, "{several:?}");
995    }
996}