jouet-github 0.0.4

jouet's GitHub, GitLab and Forgejo clients and the pull request model behind its pr and wait commands
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
//! Repositories hosted on Entire itself (`/et/PROJECT/REPO`) behind
//! [`Host`], through the `entire` CLI (see [`crate::entire`]), which finds
//! its own login: jouet never handles an Entire token.
//!
//! A trail is the PR, and its number the PR's number. Its discussions are
//! the review threads: each has a title, messages and replies, and can be
//! resolved. Its review findings (the `code_review` discussions) are not
//! listed here: `pr threads` lists them through [`crate::entire`], as for a
//! GitHub PR, with `entire:` handles. The checks are the trail's check runs
//! (Buildkite and the like) and one "Entire Gates" check made of its
//! blocking gates, so a failing gate reads as it does on GitHub; the
//! approvals gate is the review decision instead.
//!
//! The CLI has no route to a commit's files, the merge base or the
//! branch's commits, so those come from this clone's git, and say so when
//! it lacks the commit.

use crate::entire::gates::{CHECK, Gate, Gates};
use crate::entire::{self, Entire, Trail};
use crate::forge::Forge;
use crate::host::{Feature, Host};
use crate::pr::status::{
    Checks, EntireStatus, FetchResult, Fetched, Lookup, Mergeability, PrStatus, State,
};
use crate::pr::target::{Repo, Target};
use crate::pr::threads::{self, Comment, Kind, PrThreads, Pushed, Side, Thread};
use jouet_output::time;
use serde_json::Value;
use std::collections::BTreeMap;
use std::process::Command;

/// Trails listed for `--mine`.
const MINE: &str = "100";

pub struct EntireForge {
    cli: Option<Result<Entire, String>>,
    viewer: Option<String>,
}

impl Default for EntireForge {
    fn default() -> Self {
        Self::new()
    }
}

impl EntireForge {
    pub fn new() -> Self {
        Self {
            cli: None,
            viewer: None,
        }
    }

    /// The `entire` CLI, found and logged in once.
    pub fn cli(&mut self) -> Result<&Entire, String> {
        self.cli
            .get_or_insert_with(Entire::probe)
            .as_ref()
            .map_err(|e| format!("Entire-hosted repositories are read through `entire`, and {e}"))
    }

    fn read(&mut self, args: &[&str]) -> Result<Value, String> {
        self.cli()?.read(args)
    }

    /// The trail a target names, as `entire trail show --json` prints it.
    /// `None` when there is none.
    pub fn show(&mut self, target: &Target) -> Result<Option<Value>, String> {
        let repo = target.repo();
        let sel = entire::selector(repo);
        let n = match target {
            Target::Number(_, n) => *n,
            Target::Branch(_, branch) => match self.cli()?.trail(repo, None, branch)? {
                Some(trail) => trail.number,
                None => return Ok(None),
            },
        };
        match self.read(&["trail", "show", &n.to_string(), "--json", "--repo", &sel]) {
            Ok(doc) => Ok(Some(doc)),
            Err(e) if e.starts_with("no trail") => Ok(None),
            Err(e) => Err(e),
        }
    }

    /// Trail `n` as it is now, past the cache, for a wait's polls.
    pub fn fresh(&mut self, repo: &Repo, n: u64) -> Result<Option<Value>, String> {
        let sel = entire::selector(repo);
        let n = n.to_string();
        match self
            .cli()?
            .output(&["trail", "show", &n, "--json", "--repo", &sel])
        {
            Ok(out) => serde_json::from_str(&out)
                .map(Some)
                .map_err(|e| format!("entire trail show printed JSON jouet could not read: {e}")),
            Err(e) if e.starts_with("no trail") => Ok(None),
            Err(e) => Err(e),
        }
    }

    /// The login `entire` acts as, such as `jdx`; empty when it says none.
    fn viewer(&mut self) -> String {
        if self.viewer.is_none() {
            let user = self
                .read(&["auth", "status", "--json"])
                .ok()
                .and_then(|s| s["user"].as_str().map(login));
            self.viewer = Some(user.unwrap_or_default());
        }
        self.viewer.clone().unwrap_or_default()
    }

