1use crate::entire::gates::{CHECK, Gate, Gates};
19use crate::entire::{self, Entire, Trail};
20use crate::forge::Forge;
21use crate::host::{Feature, Host};
22use crate::pr::status::{
23 Checks, EntireStatus, FetchResult, Fetched, Lookup, Mergeability, PrStatus, State,
24};
25use crate::pr::target::{Repo, Target};
26use crate::pr::threads::{self, Comment, Kind, PrThreads, Pushed, Side, Thread};
27use jouet_output::time;
28use serde_json::Value;
29use std::collections::BTreeMap;
30use std::process::Command;
31
32const MINE: &str = "100";
34
35pub struct EntireForge {
36 cli: Option<Result<Entire, String>>,
37 viewer: Option<String>,
38}
39
40impl Default for EntireForge {
41 fn default() -> Self {
42 Self::new()
43 }
44}
45
46impl EntireForge {
47 pub fn new() -> Self {
48 Self {
49 cli: None,
50 viewer: None,
51 }
52 }
53
54 pub fn cli(&mut self) -> Result<&Entire, String> {
56 self.cli
57 .get_or_insert_with(Entire::probe)
58 .as_ref()
59 .map_err(|e| format!("Entire-hosted repositories are read through `entire`, and {e}"))
60 }
61
62 fn read(&mut self, args: &[&str]) -> Result<Value, String> {
63 self.cli()?.read(args)
64 }
65
66 pub fn show(&mut self, target: &Target) -> Result<Option<Value>, String> {
69 let repo = target.repo();
70 let sel = entire::selector(repo);
71 let n = match target {
72 Target::Number(_, n) => *n,
73 Target::Branch(_, branch) => match self.cli()?.trail(repo, None, branch)? {
74 Some(trail) => trail.number,
75 None => return Ok(None),
76 },
77 };
78 match self.read(&["trail", "show", &n.to_string(), "--json", "--repo", &sel]) {
79 Ok(doc) => Ok(Some(doc)),
80 Err(e) if e.starts_with("no trail") => Ok(None),
81 Err(e) => Err(e),
82 }
83 }
84
85 pub fn fresh(&mut self, repo: &Repo, n: u64) -> Result<Option<Value>, String> {
87 let sel = entire::selector(repo);
88 let n = n.to_string();
89 match self
90 .cli()?
91 .output(&["trail", "show", &n, "--json", "--repo", &sel])
92 {
93 Ok(out) => serde_json::from_str(&out)
94 .map(Some)
95 .map_err(|e| format!("entire trail show printed JSON jouet could not read: {e}")),
96 Err(e) if e.starts_with("no trail") => Ok(None),
97 Err(e) => Err(e),
98 }
99 }
100
101 fn viewer(&mut self) -> String {
103 if self.viewer.is_none() {
104 let user = self
105 .read(&["auth", "status", "--json"])
106 .ok()
107 .and_then(|s| s["user"].as_str().map(login));
108 self.viewer = Some(user.unwrap_or_default());
109 }
110 self.viewer.clone().unwrap_or_default()
111 }
112
113 fn discussions(&mut self, repo: &Repo, trail: u64) -> Result<Vec<Value>, String> {
116 let sel = entire::selector(repo);
117 let doc = self.read(&[
118 "trail",
119 "comment",
120 "list",
121 "--trail",
122 &trail.to_string(),
123 "--json",
124 "--repo",
125 &sel,
126 ])?;
127 let mut list: Vec<Value> = doc["items"]
128 .as_array()
129 .into_iter()
130 .flatten()
131 .filter(|d| d["kind"] == "discussion")
132 .cloned()
133 .collect();
134 list.sort_by_key(|d| d["createdAt"].as_str().unwrap_or_default().to_string());
135 Ok(list)
136 }
137
138 fn review(&mut self, repo: &Repo, doc: &Value) -> Result<Option<String>, String> {
140 let n = doc["number"].as_u64().unwrap_or_default().to_string();
141 let sel = entire::selector(repo);
142 let approvals = self.read(&["trail", "approvals", &n, "--json", "--repo", &sel])?;
143 let approvals_gate = gate(doc, "approvals");
144 if approvals_gate.is_some_and(|g| g["value"]["changes_requested"] == true) {
147 return Ok(Some("changes_requested".into()));
148 }
149 let required = approvals_gate.is_some_and(|g| {
150 g["blocking"] == true && !matches!(g["status"].as_str(), Some("passed" | "skipped"))
151 });
152 Ok(decision(&approvals["approvals"], required))
153 }
154
155 fn status(&mut self, repo: &Repo, doc: &Value) -> Result<Fetched, String> {
156 let open = matches!(doc["status"].as_str(), Some("open" | "draft"));
157 let number = doc["number"].as_u64().unwrap_or_default();
158 let unresolved = if open {
159 self.discussions(repo, number)?
160 .iter()
161 .filter(|d| d["resolved"] != true)
162 .count()
163 } else {
164 0
165 };
166 let review = self.review(repo, doc)?;
167 Ok(Fetched::new(pr_status(repo, doc, unresolved, review)))
168 }
169
170 fn thread(&mut self, pr: &PrThreads, d: &Value, bots: &[String]) -> Result<Thread, String> {
172 let id = text(&d["id"]);
173 let sel = entire::selector(&pr.repo);
174 let n = pr.number.to_string();
175 let shown = self.read(&[
176 "trail", "comment", "show", &id, "--trail", &n, "--json", "--repo", &sel,
177 ])?;
178 thread(pr, d, &shown, bots)
179 }
180}
181
182fn pr_status(repo: &Repo, doc: &Value, unresolved: usize, review: Option<String>) -> PrStatus {
185 let number = doc["number"].as_u64().unwrap_or_default();
186 let state = match doc["status"].as_str() {
187 Some("merged") => State::Merged,
188 Some("closed") => State::Closed,
189 Some("draft") => State::Draft,
190 _ => State::Open,
191 };
192 let m = &doc["mergeability"];
193 let (mergeable, merge_state) = match m["conflict_status"].as_str() {
194 Some("conflicting") => (Mergeability::Conflicting, "dirty"),
195 Some("clean") if state == State::Draft => (Mergeability::Mergeable, "draft"),
196 Some("clean") if m["mergeable"] == false => (Mergeability::Mergeable, "blocked"),
198 Some("clean") => (Mergeability::Mergeable, "clean"),
199 _ => (Mergeability::Unknown, "unknown"),
200 };
201 let mut checks = Checks::default();
202 for run in runs(doc) {
203 let name = run["name"].as_str().unwrap_or_default().to_string();
204 if run["status"] != "completed" {
205 checks.pending += 1;
206 continue;
207 }
208 match run["conclusion"].as_str().unwrap_or_default() {
209 "success" => checks.pass += 1,
210 "skipped" | "neutral" | "stale" => checks.skipped += 1,
211 _ => {
212 checks.fail += 1;
213 checks.failing.push(name);
214 }
215 }
216 }
217 let gates = gates(doc);
218 if let Some(g) = &gates {
219 match g.state.as_str() {
220 "passed" => checks.pass += 1,
221 "failed" => {
222 checks.fail += 1;
223 checks.failing.push(CHECK.into());
224 }
225 _ => checks.pending += 1,
226 }
227 }
228 let open = matches!(state, State::Open | State::Draft);
229 let head_oid = m["head_sha"].as_str().unwrap_or_default().to_string();
230 let mut status = PrStatus {
231 repo: repo.to_string(),
232 forge: Some("entire"),
233 host: repo.host.clone(),
234 number,
235 title: text(&doc["title"]),
236 url: text(&doc["url"]),
237 state,
238 base: text(&doc["base"]),
239 head: branch(doc),
240 head_sha: head_oid.chars().take(10).collect(),
241 head_oid,
242 pushed_at: None,
243 mergeable,
244 merge_state: merge_state.into(),
245 checks,
246 review,
247 unresolved_threads: u32::try_from(unresolved).unwrap_or(u32::MAX),
248 auto_merge: false,
249 entire: gates.map(EntireStatus::from),
250 attention: Vec::new(),
251 };
252 if !open {
253 status.review = status.review.filter(|r| r != "review_required");
254 }
255 status
256}
257
258fn thread(pr: &PrThreads, d: &Value, shown: &Value, bots: &[String]) -> Result<Thread, String> {
261 let id = text(&d["id"]);
262 let url = text(&shown["discussion"]["url"]);
263 let url = if url.is_empty() { pr_url(pr) } else { url };
264 let mut comments = Vec::new();
265 for m in shown["messages"].as_array().into_iter().flatten() {
266 comments.push(comment(m, &url));
267 for r in m["replies"].as_array().into_iter().flatten() {
268 comments.push(comment(r, &url));
269 }
270 }
271 comments.sort_by_key(|c| c.created);
272 let title = text(&d["title"]);
273 if let Some(first) = comments.first_mut()
274 && !title.is_empty()
275 && !first.body.starts_with(&title)
276 {
277 first.body = format!("{title}\n\n{}", first.body);
278 }
279 let author = comments
280 .first()
281 .map_or_else(|| text(&d["lastMessageAuthor"]), |c| c.author.clone());
282 Ok(Thread {
283 id: handle(&id).ok_or_else(|| {
284 format!("Entire sent a discussion with an ID jouet cannot read: {id}")
285 })?,
286 node_id: id,
287 kind: Kind::Thread,
288 path: None,
289 line: None,
290 start_line: None,
291 original_line: None,
292 side: Side::Right,
293 outdated: false,
294 resolved: d["resolved"] == true,
295 is_bot: threads::is_bot(&author, bots),
296 author,
297 state: None,
298 url,
299 comments,
300 context: None,
301 })
302}
303
304fn login(user: &str) -> String {
306 user.split_once(':').map_or(user, |(_, l)| l).to_string()
307}
308
309fn text(v: &Value) -> String {
310 v.as_str().unwrap_or_default().to_string()
311}
312
313fn branch(doc: &Value) -> String {
315 Some(text(&doc["branch"]))
316 .filter(|b| !b.is_empty())
317 .unwrap_or_else(|| text(&doc["original_branch"]))
318}
319
320fn pr_url(pr: &PrThreads) -> String {
321 format!("https://entire.com/et/{}/trails/{}", pr.repo, pr.number)
322}
323
324pub fn runs(doc: &Value) -> &[Value] {
326 doc["mergeability"]["checks"]["runs"]
327 .as_array()
328 .map_or(&[], Vec::as_slice)
329}
330
331fn gate<'a>(doc: &'a Value, key: &str) -> Option<&'a Value> {
332 doc["mergeability"]["gates"]
333 .as_array()?
334 .iter()
335 .find(|g| g["gate_key"] == key)
336}
337
338pub fn gates(doc: &Value) -> Option<Gates> {
343 let trail = Trail::parse(doc)?;
344 let gates: Vec<Gate> = trail
345 .gates
346 .into_iter()
347 .filter(|g| g.gate != "approvals")
348 .map(|mut g| {
349 if !matches!(g.status.as_str(), "passed" | "failed" | "skipped") {
350 g.status = "pending".into();
351 }
352 g
353 })
354 .collect();
355 if gates.is_empty() {
356 return None;
357 }
358 let state = if gates.iter().any(Gate::failed) {
359 "failed"
360 } else if gates.iter().any(|g| g.status == "pending") {
361 "pending"
362 } else {
363 "passed"
364 };
365 Some(Gates {
366 state: state.into(),
367 title: None,
368 gates,
369 trail: Some(trail.number),
370 url: Some(trail.url).filter(|u| !u.is_empty()),
371 })
372}
373
374fn decision(approvals: &Value, required: bool) -> Option<String> {
378 let mut list: Vec<&Value> = approvals.as_array().into_iter().flatten().collect();
379 list.sort_by_key(|a| a["createdAt"].as_str().unwrap_or_default().to_string());
380 let mut latest: BTreeMap<&str, &str> = BTreeMap::new();
381 for a in list {
382 if let (Some(author), Some(event)) = (a["author"].as_str(), a["event"].as_str()) {
383 latest.insert(author, event);
384 }
385 }
386 if latest.values().any(|e| *e == "changes_requested") {
387 Some("changes_requested".into())
388 } else if latest.values().any(|e| *e == "approved") {
389 Some("approved".into())
390 } else {
391 required.then(|| "review_required".into())
392 }
393}
394
395pub(crate) fn handle(ulid: &str) -> Option<u64> {
399 const DIGITS: &str = "0123456789ABCDEFGHJKMNPQRSTVWXYZ";
400 if ulid.len() < 12 {
401 return None;
402 }
403 ulid[..12].chars().try_fold(0u64, |n, c| {
404 let d = DIGITS.find(c.to_ascii_uppercase())?;
405 Some(n << 5 | d as u64)
406 })
407}
408
409fn comment(m: &Value, url: &str) -> Comment {
410 let created_at = text(&m["createdAt"]);
411 Comment {
412 id: handle(m["id"].as_str().unwrap_or_default()).unwrap_or_default(),
413 author: m["author"].as_str().unwrap_or("ghost").to_string(),
414 created: time::parse_rfc3339(&created_at).unwrap_or(0),
415 created_at,
416 body: text(&m["body"]),
417 body_truncated: false,
418 suggestion: None,
419 url: url.to_string(),
420 }
421}
422
423fn git(args: &[&str]) -> Option<String> {
425 let out = Command::new("git").args(args).output().ok()?;
426 out.status
427 .success()
428 .then(|| String::from_utf8_lossy(&out.stdout).into_owned())
429}
430
431impl Host for EntireForge {
432 fn forge(&self) -> Forge {
433 Forge::Entire
434 }
435
436 fn lacks(&mut self, feature: Feature) -> Option<String> {
437 match feature {
438 Feature::Search => Some(
439 "--search takes GitHub's search syntax, which Entire has no equivalent of".into(),
440 ),
441 Feature::Resolve => None,
442 Feature::Land => Some(
443 "`pr land` merges GitHub PRs only so far, and the entire CLI has no merge command; merge the trail on entire.com".into(),
444 ),
445 Feature::Runs => Some(
446 "Entire gives a trail's checks but no runs or jobs of its own; wait on the trail with `jouet wait ci` instead".into(),
447 ),
448 Feature::Explain => Some(
449 "`ci explain` judges a failure by GitHub Actions' run history, which Entire does not give; use `jouet wait ci` for the failed checks".into(),
450 ),
451 Feature::RequiredChecks => Some(
452 "Entire's CLI does not say which checks are required, so --required would select none; name them with --check".into(),
453 ),
454 }
455 }
456
457 fn fetch(&mut self, lookups: Vec<Lookup>) -> Result<FetchResult, String> {
458 let mut result = FetchResult::default();
459 for lookup in lookups {
460 match lookup {
461 Lookup::Pr(target) => match self.show(&target)? {
462 Some(doc) => result.prs.push(self.status(target.repo(), &doc)?),
463 None => result.not_found.push(target.to_string()),
464 },
465 Lookup::Mine(repo) => {
466 let viewer = self.viewer();
467 if viewer.is_empty() {
468 return Err(
469 "--mine needs to know who you are, and `entire auth status` names no user; run `entire login`".into(),
470 );
471 }
472 let sel = entire::selector(&repo);
473 let list = self.read(&[
474 "trail",
475 "list",
476 "--author",
477 &viewer,
478 "--status",
479 "open,draft",
480 "--json",
481 "-n",
482 MINE,
483 "--repo",
484 &sel,
485 ])?;
486 for t in list.as_array().into_iter().flatten() {
487 let Some(n) = t["number"].as_u64() else {
488 continue;
489 };
490 if let Some(doc) = self.show(&Target::Number(repo.clone(), n))? {
491 result.prs.push(self.status(&repo, &doc)?);
492 }
493 }
494 }
495 Lookup::Search { .. } | Lookup::Threads { .. } | Lookup::Contexts { .. } => {}
496 }
497 }
498 Ok(result)
499 }
500
501 fn threads(
502 &mut self,
503 target: &Target,
504 _extra: bool,
505 bots: &[String],
506 ) -> Result<Option<PrThreads>, String> {
507 let Some(doc) = self.show(target)? else {
508 return Ok(None);
509 };
510 let repo = target.repo().clone();
511 let number = doc["number"].as_u64().unwrap_or_default();
512 let viewer = self.viewer();
513 let mut pr = PrThreads {
514 repo: repo.clone(),
515 number,
516 node_id: text(&doc["trail_id"]),
517 head_ref: branch(&doc),
518 head_oid: text(&doc["mergeability"]["head_sha"]),
519 base_oid: git(&["rev-parse", &format!("origin/{}", text(&doc["base"]))])
522 .map(|s| s.trim().to_string())
523 .unwrap_or_default(),
524 head_repo: None,
525 viewer,
526 threads: Vec::new(),
527 others: Vec::new(),
528 unreadable: 0,
529 };
530 for d in self.discussions(&repo, number)? {
531 let thread = self.thread(&pr, &d, bots)?;
532 pr.threads.push(thread);
533 }
534 Ok(Some(pr))
535 }
536
537 fn pushed_at(&mut self, pr: &PrThreads, sha: &str) -> Result<Pushed, threads::Lookup> {
540 let sha = threads::sha_prefix(sha)?;
541 let log = git(&["log", "--format=%H %ct", "--reverse", &pr.head_oid]).ok_or_else(|| {
542 threads::Lookup::NotFound(format!(
543 "this clone does not have the trail's head {}; fetch {} first",
544 &pr.head_oid[..pr.head_oid.len().min(10)],
545 pr.head_ref
546 ))
547 })?;
548 let commits: Vec<(String, i64)> = log
549 .lines()
550 .filter_map(|l| {
551 let (oid, at) = l.split_once(' ')?;
552 Some((oid.to_string(), at.parse().ok()?))
553 })
554 .collect();
555 threads::pushed_from(&commits, &[], &sha)
556 }
557
558 fn files(
559 &mut self,
560 _pr: &PrThreads,
561 oid: &str,
562 paths: &[String],
563 ) -> Result<Vec<(String, String)>, String> {
564 Ok(paths
565 .iter()
566 .filter_map(|p| Some((p.clone(), git(&["show", &format!("{oid}:{p}")])?)))
567 .collect())
568 }
569
570 fn merge_base(&mut self, pr: &PrThreads) -> Result<String, String> {
571 let found = (!pr.base_oid.is_empty())
572 .then(|| git(&["merge-base", &pr.head_oid, &pr.base_oid]))
573 .flatten()
574 .map(|s| s.trim().to_string())
575 .filter(|s| !s.is_empty());
576 found.ok_or_else(|| {
577 "Entire's CLI gives no merge base, and git found none in this clone; fetch the trail's base and head".into()
578 })
579 }
580
581 fn on_branch(&mut self, pr: &PrThreads, head: &str) -> Result<bool, String> {
582 Err(format!(
583 "this clone does not have the trail's head, and Entire's CLI cannot say whether {} is on {}; fetch the branch first",
584 &head[..head.len().min(10)],
585 pr.head_ref
586 ))
587 }
588
589 fn reply(&mut self, pr: &PrThreads, thread: &Thread, body: &str) -> Result<String, String> {
590 let sel = entire::selector(&pr.repo);
591 let n = pr.number.to_string();
592 self.cli()?.output(&[
593 "trail",
594 "comment",
595 "reply",
596 &thread.node_id,
597 "-m",
598 body,
599 "--trail",
600 &n,
601 "--repo",
602 &sel,
603 ])?;
604 Ok(thread.url.clone())
605 }
606
607 fn set_resolved(
608 &mut self,
609 pr: &PrThreads,
610 thread: &Thread,
611 resolved: bool,
612 ) -> Result<(), String> {
613 let verb = if resolved { "resolve" } else { "unresolve" };
614 let sel = entire::selector(&pr.repo);
615 let n = pr.number.to_string();
616 self.cli()?.output(&[
617 "trail",
618 "comment",
619 verb,
620 &thread.node_id,
621 "--trail",
622 &n,
623 "--repo",
624 &sel,
625 ])?;
626 Ok(())
627 }
628}
629
630#[cfg(test)]
631mod tests {
632 use super::*;
633 use serde_json::json;
634
635 const SHOW: &str = include_str!("entire_forge/fixtures/show.json");
636 const SHOW_FAILING: &str = include_str!("entire_forge/fixtures/show-failing.json");
637 const COMMENTS: &str = include_str!("entire_forge/fixtures/comment-list.json");
638 const NAMING: &str =
639 include_str!("entire_forge/fixtures/comment-01M69GVB1SNG4YRX6R3J5ZHSDP.json");
640
641 fn doc(s: &str) -> Value {
642 serde_json::from_str(s).unwrap()
643 }
644
645 fn repo() -> Repo {
646 Repo::parse("entire.com/jdx/jouet-entire-forge-test").unwrap()
647 }
648
649 #[test]
650 fn a_trail_with_no_gates_configured_is_open_and_clean() {
651 let s = pr_status(&repo(), &doc(SHOW), 1, None);
652 assert_eq!(
653 (s.number, s.state, s.forge),
654 (1, State::Open, Some("entire"))
655 );
656 assert_eq!(s.host.as_deref(), Some("entire.com"));
657 assert_eq!(s.head, "feat/subtract");
658 assert_eq!(s.head_sha, "e971859eed");
659 assert_eq!(
660 s.url,
661 "https://entire.com/et/jdx/jouet-entire-forge-test/trails/1"
662 );
663 assert_eq!(
664 (s.mergeable, s.merge_state.as_str()),
665 (Mergeability::Mergeable, "clean")
666 );
667 assert_eq!((s.checks.pass, s.checks.total()), (1, 1));
669 assert!(!s.entire.as_ref().unwrap().gates.failed());
670 assert_eq!(s.unresolved_threads, 1);
671 }
672
673 #[test]
674 fn failing_gates_and_runs_are_checks_and_the_approvals_gate_is_the_review() {
675 let d = doc(SHOW_FAILING);
676 let s = pr_status(&repo(), &d, 0, None);
677 assert_eq!(s.checks.failing, ["buildkite/test", CHECK]);
678 assert_eq!((s.checks.fail, s.checks.pending), (2, 1));
679 assert_eq!(s.merge_state, "blocked");
680 let g = gates(&d).unwrap();
681 assert_eq!(g.trail, Some(1));
682 let failing: Vec<&str> = g.failing().map(|g| g.gate.as_str()).collect();
683 assert_eq!(failing, ["findings", "up_to_date"]);
684 assert!(!g.derived());
685 assert_eq!(
686 g.failing_text(),
687 "findings: Unresolved findings: 1 medium severity; up to date: 1 commit behind"
688 );
689 let approvals = gate(&d, "approvals").unwrap();
690 assert_eq!(approvals["status"], "failed");
691 }
692
693 #[test]
694 fn a_closed_trail_needs_no_review() {
695 let mut d = doc(SHOW);
696 d["status"] = "closed".into();
697 let s = pr_status(&repo(), &d, 0, Some("review_required".into()));
698 assert_eq!((s.state, s.review), (State::Closed, None));
699 }
700
701 #[test]
702 fn a_discussion_is_a_thread_with_its_title_first() {
703 let list = doc(COMMENTS);
704 let naming = list["items"]
705 .as_array()
706 .unwrap()
707 .iter()
708 .find(|d| d["title"] == "Naming")
709 .unwrap();
710 let pr = PrThreads {
711 repo: repo(),
712 number: 1,
713 node_id: String::new(),
714 head_ref: "feat/subtract".into(),
715 head_oid: String::new(),
716 base_oid: String::new(),
717 head_repo: None,
718 viewer: "jdx".into(),
719 threads: Vec::new(),
720 others: Vec::new(),
721 unreadable: 0,
722 };
723 let t = thread(&pr, naming, &doc(NAMING), &[]).unwrap();
724 assert_eq!(t.node_id, "01M69GVB1SNG4YRX6R3J5ZHSDP");
725 assert_eq!(Some(t.id), handle("01M69GVB1SNG4YRX6R3J5ZHSDP"));
726 assert!(t.resolved && t.path.is_none());
727 assert_eq!(t.author, "jdx");
728 assert_eq!(t.comments.len(), 2);
729 assert!(
730 t.comments[0]
731 .body
732 .starts_with("Naming\n\nShould subtract be called sub")
733 );
734 assert_eq!(
735 t.comments[1].body,
736 "Keeping subtract: the other helpers are spelled out too."
737 );
738 assert_eq!(
739 t.url,
740 "https://entire.com/et/jdx/jouet-entire-forge-test/trails/1"
741 );
742 }
743
744 #[test]
745 fn entire_names_users_by_provider_and_trails_by_login() {
746 assert_eq!(login("github:jdx"), "jdx");
747 assert_eq!(login("jdx"), "jdx");
748 }
749
750 #[test]
751 fn discussion_handles_are_stable_numbers() {
752 let a = handle("01M67M0N092XMZ9EQMDZKWV4H9").unwrap();
753 assert_eq!(handle("01m67m0n092xmz9eqmdzkwv4h9"), Some(a));
754 assert_ne!(handle("01M67M0N093XMZ9EQMDZKWV4H9"), Some(a));
755 assert_eq!(handle("short"), None);
756 assert_eq!(handle("01M67M0N092XAAAAAAAAAAAAAA"), Some(a));
757 assert_eq!(handle("01M67M0N0U2XMZ9EQMDZKWV4H9"), None);
758 }
759
760 #[test]
761 fn the_latest_decision_of_each_reviewer_counts() {
762 let a = |who: &str, event: &str, at: &str| json!({ "author": who, "event": event, "createdAt": at });
763 let list = json!([
764 a("x", "changes_requested", "2026-10-31T10:00:00Z"),
765 a("x", "approved", "2026-10-31T11:00:00Z"),
766 ]);
767 assert_eq!(decision(&list, true).as_deref(), Some("approved"));
768 let list = json!([
769 a("x", "approved", "2026-10-31T10:00:00Z"),
770 a("y", "changes_requested", "2026-10-31T09:00:00Z"),
771 ]);
772 assert_eq!(decision(&list, false).as_deref(), Some("changes_requested"));
773 assert_eq!(
774 decision(&json!([]), true).as_deref(),
775 Some("review_required")
776 );
777 assert_eq!(decision(&json!([]), false), None);
778 }
779}