Skip to main content

jouet_github/entire/
gates.rs

1//! The "Entire Gates" check: one check run that passes only when every
2//! blocking gate on the PR's trail does. Its summary lists each gate on a
3//! line of its own, readable with the forge's token alone:
4//!
5//! ```text
6//! - ❌ **Checks**: failed — CI checks have not passed
7//! - ❌ **Findings**: failed — Unresolved findings: 2 medium severity
8//! - ✅ **Up to date**: passed — 2 commits behind · Mergeable
9//!
10//! [Trail #424 on Entire](https://entire.io/gh/jdx/mise/trails/424)
11//! ```
12//!
13//! Two of the gates only repeat what is already known elsewhere: `checks`
14//! fails because another check failed, and `up_to_date` because the branch
15//! is behind its base or conflicts with it. `approvals` waits on a person,
16//! not on CI. Only `findings` (and any gate jouet does not know) is a
17//! failure of its own.
18
19use serde::{Deserialize, Serialize};
20
21/// The check run's name.
22pub const CHECK: &str = "Entire Gates";
23
24/// Gates whose failure repeats something already reported elsewhere.
25const DERIVED: [&str; 2] = ["checks", "up_to_date"];
26/// Gates that wait on a reviewer: an approval on the trail.
27const REVIEW: [&str; 1] = ["approvals"];
28
29#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
30pub struct Gate {
31    /// `checks`, `findings`, `up_to_date`, `approvals`, or another gate's
32    /// label in snake_case.
33    pub gate: String,
34    /// As Entire words it: `passed`, `failed`, `pending`, `skipped`.
35    pub status: String,
36    #[serde(skip_serializing_if = "Option::is_none", default)]
37    pub reason: Option<String>,
38}
39
40impl Gate {
41    pub fn failed(&self) -> bool {
42        self.status == "failed"
43    }
44}
45
46#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
47pub struct Gates {
48    /// The check's own state: `passed`, `failed`, `pending` or `neutral`
49    /// (the gates do not apply, as when no trail tracks the branch).
50    pub state: String,
51    #[serde(skip_serializing_if = "Option::is_none", default)]
52    pub title: Option<String>,
53    #[serde(skip_serializing_if = "Vec::is_empty", default)]
54    pub gates: Vec<Gate>,
55    /// The trail number the summary links to. Trail numbers are not PR
56    /// numbers.
57    #[serde(skip_serializing_if = "Option::is_none", default)]
58    pub trail: Option<u64>,
59    #[serde(skip_serializing_if = "Option::is_none", default)]
60    pub url: Option<String>,
61}
62
63impl Gates {
64    /// Reads the check from its status and conclusion (in either REST's
65    /// lowercase or GraphQL's uppercase), title, summary and details URL.
66    pub fn parse(
67        status: &str,
68        conclusion: Option<&str>,
69        title: Option<&str>,
70        summary: Option<&str>,
71        url: Option<&str>,
72    ) -> Self {
73        let state = if !status.eq_ignore_ascii_case("completed") {
74            "pending"
75        } else {
76            match conclusion.map(str::to_ascii_lowercase).as_deref() {
77                Some("success") => "passed",
78                Some("neutral" | "skipped" | "stale") => "neutral",
79                _ => "failed",
80            }
81        };
82        let summary = summary.unwrap_or_default();
83        Self {
84            state: state.into(),
85            title: title.filter(|t| !t.is_empty()).map(str::to_string),
86            gates: summary.lines().filter_map(gate_line).collect(),
87            trail: trail_number(summary),
88            url: url.filter(|u| !u.is_empty()).map(str::to_string),
89        }
90    }
91
92    pub fn failed(&self) -> bool {
93        self.state == "failed"
94    }
95
96    pub fn failing(&self) -> impl Iterator<Item = &Gate> {
97        self.gates.iter().filter(|g| g.failed())
98    }
99
100    /// Whether the gate named `gate` failed.
101    pub fn fails(&self, gate: &str) -> bool {
102        self.failing().any(|g| g.gate == gate)
103    }
104
105    /// Whether the check failed only for reasons reported elsewhere: other
106    /// checks failing, or the branch behind or conflicting. A failed check
107    /// whose summary names no failing gate is not derived: there is nothing
108    /// to point at instead.
109    pub fn derived(&self) -> bool {
110        self.only(&[&DERIVED])
111    }
112
113    /// Whether the check failed for nothing CI did: derived gates, or an
114    /// approval on the trail still to come. A wait for CI does not count it.
115    pub fn not_ci(&self) -> bool {
116        self.only(&[&DERIVED, &REVIEW])
117    }
118
119    fn only(&self, groups: &[&[&str]]) -> bool {
120        self.failed()
121            && self.failing().next().is_some()
122            && self
123                .failing()
124                .all(|g| groups.iter().any(|group| group.contains(&g.gate.as_str())))
125    }
126
127    /// Whether the summary was read: a failed check names its failing
128    /// gates. One that names none is in a form jouet does not know, and is
129    /// never guessed at.
130    pub fn read(&self) -> bool {
131        !self.failed() || self.failing().next().is_some()
132    }
133
134    /// The failing gates, as `findings: Unresolved findings: 2 medium
135    /// severity; checks: CI checks have not passed`, or, when the summary
136    /// names none, the check's title and that jouet could not read it.
137    pub fn failing_text(&self) -> String {
138        if self.failing().next().is_none() {
139            let title = self.title.clone().unwrap_or_else(|| self.state.clone());
140            return format!("{title} (jouet could not read the check's summary)");
141        }
142        self.failing()
143            .map(|g| match &g.reason {
144                Some(r) => format!("{}: {r}", label(&g.gate)),
145                None => format!("{} failed", label(&g.gate)),
146            })
147            .collect::<Vec<_>>()
148            .join("; ")
149    }
150}
151
152/// A gate's name as people read it.
153pub fn label(gate: &str) -> String {
154    match gate {
155        "up_to_date" => "up to date".into(),
156        other => other.replace('_', " "),
157    }
158}
159
160/// `- ❌ **Checks**: failed — CI checks have not passed`.
161fn gate_line(line: &str) -> Option<Gate> {
162    let line = line.trim();
163    let rest = line.strip_prefix("- ")?;
164    let (_, rest) = rest.split_once("**")?;
165    let (name, rest) = rest.split_once("**")?;
166    let rest = rest.strip_prefix(':')?.trim();
167    let (status, reason) = match rest.split_once('—') {
168        Some((status, reason)) => (status.trim(), Some(reason.trim())),
169        None => (rest, None),
170    };
171    if name.is_empty() || status.is_empty() {
172        return None;
173    }
174    Some(Gate {
175        gate: key(name),
176        status: status.to_ascii_lowercase(),
177        reason: reason.filter(|r| !r.is_empty()).map(str::to_string),
178    })
179}
180
181/// `Up to date` → `up_to_date`.
182fn key(name: &str) -> String {
183    name.trim()
184        .to_ascii_lowercase()
185        .split(|c: char| !c.is_ascii_alphanumeric())
186        .filter(|w| !w.is_empty())
187        .collect::<Vec<_>>()
188        .join("_")
189}
190
191/// The number in `[Trail #424 on Entire](...)`.
192fn trail_number(summary: &str) -> Option<u64> {
193    let (_, rest) = summary.split_once("Trail #")?;
194    let digits: String = rest.chars().take_while(char::is_ascii_digit).collect();
195    digits.parse().ok()
196}
197
198#[cfg(test)]
199mod tests {
200    use super::*;
201
202    // Recorded from jdx/mise#13958, jdx/mise#15220 and jdx/jouet#104.
203    const CHECKS_AND_FINDINGS: &str = "- ❌ **Checks**: failed — CI checks have not passed\n- ❌ **Findings**: failed — Unresolved findings: 2 medium severity\n\n[Trail #424 on Entire](https://entire.io/gh/jdx/mise/trails/424)";
204    const CHECKS: &str = "- ❌ **Checks**: failed — CI checks have not passed\n- ✅ **Findings**: passed — Agent review found no blocking issues\n\n[Trail #1176 on Entire](https://entire.com/gh/jdx/-/trails/3261/changes/mise/1176)";
205    const UP_TO_DATE: &str = "- ✅ **Checks**: passed — CI checks have passed\n- ✅ **Findings**: passed — No blocking findings\n- ❌ **Up to date**: failed — 3 commits behind · Merge conflicts\n\n[Trail #88 on Entire](https://entire.com/gh/jdx/-/trails/3284/changes/jouet/88)";
206
207    #[test]
208    fn the_summary_names_each_gate_and_the_trail() {
209        let g = Gates::parse(
210            "completed",
211            Some("failure"),
212            Some("2 blocking gates not passing"),
213            Some(CHECKS_AND_FINDINGS),
214            Some("https://entire.io/gh/jdx/mise/trails/424"),
215        );
216        assert_eq!(g.state, "failed");
217        assert_eq!(g.trail, Some(424));
218        assert_eq!(
219            g.gates[1],
220            Gate {
221                gate: "findings".into(),
222                status: "failed".into(),
223                reason: Some("Unresolved findings: 2 medium severity".into()),
224            }
225        );
226        assert!(!g.derived(), "findings are a failure of their own");
227        assert_eq!(
228            g.failing_text(),
229            "checks: CI checks have not passed; findings: Unresolved findings: 2 medium severity"
230        );
231    }
232
233    #[test]
234    fn failed_checks_and_a_stale_branch_are_derived() {
235        let checks = Gates::parse("COMPLETED", Some("FAILURE"), None, Some(CHECKS), None);
236        assert_eq!(checks.trail, Some(1176));
237        assert!(checks.derived());
238        let approval = Gates::parse(
239            "completed",
240            Some("failure"),
241            None,
242            Some(
243                "- ✅ **Checks**: passed — CI checks have passed\n- ❌ **Approvals**: failed — No reviewers have approved this trail",
244            ),
245            None,
246        );
247        assert!(!approval.derived(), "nothing else reports it");
248        assert!(approval.not_ci());
249        assert!(
250            !Gates::parse(
251                "completed",
252                Some("failure"),
253                None,
254                Some(CHECKS_AND_FINDINGS),
255                None
256            )
257            .not_ci()
258        );
259        let behind = Gates::parse("completed", Some("failure"), None, Some(UP_TO_DATE), None);
260        assert!(behind.fails("up_to_date"));
261        assert!(behind.derived());
262        assert_eq!(
263            behind.failing_text(),
264            "up to date: 3 commits behind · Merge conflicts"
265        );
266    }
267
268    #[test]
269    fn a_failure_with_no_gates_named_is_not_derived() {
270        let g = Gates::parse("completed", Some("failure"), None, None, None);
271        assert!(g.failed());
272        assert!(!g.derived());
273        assert!(!g.read());
274        // A summary in a form jouet does not know is not misread.
275        let changed = Gates::parse(
276            "completed",
277            Some("failure"),
278            Some("1 blocking gate not passing"),
279            Some("| Gate | Status |\n|---|---|\n| Findings | failed |"),
280            None,
281        );
282        assert!(changed.gates.is_empty() && !changed.read() && !changed.derived());
283        assert_eq!(
284            changed.failing_text(),
285            "1 blocking gate not passing (jouet could not read the check's summary)"
286        );
287        let evaluating = Gates::parse(
288            "in_progress",
289            None,
290            Some("Gates are evaluating"),
291            Some("- ⏳ **Checks**: pending — CI checks are still running"),
292            None,
293        );
294        assert_eq!(evaluating.state, "pending");
295        assert_eq!(evaluating.gates[0].status, "pending");
296        let none = Gates::parse(
297            "completed",
298            Some("neutral"),
299            Some("No trail tracks this branch"),
300            Some(
301                "Entire gates do not apply to this pull request: no open trail tracks its head branch.",
302            ),
303            None,
304        );
305        assert_eq!((none.state.as_str(), none.gates.len()), ("neutral", 0));
306    }
307}