    /// The trail's discussions, oldest first: the conversations, without
    /// the findings Entire keeps as `code_review` discussions.
    fn discussions(&mut self, repo: &Repo, trail: u64) -> Result<Vec<Value>, String> {
        let sel = entire::selector(repo);
        let doc = self.read(&[
            "trail",
            "comment",
            "list",
            "--trail",
            &trail.to_string(),
            "--json",
            "--repo",
            &sel,
        ])?;
        let mut list: Vec<Value> = doc["items"]
            .as_array()
            .into_iter()
            .flatten()
            .filter(|d| d["kind"] == "discussion")
            .cloned()
            .collect();
        list.sort_by_key(|d| d["createdAt"].as_str().unwrap_or_default().to_string());
        Ok(list)
    }

    /// The review decision, from `entire trail approvals`.
    fn review(&mut self, repo: &Repo, doc: &Value) -> Result<Option<String>, String> {
        let n = doc["number"].as_u64().unwrap_or_default().to_string();
        let sel = entire::selector(repo);
        let approvals = self.read(&["trail", "approvals", &n, "--json", "--repo", &sel])?;
        let approvals_gate = gate(doc, "approvals");
        // The gate says changes were asked for even when the decision that
        // asked is gone from the list, as a dismissed one would be.
        if approvals_gate.is_some_and(|g| g["value"]["changes_requested"] == true) {
            return Ok(Some("changes_requested".into()));
        }
        let required = approvals_gate.is_some_and(|g| {
            g["blocking"] == true && !matches!(g["status"].as_str(), Some("passed" | "skipped"))
        });
        Ok(decision(&approvals["approvals"], required))
    }

    fn status(&mut self, repo: &Repo, doc: &Value) -> Result<Fetched, String> {
        let open = matches!(doc["status"].as_str(), Some("open" | "draft"));
        let number = doc["number"].as_u64().unwrap_or_default();
        let unresolved = if open {
            self.discussions(repo, number)?
                .iter()
                .filter(|d| d["resolved"] != true)
                .count()
        } else {
            0
        };
        let review = self.review(repo, doc)?;
        Ok(Fetched::new(pr_status(repo, doc, unresolved, review)))
    }

    /// A discussion as a thread, with every message and reply in it.
    fn thread(&mut self, pr: &PrThreads, d: &Value, bots: &[String]) -> Result<Thread, String> {
        let id = text(&d["id"]);
        let sel = entire::selector(&pr.repo);
        let n = pr.number.to_string();
        let shown = self.read(&[
            "trail", "comment", "show", &id, "--trail", &n, "--json", "--repo", &sel,
        ])?;
        thread(pr, d, &shown, bots)
    }
}

