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, MANIFEST};
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(gates: &[TreeGate], workflows: &[(String, String)]) -> Vec<Problem> {
316    let mut problems = Vec::new();
317    let mut seen: Vec<&str> = Vec::new();
318    for (file, text) in workflows {
319        let wf = read_workflow(text);
320        for line in &wf.stray {
321            problems.push(Problem {
322                file: file.clone(),
323                line: *line,
324                what: "a tree gate referenced outside a step — only a step may be skipped on one"
325                    .into(),
326            });
327        }
328        for job in &wf.jobs {
329            for step in &job.steps {
330                let names = referenced(&step.text);
331                if names.is_empty() {
332                    continue;
333                }
334                let at = |what: String| Problem {
335                    file: file.clone(),
336                    line: step.line,
337                    what,
338                };
339                if names.len() > 1 {
340                    problems.push(at(format!(
341                        "one step is gated on several tree gates ({}) — a gate proves one command",
342                        names.join(", ")
343                    )));
344                    continue;
345                }
346                let name = &names[0];
347                let Some(gate) = gates.iter().find(|g| &g.name == name) else {
348                    problems.push(at(format!("`tree-{name}` is not declared in {MANIFEST}")));
349                    continue;
350                };
351                seen.push(&gate.name);
352                let inherited: Vec<(usize, Inherited)> =
353                    wf.inherits.iter().chain(&job.inherits).copied().collect();
354                if let Some((l, _)) = inherited.iter().find(|(_, k)| *k == Inherited::Other) {
355                    problems.push(Problem {
356                        file: file.clone(),
357                        line: *l,
358                        what: format!(
359                            "`tree-{name}` is skipped in a job that inherits `env:` or \
360                             `defaults:` — they change what `run:` does; move them onto \
361                             the steps that need them"
362                        ),
363                    });
364                    continue;
365                }
366                if let Some((l, _)) = inherited.first() {
367                    if !is_simple(&gate.normalized()) {
368                        problems.push(Problem {
369                            file: file.clone(),
370                            line: *l,
371                            what: format!(
372                                "`tree-{name}` inherits `shell: bash`, which is accepted only \
373                                 for a simple command — this one has a pipe, list, \
374                                 redirection or substitution"
375                            ),
376                        });
377                        continue;
378                    }
379                }
380                let mut run = None;
381                let mut bad = None;
382                for (k, v, l) in &step.keys {
383                    match k.as_str() {
384                        "run" => run = Some((v, *l)),
385                        "env" | "shell" => {
386                            bad = Some(format!("a step-level `{k}:` changes what `run:` does"))
387                        }
388                        "working-directory" => match (scalar(v), &gate.cwd) {
389                            (Ok(dir), Some(cwd))
390                                if dir.trim_end_matches('/').trim_start_matches("./")
391                                    == cwd.as_str() => {}
392                            _ => {
393                                bad = Some(
394                                    "`working-directory:` differs from the gate's `cwd=`".into(),
395                                )
396                            }
397                        },
398                        _ => {}
399                    }
400                }
401                if bad.is_none() && gate.cwd.is_some() {
402                    let has_wd = step.keys.iter().any(|(k, _, _)| k == "working-directory");
403                    if !has_wd {
404                        bad = Some(format!(
405                            "the gate runs in `{}` (cwd=) but the step has no \
406                             `working-directory:`",
407                            gate.cwd.as_deref().unwrap_or("")
408                        ));
409                    }
410                }
411                if let Some(why) = bad {
412                    problems.push(at(format!("`tree-{name}`: {why}")));
413                    continue;
414                }
415                let Some((raw, line)) = run else {
416                    problems.push(at(format!("`tree-{name}` gates a step with no `run:`")));
417                    continue;
418                };
419                match scalar(raw) {
420                    Err(why) => problems.push(Problem {
421                        file: file.clone(),
422                        line,
423                        what: format!("`tree-{name}`: `run:` is {why}"),
424                    }),
425                    Ok(value) => {
426                        let got = normalize_command(&value);
427                        let want = gate.normalized();
428                        if got != want {
429                            problems.push(Problem {
430                                file: file.clone(),
431                                line,
432                                what: format!(
433                                    "`tree-{name}` runs `{got}` here but `{want}` in {MANIFEST}:{}",
434                                    gate.lineno
435                                ),
436                            });
437                        }
438                    }
439                }
440            }
441        }
442    }
443    for gate in gates {
444        if !seen.contains(&gate.name.as_str()) {
445            problems.push(Problem {
446                file: MANIFEST.into(),
447                line: gate.lineno,
448                what: format!(
449                    "`tree-{}` is declared but no workflow step is skipped on it",
450                    gate.name
451                ),
452            });
453        }
454    }
455    problems
456}
457
458/// The built-in test gates a CI step may be skipped on (#288).
459pub const BUILTIN_TEST_GATES: &[&str] = &[
460    "pre-push-cargo-test",
461    "pre-push-go-test",
462    "pre-push-pytest",
463    "pre-push-run-tests-js",
464];
465
466/// Flags that change what a run prints, never its verdict.
467const NOISE: &[&str] = &["-q", "--quiet", "-v", "--verbose"];
468
469/// Whether `command` runs what the built-in `gate` runs locally, under the
470/// stated equivalences (#288, the t03 survey):
471///
472/// - `pre-push-cargo-test`: `cargo test`, with `--workspace` and
473///   `--all-features` optional (the local gate passes both; a single-package
474///   repository is the same suite without them).
475/// - `pre-push-go-test`: `go test ./...`.
476/// - `pre-push-pytest`: `pytest`, bare, as `python -m pytest`, or under
477///   `uv run` with `--no-sync` or `--frozen`.
478/// - `pre-push-run-tests-js`: one of the scripts the local gate runs
479///   (`typecheck`, `test:unit`, `test`), through npm, pnpm or yarn.
480///
481/// `-q`/`-v` are ignored everywhere. Anything else differs: a coverage
482/// floor, `-race`, `--locked`, a package subset, a `make` target, a pipe.
483fn builtin_matches(gate: &str, command: &str) -> bool {
484    if !is_simple(command) {
485        return false;
486    }
487    let tokens: Vec<&str> = command
488        .split_whitespace()
489        .filter(|t| !NOISE.contains(t))
490        .collect();
491    match gate {
492        "pre-push-cargo-test" => {
493            tokens.starts_with(&["cargo", "test"])
494                && tokens[2..]
495                    .iter()
496                    .all(|t| matches!(*t, "--workspace" | "--all-features"))
497        }
498        "pre-push-go-test" => tokens == ["go", "test", "./..."],
499        "pre-push-pytest" => {
500            let rest: Vec<&str> = match tokens.as_slice() {
501                ["uv", "run", rest @ ..] => rest
502                    .iter()
503                    .copied()
504                    .filter(|t| !matches!(*t, "--no-sync" | "--frozen"))
505                    .collect(),
506                ["python" | "python3", "-m", rest @ ..] => rest.to_vec(),
507                other => other.to_vec(),
508            };
509            rest == ["pytest"]
510        }
511        "pre-push-run-tests-js" => {
512            let script = match tokens.as_slice() {
513                ["npm" | "pnpm" | "yarn", "test"] => Some("test"),
514                ["npm" | "pnpm", "run", s] => Some(*s),
515                ["pnpm" | "yarn", s] => Some(*s),
516                _ => None,
517            };
518            matches!(script, Some("typecheck" | "test:unit" | "test"))
519        }
520        _ => false,
521    }
522}
523
524/// The built-in test gate a step is skipped on (`!contains(…, '<gate>')`),
525/// if any. A step that runs only WHEN attested (`contains(…)` without `!`)
526/// reports the skip and is not one.
527fn skipped_builtin(text: &str) -> Option<&'static str> {
528    if !text.contains("!contains(") {
529        return None;
530    }
531    BUILTIN_TEST_GATES
532        .iter()
533        .copied()
534        .find(|g| text.contains(&format!("'{g}'")) || text.contains(&format!("\"{g}\"")))
535}
536
537/// Every CI step skipped on a built-in test gate whose command is not that
538/// gate's (#288). Reported at warn severity: about 25 repositories differ
539/// today, and a blocking check would stop their commits on upgrade. The same
540/// fail-closed reading as the tree gates: what cannot be read with certainty
541/// differs.
542pub fn builtin_drift_texts(workflows: &[(String, String)]) -> Vec<Problem> {
543    let mut problems = Vec::new();
544    for (file, text) in workflows {
545        let wf = read_workflow(text);
546        for job in &wf.jobs {
547            for step in &job.steps {
548                let Some(gate) = skipped_builtin(&step.text) else {
549                    continue;
550                };
551                let at = |line: usize, what: String| Problem {
552                    file: file.clone(),
553                    line,
554                    what: format!(
555                        "`{gate}` {what} — CI skips this step on a signature of a \
556                         different command"
557                    ),
558                };
559                let inherited: Vec<(usize, Inherited)> =
560                    wf.inherits.iter().chain(&job.inherits).copied().collect();
561                if let Some((l, _)) = inherited.iter().find(|(_, k)| *k == Inherited::Other) {
562                    problems.push(at(
563                        *l,
564                        "is skipped in a job that inherits `env:` or `defaults:`".into(),
565                    ));
566                    continue;
567                }
568                let mut run = None;
569                let mut bad = None;
570                for (k, v, l) in &step.keys {
571                    match k.as_str() {
572                        "run" => run = Some((v, *l)),
573                        "env" | "shell" | "working-directory" => {
574                            bad = Some((*l, format!("gates a step with its own `{k}:`")))
575                        }
576                        _ => {}
577                    }
578                }
579                if let Some((l, why)) = bad {
580                    problems.push(at(l, why));
581                    continue;
582                }
583                let Some((raw, line)) = run else {
584                    problems.push(at(step.line, "gates a step with no `run:`".into()));
585                    continue;
586                };
587                match scalar(raw) {
588                    Err(why) => problems.push(at(line, format!("gates a `run:` that is {why}"))),
589                    Ok(value) => {
590                        let got = normalize_command(&value);
591                        if !builtin_matches(gate, &got) {
592                            problems.push(at(line, format!("gates `{got}`")));
593                        }
594                    }
595                }
596            }
597        }
598    }
599    problems
600}
601
602/// [`builtin_drift_texts`] over `root`'s workflows.
603pub fn builtin_drift(root: &Path) -> Vec<Problem> {
604    builtin_drift_texts(&read_workflows(root))
605}
606
607/// Every workflow file under `root`, as (relative path, text), sorted.
608fn read_workflows(root: &Path) -> Vec<(String, String)> {
609    let mut workflows = Vec::new();
610    for dir in WORKFLOW_DIRS {
611        let Ok(entries) = std::fs::read_dir(root.join(dir)) else {
612            continue;
613        };
614        let mut paths: Vec<_> = entries
615            .filter_map(Result::ok)
616            .map(|e| e.path())
617            .filter(|p| matches!(p.extension().and_then(|e| e.to_str()), Some("yml" | "yaml")))
618            .collect();
619        paths.sort();
620        for p in paths {
621            if let Ok(text) = std::fs::read_to_string(&p) {
622                let rel = p.strip_prefix(root).unwrap_or(&p).display().to_string();
623                workflows.push((rel, text));
624            }
625        }
626    }
627    workflows
628}
629
630/// Read `root`'s manifest and workflows, and compare them.
631pub fn check_repo(root: &Path) -> Vec<Problem> {
632    let Ok(manifest) = std::fs::read_to_string(root.join(MANIFEST)) else {
633        return Vec::new();
634    };
635    let gates = tree_gates(&manifest);
636    if gates.is_empty() {
637        return Vec::new();
638    }
639    check_texts(&gates, &read_workflows(root))
640}
641
642/// The pre-commit check. A built-in test gate's drift warns (#288); a tree
643/// gate's blocks. `Inert` when there is neither a tree gate nor a step
644/// skipped on a built-in one.
645pub fn run(settings: &crate::config::Settings) -> Outcome {
646    let root = repo_root();
647    let root = Path::new(&root);
648    let drift = builtin_drift(root);
649    for p in &drift {
650        warn(&crate::ui::sanitize(&p.to_string()));
651    }
652    let declares = std::fs::read_to_string(root.join(MANIFEST))
653        .map(|t| !tree_gates(&t).is_empty())
654        .unwrap_or(false);
655    let problems = if declares {
656        check_repo(root)
657    } else {
658        Vec::new()
659    };
660    if problems.is_empty() {
661        return match (declares, drift.is_empty()) {
662            (_, false) => Outcome::Warned,
663            (true, true) => {
664                ok(settings, "tree gates match their CI steps");
665                Outcome::Passed
666            }
667            (false, true) => Outcome::Inert,
668        };
669    }
670    for p in &problems {
671        eprintln!("  {}", crate::ui::sanitize(&p.to_string()));
672    }
673    fail(&format!(
674        "{} tree-gate parity problem(s) — fix the workflow or the {} line; run {} to re-check",
675        problems.len(),
676        MANIFEST,
677        hl(concat!(crate::bin!(), " tree-parity"))
678    ));
679    Outcome::Failed
680}
681
682#[cfg(test)]
683mod tests {
684    use super::*;
685
686    fn drift(step_run: &str) -> Vec<Problem> {
687        let text = format!(
688            "name: ci\non:\n  push:\njobs:\n  test:\n    runs-on: ubuntu-latest\n    steps:\n      - id: attest\n        uses: fredericrous/attest@v1\n      - if: ${{{{ !contains(fromJSON(steps.attest.outputs.gates || '[]'), 'pre-push-cargo-test') }}}}\n        {step_run}\n"
689        );
690        builtin_drift_texts(&[(".github/workflows/ci.yaml".into(), text)])
691    }
692
693    /// #288: a step skipped on a built-in test gate must run that gate's
694    /// command, under the stated equivalences.
695    #[test]
696    fn a_builtin_gate_step_is_compared_with_the_local_command() {
697        assert_eq!(drift("run: cargo test"), vec![]);
698        assert_eq!(
699            drift("run: cargo test --workspace --all-features -q"),
700            vec![]
701        );
702        let locked = drift("run: cargo test --workspace --locked");
703        assert_eq!(locked.len(), 1, "{locked:?}");
704        assert!(locked[0].what.contains("pre-push-cargo-test"), "{locked:?}");
705        assert_eq!(drift("run: make test").len(), 1);
706        assert_eq!(
707            drift("run: |\n          cargo test").len(),
708            1,
709            "a block scalar differs"
710        );
711        assert_eq!(
712            drift("run: cargo test\n        env:\n          X: 1").len(),
713            1
714        );
715    }
716
717    #[test]
718    fn the_builtin_equivalences() {
719        assert!(builtin_matches("pre-push-go-test", "go test ./..."));
720        assert!(!builtin_matches("pre-push-go-test", "go test -race ./..."));
721        assert!(builtin_matches(
722            "pre-push-pytest",
723            "uv run --no-sync pytest"
724        ));
725        assert!(builtin_matches("pre-push-pytest", "python -m pytest -q"));
726        assert!(!builtin_matches(
727            "pre-push-pytest",
728            "uv run pytest --cov-fail-under=80"
729        ));
730        assert!(builtin_matches(
731            "pre-push-run-tests-js",
732            "pnpm run test:unit"
733        ));
734        assert!(builtin_matches("pre-push-run-tests-js", "npm test"));
735        assert!(!builtin_matches("pre-push-run-tests-js", "pnpm coverage"));
736        assert!(!builtin_matches(
737            "pre-push-cargo-test",
738            "cargo test | tee log"
739        ));
740    }
741
742    /// A step that runs only when attested reports the skip; it is not one.
743    #[test]
744    fn a_step_run_when_attested_is_not_a_skipped_one() {
745        assert_eq!(
746            skipped_builtin("if: ${{ contains(fromJSON(x), 'pre-push-cargo-test') }}"),
747            None
748        );
749        assert_eq!(
750            skipped_builtin("if: ${{ !contains(fromJSON(x), 'pre-push-cargo-test') }}"),
751            Some("pre-push-cargo-test")
752        );
753    }
754
755    fn gates(text: &str) -> Vec<TreeGate> {
756        let g = tree_gates(text);
757        assert!(!g.is_empty(), "no gate parsed from {text:?}");
758        g
759    }
760
761    fn check(manifest: &str, workflow: &str) -> Vec<Problem> {
762        check_texts(
763            &gates(manifest),
764            &[(
765                ".forgejo/workflows/ci.yaml".to_string(),
766                workflow.to_string(),
767            )],
768        )
769    }
770
771    const ESLINT: &str = "tree eslint eslint * attest npm run lint -- {cache}";
772
773    fn wf(step_run: &str) -> String {
774        format!(
775            "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: fredericrous/attest@v1\n      - name: Lint\n        if: ${{{{ !contains(fromJSON(steps.attest.outputs.gates || '[]'), 'tree-eslint') }}}}\n        {step_run}\n"
776        )
777    }
778
779    #[test]
780    fn parity_matching_run_passes() {
781        assert_eq!(check(ESLINT, &wf("run: npm run lint")), vec![]);
782    }
783
784    #[test]
785    fn parity_quoted_run_passes() {
786        assert_eq!(check(ESLINT, &wf("run: 'npm run lint'")), vec![]);
787    }
788
789    #[test]
790    fn parity_drifted_run_fails() {
791        let p = check(ESLINT, &wf("run: npm run lint -- --max-warnings 0"));
792        assert_eq!(p.len(), 1, "{p:?}");
793        assert!(p[0]
794            .what
795            .contains("runs `npm run lint -- --max-warnings 0` here"));
796    }
797
798    #[test]
799    fn parity_block_scalar_rejected() {
800        let p = check(ESLINT, &wf("run: |\n          npm run lint"));
801        assert_eq!(p.len(), 1, "{p:?}");
802        assert!(p[0].what.contains("block scalar"));
803    }
804
805    #[test]
806    fn parity_anchor_rejected() {
807        let p = check(ESLINT, &wf("run: *lint"));
808        assert!(p[0].what.contains("anchor"), "{p:?}");
809    }
810
811    #[test]
812    fn parity_interpolation_rejected() {
813        let p = check(ESLINT, &wf("run: npm run ${{ matrix.task }}"));
814        assert!(p[0].what.contains("interpolation"), "{p:?}");
815    }
816
817    #[test]
818    fn parity_step_env_rejected() {
819        let p = check(
820            ESLINT,
821            &wf("env:\n          CI: '1'\n        run: npm run lint"),
822        );
823        assert!(p[0].what.contains("step-level `env:`"), "{p:?}");
824    }
825
826    #[test]
827    fn parity_step_shell_rejected() {
828        let p = check(ESLINT, &wf("shell: bash\n        run: npm run lint"));
829        assert!(p[0].what.contains("step-level `shell:`"), "{p:?}");
830    }
831
832    #[test]
833    fn parity_undeclared_working_directory_rejected() {
834        let p = check(
835            ESLINT,
836            &wf("working-directory: web\n        run: npm run lint"),
837        );
838        assert!(p[0].what.contains("working-directory"), "{p:?}");
839    }
840
841    #[test]
842    fn parity_declared_cwd_passes() {
843        let p = check(
844            "tree eslint eslint * attest cwd=web npm run lint",
845            &wf("working-directory: web\n        run: npm run lint"),
846        );
847        assert_eq!(p, vec![]);
848    }
849
850    #[test]
851    fn parity_cwd_without_working_directory_rejected() {
852        let p = check(
853            "tree eslint eslint * attest cwd=web npm run lint",
854            &wf("run: npm run lint"),
855        );
856        assert!(p[0].what.contains("no `working-directory:`"), "{p:?}");
857    }
858
859    #[test]
860    fn parity_job_env_rejected() {
861        let w = wf("run: npm run lint").replace(
862            "    runs-on: ubuntu-latest\n",
863            "    runs-on: ubuntu-latest\n    env:\n      NODE_ENV: test\n",
864        );
865        let p = check(ESLINT, &w);
866        assert!(p[0].what.contains("inherits"), "{p:?}");
867    }
868
869    #[test]
870    fn parity_job_defaults_rejected() {
871        let w = wf("run: npm run lint").replace(
872            "    runs-on: ubuntu-latest\n",
873            "    runs-on: ubuntu-latest\n    defaults:\n      run:\n        working-directory: web\n",
874        );
875        let p = check(ESLINT, &w);
876        assert!(p[0].what.contains("inherits"), "{p:?}");
877    }
878
879    #[test]
880    fn parity_workflow_shell_bash_accepted_for_a_simple_command() {
881        let w = wf("run: npm run lint")
882            .replace("jobs:\n", "defaults:\n  run:\n    shell: bash\njobs:\n");
883        assert_eq!(check(ESLINT, &w), vec![]);
884    }
885
886    #[test]
887    fn parity_job_shell_bash_accepted_for_a_simple_command() {
888        let w = wf("run: npm run lint").replace(
889            "    runs-on: ubuntu-latest\n",
890            "    runs-on: ubuntu-latest\n    defaults:\n      run:\n        shell: bash\n",
891        );
892        assert_eq!(check(ESLINT, &w), vec![]);
893    }
894
895    #[test]
896    fn parity_shell_bash_rejected_for_a_pipeline() {
897        let w = wf("run: npm run lint | tee lint.log")
898            .replace("jobs:\n", "defaults:\n  run:\n    shell: bash\njobs:\n");
899        let p = check(
900            "tree eslint eslint * attest npm run lint | tee lint.log",
901            &w,
902        );
903        assert!(p[0].what.contains("simple command"), "{p:?}");
904    }
905
906    #[test]
907    fn parity_other_shell_rejected() {
908        let w =
909            wf("run: npm run lint").replace("jobs:\n", "defaults:\n  run:\n    shell: sh\njobs:\n");
910        let p = check(ESLINT, &w);
911        assert!(p[0].what.contains("inherits `env:` or"), "{p:?}");
912    }
913
914    #[test]
915    fn parity_shell_bash_plus_working_directory_rejected() {
916        let w = wf("run: npm run lint").replace(
917            "jobs:\n",
918            "defaults:\n  run:\n    shell: bash\n    working-directory: web\njobs:\n",
919        );
920        let p = check(ESLINT, &w);
921        assert!(p[0].what.contains("inherits `env:` or"), "{p:?}");
922    }
923
924    #[test]
925    fn parity_workflow_env_still_rejected_beside_shell_bash() {
926        let w = wf("run: npm run lint").replace(
927            "jobs:\n",
928            "defaults:\n  run:\n    shell: bash\nenv:\n  CI: '1'\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_undeclared_gate_rejected() {
936        let p = check(
937            "tree prettier prettier * attest npx prettier --check .",
938            &wf("run: npm run lint"),
939        );
940        assert!(
941            p.iter()
942                .any(|p| p.what.contains("`tree-eslint` is not declared")),
943            "{p:?}"
944        );
945        assert!(
946            p.iter().any(|p| p.what.contains("no workflow step")),
947            "{p:?}"
948        );
949    }
950
951    #[test]
952    fn parity_declared_gate_without_step_rejected() {
953        let p = check(
954            ESLINT,
955            "name: ci\njobs:\n  a:\n    steps:\n      - run: true\n",
956        );
957        assert_eq!(p.len(), 1, "{p:?}");
958        assert!(p[0].what.contains("no workflow step is skipped on it"));
959    }
960
961    #[test]
962    fn parity_job_level_reference_rejected() {
963        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";
964        let p = check(ESLINT, w);
965        assert!(p.iter().any(|p| p.what.contains("outside a step")), "{p:?}");
966    }
967
968    #[test]
969    fn parity_two_gates_on_one_step_rejected() {
970        let w = wf("run: npm run lint").replace(
971            "'tree-eslint') }}",
972            "'tree-eslint') && !contains(fromJSON(steps.attest.outputs.gates), 'tree-prettier') }}",
973        );
974        let p = check(
975            "tree eslint eslint * attest npm run lint\ntree prettier prettier * attest npx prettier --check .",
976            &w,
977        );
978        let several = p
979            .iter()
980            .find(|p| p.what.contains("several tree gates"))
981            .unwrap_or_else(|| panic!("{p:?}"));
982        // The problem names the step's own line (`- name: Lint`), where the
983        // reader has to look.
984        assert_eq!(several.line, 11, "{several:?}");
985    }
986}