1use serde::{Deserialize, Serialize};
20
21pub const CHECK: &str = "Entire Gates";
23
24const DERIVED: [&str; 2] = ["checks", "up_to_date"];
26const REVIEW: [&str; 1] = ["approvals"];
28
29#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
30pub struct Gate {
31 pub gate: String,
34 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 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 #[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 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 pub fn fails(&self, gate: &str) -> bool {
102 self.failing().any(|g| g.gate == gate)
103 }
104
105 pub fn derived(&self) -> bool {
110 self.only(&[&DERIVED])
111 }
112
113 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 pub fn read(&self) -> bool {
131 !self.failed() || self.failing().next().is_some()
132 }
133
134 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
152pub fn label(gate: &str) -> String {
154 match gate {
155 "up_to_date" => "up to date".into(),
156 other => other.replace('_', " "),
157 }
158}
159
160fn 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
181fn 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
191fn 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 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 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}