/// A trail as `pr status` reports it, given its unresolved discussions and
/// review decision.
fn pr_status(repo: &Repo, doc: &Value, unresolved: usize, review: Option<String>) -> PrStatus {
    let number = doc["number"].as_u64().unwrap_or_default();
    let state = match doc["status"].as_str() {
        Some("merged") => State::Merged,
        Some("closed") => State::Closed,
        Some("draft") => State::Draft,
        _ => State::Open,
    };
    let m = &doc["mergeability"];
    let (mergeable, merge_state) = match m["conflict_status"].as_str() {
        Some("conflicting") => (Mergeability::Conflicting, "dirty"),
        Some("clean") if state == State::Draft => (Mergeability::Mergeable, "draft"),
        // Clean, but a gate holds it back; the gates say which.
        Some("clean") if m["mergeable"] == false => (Mergeability::Mergeable, "blocked"),
        Some("clean") => (Mergeability::Mergeable, "clean"),
        _ => (Mergeability::Unknown, "unknown"),
    };
    let mut checks = Checks::default();
    for run in runs(doc) {
        let name = run["name"].as_str().unwrap_or_default().to_string();
        if run["status"] != "completed" {
            checks.pending += 1;
            continue;
        }
        match run["conclusion"].as_str().unwrap_or_default() {
            "success" => checks.pass += 1,
            "skipped" | "neutral" | "stale" => checks.skipped += 1,
            _ => {
                checks.fail += 1;
                checks.failing.push(name);
            }
        }
    }
    let gates = gates(doc);
    if let Some(g) = &gates {
        match g.state.as_str() {
            "passed" => checks.pass += 1,
            "failed" => {
                checks.fail += 1;
                checks.failing.push(CHECK.into());
            }
            _ => checks.pending += 1,
        }
    }
    let open = matches!(state, State::Open | State::Draft);
    let head_oid = m["head_sha"].as_str().unwrap_or_default().to_string();
    let mut status = PrStatus {
        repo: repo.to_string(),
        forge: Some("entire"),
        host: repo.host.clone(),
        number,
        title: text(&doc["title"]),
        url: text(&doc["url"]),
        state,
        base: text(&doc["base"]),
        head: branch(doc),
        head_sha: head_oid.chars().take(10).collect(),
        head_oid,
        pushed_at: None,
        mergeable,
        merge_state: merge_state.into(),
        checks,
        review,
        unresolved_threads: u32::try_from(unresolved).unwrap_or(u32::MAX),
        auto_merge: false,
        entire: gates.map(EntireStatus::from),
        attention: Vec::new(),
    };
    if !open {
        status.review = status.review.filter(|r| r != "review_required");
    }
    status
}

/// Discussion `d`, as `trail comment list` lists it, made a thread from
/// `shown`, what `trail comment show` prints for it.
fn thread(pr: &PrThreads, d: &Value, shown: &Value, bots: &[String]) -> Result<Thread, String> {
    let id = text(&d["id"]);
    let url = text(&shown["discussion"]["url"]);
    let url = if url.is_empty() { pr_url(pr) } else { url };
    let mut comments = Vec::new();
    for m in shown["messages"].as_array().into_iter().flatten() {
        comments.push(comment(m, &url));
        for r in m["replies"].as_array().into_iter().flatten() {
            comments.push(comment(r, &url));
        }
    }
    comments.sort_by_key(|c| c.created);
    let title = text(&d["title"]);
    if let Some(first) = comments.first_mut()
        && !title.is_empty()
        && !first.body.starts_with(&title)
    {
        first.body = format!("{title}\n\n{}", first.body);
    }
    let author = comments
        .first()
        .map_or_else(|| text(&d["lastMessageAuthor"]), |c| c.author.clone());
    Ok(Thread {
        id: handle(&id).ok_or_else(|| {
            format!("Entire sent a discussion with an ID jouet cannot read: {id}")
        })?,
        node_id: id,
        kind: Kind::Thread,
        path: None,
        line: None,
        start_line: None,
        original_line: None,
        side: Side::Right,
        outdated: false,
        resolved: d["resolved"] == true,
        is_bot: threads::is_bot(&author, bots),
        author,
        state: None,
        url,
        comments,
        context: None,
    })
}

/// `github:jdx` as Entire names a user, as the login trails show: `jdx`.
fn login(user: &str) -> String {
    user.split_once(':').map_or(user, |(_, l)| l).to_string()
}

fn text(v: &Value) -> String {
    v.as_str().unwrap_or_default().to_string()
}

/// The trail's branch, or for a merged trail the one it had.
fn branch(doc: &Value) -> String {
    Some(text(&doc["branch"]))
        .filter(|b| !b.is_empty())
        .unwrap_or_else(|| text(&doc["original_branch"]))
}

fn pr_url(pr: &PrThreads) -> String {
    format!("https://entire.com/et/{}/trails/{}", pr.repo, pr.number)
}

/// The trail's check runs, as `mergeability.checks.runs` lists them.
pub fn runs(doc: &Value) -> &[Value] {
    doc["mergeability"]["checks"]["runs"]
        .as_array()
        .map_or(&[], Vec::as_slice)
}

fn gate<'a>(doc: &'a Value, key: &str) -> Option<&'a Value> {
    doc["mergeability"]["gates"]
        .as_array()?
        .iter()
        .find(|g| g["gate_key"] == key)
}

/// The trail's blocking gates as one Entire Gates check, the way the check
/// GitHub shows reads them: failed if any fails, pending while any has not
/// been evaluated, else passed. The approvals gate is left out, since it is
/// the review decision. `None` when the trail has no other blocking gate.
pub fn gates(doc: &Value) -> Option<Gates> {
    let trail = Trail::parse(doc)?;
    let gates: Vec<Gate> = trail
        .gates
        .into_iter()
        .filter(|g| g.gate != "approvals")
        .map(|mut g| {
            if !matches!(g.status.as_str(), "passed" | "failed" | "skipped") {
                g.status = "pending".into();
            }
            g
        })
        .collect();
    if gates.is_empty() {
        return None;
    }
    let state = if gates.iter().any(Gate::failed) {
        "failed"
    } else if gates.iter().any(|g| g.status == "pending") {
        "pending"
    } else {
        "passed"
    };
    Some(Gates {
        state: state.into(),
        title: None,
        gates,
        trail: Some(trail.number),
        url: Some(trail.url).filter(|u| !u.is_empty()),
    })
}

/// The review decision: changes requested if anyone's latest decision asks
/// for them, else approved if one approves, else `review_required` when
/// the approvals gate blocks.
fn decision(approvals: &Value, required: bool) -> Option<String> {
    let mut list: Vec<&Value> = approvals.as_array().into_iter().flatten().collect();
    list.sort_by_key(|a| a["createdAt"].as_str().unwrap_or_default().to_string());
    let mut latest: BTreeMap<&str, &str> = BTreeMap::new();
    for a in list {
        if let (Some(author), Some(event)) = (a["author"].as_str(), a["event"].as_str()) {
            latest.insert(author, event);
        }
    }
    if latest.values().any(|e| *e == "changes_requested") {
        Some("changes_requested".into())
    } else if latest.values().any(|e| *e == "approved") {
        Some("approved".into())
    } else {
        required.then(|| "review_required".into())
    }
}

/// The number jouet names a discussion by: the first 12 characters of its
/// ULID, the 48-bit time it was made and 12 random bits, read as Crockford
/// base 32. Stable for as long as the discussion lasts.
pub(crate) fn handle(ulid: &str) -> Option<u64> {
    const DIGITS: &str = "0123456789ABCDEFGHJKMNPQRSTVWXYZ";
    if ulid.len() < 12 {
        return None;
    }
    ulid[..12].chars().try_fold(0u64, |n, c| {
        let d = DIGITS.find(c.to_ascii_uppercase())?;
        Some(n << 5 | d as u64)
    })
}

fn comment(m: &Value, url: &str) -> Comment {
    let created_at = text(&m["createdAt"]);
    Comment {
        id: handle(m["id"].as_str().unwrap_or_default()).unwrap_or_default(),
        author: m["author"].as_str().unwrap_or("ghost").to_string(),
        created: time::parse_rfc3339(&created_at).unwrap_or(0),
        created_at,
        body: text(&m["body"]),
        body_truncated: false,
        suggestion: None,
        url: url.to_string(),
    }
}

/// `git ARGS` in this clone, its stdout when it succeeds.
fn git(args: &[&str]) -> Option<String> {
    let out = Command::new("git").args(args).output().ok()?;
    out.status
        .success()
        .then(|| String::from_utf8_lossy(&out.stdout).into_owned())
}

impl Host for EntireForge {
    fn forge(&self) -> Forge {
        Forge::Entire
    }

    fn lacks(&mut self, feature: Feature) -> Option<String> {
        match feature {
            Feature::Search => Some(
                "--search takes GitHub's search syntax, which Entire has no equivalent of".into(),
            ),
            Feature::Resolve => None,
            Feature::Land => Some(
                "`pr land` merges GitHub PRs only so far, and the entire CLI has no merge command; merge the trail on entire.com".into(),
            ),
            Feature::Runs => Some(
                "Entire gives a trail's checks but no runs or jobs of its own; wait on the trail with `jouet wait ci` instead".into(),
            ),
            Feature::Explain => Some(
                "`ci explain` judges a failure by GitHub Actions' run history, which Entire does not give; use `jouet wait ci` for the failed checks".into(),
            ),
            Feature::RequiredChecks => Some(
                "Entire's CLI does not say which checks are required, so --required would select none; name them with --check".into(),
            ),
        }
    }

    fn fetch(&mut self, lookups: Vec<Lookup>) -> Result<FetchResult, String> {
        let mut result = FetchResult::default();
        for lookup in lookups {
            match lookup {
                Lookup::Pr(target) => match self.show(&target)? {
                    Some(doc) => result.prs.push(self.status(target.repo(), &doc)?),
                    None => result.not_found.push(target.to_string()),
                },
                Lookup::Mine(repo) => {
                    let viewer = self.viewer();
                    if viewer.is_empty() {
                        return Err(
                            "--mine needs to know who you are, and `entire auth status` names no user; run `entire login`".into(),
                        );
                    }
                    let sel = entire::selector(&repo);
                    let list = self.read(&[
                        "trail",
                        "list",
                        "--author",
                        &viewer,
                        "--status",
                        "open,draft",
                        "--json",
                        "-n",
                        MINE,
                        "--repo",
                        &sel,
                    ])?;
                    for t in list.as_array().into_iter().flatten() {
                        let Some(n) = t["number"].as_u64() else {
                            continue;
                        };
                        if let Some(doc) = self.show(&Target::Number(repo.clone(), n))? {
                            result.prs.push(self.status(&repo, &doc)?);
                        }
                    }
                }
                Lookup::Search { .. } | Lookup::Threads { .. } | Lookup::Contexts { .. } => {}
            }
        }
        Ok(result)
    }

    fn threads(
        &mut self,
        target: &Target,
        _extra: bool,
        bots: &[String],
    ) -> Result<Option<PrThreads>, String> {
        let Some(doc) = self.show(target)? else {
            return Ok(None);
        };
        let repo = target.repo().clone();
        let number = doc["number"].as_u64().unwrap_or_default();
        let viewer = self.viewer();
        let mut pr = PrThreads {
            repo: repo.clone(),
            number,
            node_id: text(&doc["trail_id"]),
            head_ref: branch(&doc),
            head_oid: text(&doc["mergeability"]["head_sha"]),
            // The base branch's head as this clone last fetched it, for the
            // merge base.
            base_oid: git(&["rev-parse", &format!("origin/{}", text(&doc["base"]))])
                .map(|s| s.trim().to_string())
                .unwrap_or_default(),
            head_repo: None,
            viewer,
            threads: Vec::new(),
            others: Vec::new(),
            unreadable: 0,
        };
        for d in self.discussions(&repo, number)? {
            let thread = self.thread(&pr, &d, bots)?;
            pr.threads.push(thread);
        }
        Ok(Some(pr))
    }

    /// Entire keeps no push log the CLI gives, so a commit's push time is
    /// its commit time in this clone, which can only be earlier.
    fn pushed_at(&mut self, pr: &PrThreads, sha: &str) -> Result<Pushed, threads::Lookup> {
        let sha = threads::sha_prefix(sha)?;
        let log = git(&["log", "--format=%H %ct", "--reverse", &pr.head_oid]).ok_or_else(|| {
            threads::Lookup::NotFound(format!(
                "this clone does not have the trail's head {}; fetch {} first",
                &pr.head_oid[..pr.head_oid.len().min(10)],
                pr.head_ref
            ))
        })?;
        let commits: Vec<(String, i64)> = log
            .lines()
            .filter_map(|l| {
                let (oid, at) = l.split_once(' ')?;
                Some((oid.to_string(), at.parse().ok()?))
            })
            .collect();
        threads::pushed_from(&commits, &[], &sha)
    }

    fn files(
        &mut self,
        _pr: &PrThreads,
        oid: &str,
        paths: &[String],
    ) -> Result<Vec<(String, String)>, String> {
        Ok(paths
            .iter()
            .filter_map(|p| Some((p.clone(), git(&["show", &format!("{oid}:{p}")])?)))
            .collect())
    }

    fn merge_base(&mut self, pr: &PrThreads) -> Result<String, String> {
        let found = (!pr.base_oid.is_empty())
            .then(|| git(&["merge-base", &pr.head_oid, &pr.base_oid]))
            .flatten()
            .map(|s| s.trim().to_string())
            .filter(|s| !s.is_empty());
        found.ok_or_else(|| {
            "Entire's CLI gives no merge base, and git found none in this clone; fetch the trail's base and head".into()
        })
    }

    fn on_branch(&mut self, pr: &PrThreads, head: &str) -> Result<bool, String> {
        Err(format!(
            "this clone does not have the trail's head, and Entire's CLI cannot say whether {} is on {}; fetch the branch first",
            &head[..head.len().min(10)],
            pr.head_ref
        ))
    }

    fn reply(&mut self, pr: &PrThreads, thread: &Thread, body: &str) -> Result<String, String> {
        let sel = entire::selector(&pr.repo);
        let n = pr.number.to_string();
        self.cli()?.output(&[
            "trail",
            "comment",
            "reply",
            &thread.node_id,
            "-m",
            body,
            "--trail",
            &n,
            "--repo",
            &sel,
        ])?;
        Ok(thread.url.clone())
    }

    fn set_resolved(
        &mut self,
        pr: &PrThreads,
        thread: &Thread,
        resolved: bool,
    ) -> Result<(), String> {
        let verb = if resolved { "resolve" } else { "unresolve" };
        let sel = entire::selector(&pr.repo);
        let n = pr.number.to_string();
        self.cli()?.output(&[
            "trail",
            "comment",
            verb,
            &thread.node_id,
            "--trail",
            &n,
            "--repo",
            &sel,
        ])?;
        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use serde_json::json;

    const SHOW: &str = include_str!("entire_forge/fixtures/show.json");
    const SHOW_FAILING: &str = include_str!("entire_forge/fixtures/show-failing.json");
    const COMMENTS: &str = include_str!("entire_forge/fixtures/comment-list.json");
    const NAMING: &str =
        include_str!("entire_forge/fixtures/comment-01M69GVB1SNG4YRX6R3J5ZHSDP.json");

    fn doc(s: &str) -> Value {
        serde_json::from_str(s).unwrap()
    }

    fn repo() -> Repo {
        Repo::parse("entire.com/jdx/jouet-entire-forge-test").unwrap()
    }

    #[test]
    fn a_trail_with_no_gates_configured_is_open_and_clean() {
        let s = pr_status(&repo(), &doc(SHOW), 1, None);
        assert_eq!(
            (s.number, s.state, s.forge),
            (1, State::Open, Some("entire"))
        );
        assert_eq!(s.host.as_deref(), Some("entire.com"));
        assert_eq!(s.head, "feat/subtract");
        assert_eq!(s.head_sha, "e971859eed");
        assert_eq!(
            s.url,
            "https://entire.com/et/jdx/jouet-entire-forge-test/trails/1"
        );
        assert_eq!(
            (s.mergeable, s.merge_state.as_str()),
            (Mergeability::Mergeable, "clean")
        );
        // Every gate is skipped, so the gates check passes; there are no runs.
        assert_eq!((s.checks.pass, s.checks.total()), (1, 1));
        assert!(!s.entire.as_ref().unwrap().gates.failed());
        assert_eq!(s.unresolved_threads, 1);
    }

    #[test]
    fn failing_gates_and_runs_are_checks_and_the_approvals_gate_is_the_review() {
        let d = doc(SHOW_FAILING);
        let s = pr_status(&repo(), &d, 0, None);
        assert_eq!(s.checks.failing, ["buildkite/test", CHECK]);
        assert_eq!((s.checks.fail, s.checks.pending), (2, 1));
        assert_eq!(s.merge_state, "blocked");
        let g = gates(&d).unwrap();
        assert_eq!(g.trail, Some(1));
        let failing: Vec<&str> = g.failing().map(|g| g.gate.as_str()).collect();
        assert_eq!(failing, ["findings", "up_to_date"]);
        assert!(!g.derived());
        assert_eq!(
            g.failing_text(),
            "findings: Unresolved findings: 1 medium severity; up to date: 1 commit behind"
        );
        let approvals = gate(&d, "approvals").unwrap();
        assert_eq!(approvals["status"], "failed");
    }

    #[test]
    fn a_closed_trail_needs_no_review() {
        let mut d = doc(SHOW);
        d["status"] = "closed".into();
        let s = pr_status(&repo(), &d, 0, Some("review_required".into()));
        assert_eq!((s.state, s.review), (State::Closed, None));
    }

    #[test]
    fn a_discussion_is_a_thread_with_its_title_first() {
        let list = doc(COMMENTS);
        let naming = list["items"]
            .as_array()
            .unwrap()
            .iter()
            .find(|d| d["title"] == "Naming")
            .unwrap();
        let pr = PrThreads {
            repo: repo(),
            number: 1,
            node_id: String::new(),
            head_ref: "feat/subtract".into(),
            head_oid: String::new(),
            base_oid: String::new(),
            head_repo: None,
            viewer: "jdx".into(),
            threads: Vec::new(),
            others: Vec::new(),
            unreadable: 0,
        };
        let t = thread(&pr, naming, &doc(NAMING), &[]).unwrap();
        assert_eq!(t.node_id, "01M69GVB1SNG4YRX6R3J5ZHSDP");
        assert_eq!(Some(t.id), handle("01M69GVB1SNG4YRX6R3J5ZHSDP"));
        assert!(t.resolved && t.path.is_none());
        assert_eq!(t.author, "jdx");
        assert_eq!(t.comments.len(), 2);
        assert!(
            t.comments[0]
                .body
                .starts_with("Naming\n\nShould subtract be called sub")
        );
        assert_eq!(
            t.comments[1].body,
            "Keeping subtract: the other helpers are spelled out too."
        );
        assert_eq!(
            t.url,
            "https://entire.com/et/jdx/jouet-entire-forge-test/trails/1"
        );
    }

    #[test]
    fn entire_names_users_by_provider_and_trails_by_login() {
        assert_eq!(login("github:jdx"), "jdx");
        assert_eq!(login("jdx"), "jdx");
    }

    #[test]
    fn discussion_handles_are_stable_numbers() {
        let a = handle("01M67M0N092XMZ9EQMDZKWV4H9").unwrap();
        assert_eq!(handle("01m67m0n092xmz9eqmdzkwv4h9"), Some(a));
        assert_ne!(handle("01M67M0N093XMZ9EQMDZKWV4H9"), Some(a));
        assert_eq!(handle("short"), None);
        assert_eq!(handle("01M67M0N092XAAAAAAAAAAAAAA"), Some(a));
        assert_eq!(handle("01M67M0N0U2XMZ9EQMDZKWV4H9"), None);
    }

    #[test]
    fn the_latest_decision_of_each_reviewer_counts() {
        let a = |who: &str, event: &str, at: &str| json!({ "author": who, "event": event, "createdAt": at });
        let list = json!([
            a("x", "changes_requested", "2026-10-31T10:00:00Z"),
            a("x", "approved", "2026-10-31T11:00:00Z"),
        ]);
        assert_eq!(decision(&list, true).as_deref(), Some("approved"));
        let list = json!([
            a("x", "approved", "2026-10-31T10:00:00Z"),
            a("y", "changes_requested", "2026-10-31T09:00:00Z"),
        ]);
        assert_eq!(decision(&list, false).as_deref(), Some("changes_requested"));
        assert_eq!(
            decision(&json!([]), true).as_deref(),
            Some("review_required")
        );
        assert_eq!(decision(&json!([]), false), None);
    }
}