ghtui 0.2.0

A keyboard-driven terminal client for GitHub, with a pull request diff viewer that goes further than GitHub's
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
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
//! Domain types the app works with, decoupled from the GraphQL wire shapes;
//! GitHub's closed vocabularies are its own enums, checked against the
//! schema here, so a value keeps one spelling from decode to render.
//! These are what get cached, so changing them requires bumping
//! `crate::store::SCHEMA_VERSION`.

use crate::schema::schema;
use serde::{Deserialize, Serialize};

use crate::api::change::MergeMethod;
use crate::api::edit::{Editable, SidebarPermits, reactions};
use crate::api::queries::{self as q, nodes};

/// Some of a list: the items fetched, and how many GitHub has. A list
/// fetched with `first:` or `last:` is kept as one of these, so what shows
/// it can say what it left out ("+3", "20 of 45").
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Capped<T> {
    pub items: Vec<T>,
    /// Private, so a list's count comes only from `new` (or `from`, which
    /// claims all of it); read as never fewer than `items`.
    total: u64,
}

impl<T> Capped<T> {
    /// `items` of `total` (raised to the items' count if GitHub said fewer).
    pub fn new(items: Vec<T>, total: u64) -> Self {
        let total = total.max(items.len() as u64);
        Self { items, total }
    }

    /// From a connection's total and nodes; its null nodes (ones your
    /// token can't see) count as left out.
    pub(crate) fn from_nodes<N>(
        total: i32,
        list: Option<Vec<Option<N>>>,
        f: impl FnMut(N) -> T,
    ) -> Self {
        Self::new(
            nodes(list).map(f).collect(),
            u64::try_from(total).unwrap_or_default(),
        )
    }

    /// Each item made another by `f`, of the same total.
    pub fn map<U>(self, f: impl FnMut(T) -> U) -> Capped<U> {
        let items = self.items.into_iter().map(f).collect();
        Capped {
            items,
            total: self.total,
        }
    }

    /// How many GitHub has.
    pub fn total(&self) -> u64 {
        self.total.max(self.items.len() as u64)
    }

    /// How many GitHub has that aren't here.
    pub fn left_out(&self) -> u64 {
        self.total.saturating_sub(self.items.len() as u64)
    }
}

impl<T> Default for Capped<T> {
    fn default() -> Self {
        Self {
            items: Vec::new(),
            total: 0,
        }
    }
}

/// All of a list: the way to say none of it is left out.
impl<T> From<Vec<T>> for Capped<T> {
    fn from(items: Vec<T>) -> Self {
        Self::new(items, 0)
    }
}

impl<T> std::ops::Deref for Capped<T> {
    type Target = [T];

    fn deref(&self) -> &[T] {
        &self.items
    }
}

impl<T> std::ops::DerefMut for Capped<T> {
    fn deref_mut(&mut self) -> &mut [T] {
        &mut self.items
    }
}

impl<'a, T> IntoIterator for &'a Capped<T> {
    type Item = &'a T;
    type IntoIter = std::slice::Iter<'a, T>;

    fn into_iter(self) -> Self::IntoIter {
        self.items.iter()
    }
}

/// A GitHub GraphQL node ID (`PR_kwDO…`, `PRRT_…`): what mutations name
/// things by. Its own type so it can't be mixed up with a path, a SHA or
/// another string.
#[derive(Debug, Clone, Default, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(transparent)]
pub struct NodeId(String);

impl NodeId {
    pub fn new(id: impl Into<String>) -> Self {
        Self(id.into())
    }

    pub fn as_str(&self) -> &str {
        &self.0
    }

    pub(crate) fn gql(&self) -> cynic::Id {
        cynic::Id::new(&self.0)
    }
}

impl From<cynic::Id> for NodeId {
    fn from(id: cynic::Id) -> Self {
        Self(id.into_inner())
    }
}

impl std::fmt::Display for NodeId {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(&self.0)
    }
}

#[derive(Debug, Clone, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct RepoId {
    pub owner: String,
    pub name: String,
}

impl RepoId {
    pub fn new(owner: impl Into<String>, name: impl Into<String>) -> Self {
        Self {
            owner: owner.into(),
            name: name.into(),
        }
    }

    /// Parses `owner/name`.
    pub fn parse(s: &str) -> Option<Self> {
        let (owner, name) = s.split_once('/')?;
        let name = name.strip_suffix(".git").unwrap_or(name);
        (valid_segment(owner) && valid_segment(name)).then(|| Self::new(owner, name))
    }
}

fn valid_segment(s: &str) -> bool {
    !s.is_empty()
        && s != "."
        && s != ".."
        && s.chars()
            .all(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '_' | '.'))
}

impl std::fmt::Display for RepoId {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}/{}", self.owner, self.name)
    }
}

/// A pull request address: `owner/repo#N`.
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct PrRef {
    pub repo: RepoId,
    pub number: u64,
}

impl PrRef {
    /// Parses `owner/repo#N` or a pull request's URL on the GitHub ghtui
    /// works with (any sub-page, e.g. `/files`, is accepted).
    pub fn parse(s: &str) -> Option<Self> {
        let s = s.trim();
        if !s.contains("://")
            && let Some((repo, number)) = s.split_once('#')
        {
            return Some(Self {
                repo: RepoId::parse(repo)?,
                number: parse_number(number)?,
            });
        }
        let url = url::Url::parse(s).ok()?;
        if !matches!(url.scheme(), "https" | "http") || !crate::host::current().serves_url(&url) {
            return None;
        }
        let mut segments = url.path_segments()?;
        let owner = segments.next()?;
        let name = segments.next()?;
        if segments.next()? != "pull" {
            return None;
        }
        Some(Self {
            repo: RepoId::parse(&format!("{owner}/{name}"))?,
            number: parse_number(segments.next()?)?,
        })
    }

    pub fn url(&self) -> String {
        crate::ui::pages::url::pull(self)
    }
}

fn parse_number(s: &str) -> Option<u64> {
    s.parse().ok().filter(|n| *n > 0)
}

impl std::fmt::Display for PrRef {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}#{}", self.repo, self.number)
    }
}

#[derive(cynic::Enum, Debug, Clone, Copy, PartialEq, Eq)]
#[cynic(graphql_type = "PullRequestReviewDecision")]
pub enum ReviewDecision {
    Approved,
    ChangesRequested,
    ReviewRequired,
}

#[derive(Debug, Clone, Default, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum IssueState {
    #[default]
    Open,
    Closed,
    /// Closed as not planned (or duplicate).
    NotPlanned,
}

/// Only a pull request is a draft or merged, and only an issue is closed
/// as not planned: each has its own states.
#[derive(Debug, Clone, Default, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum PrState {
    #[default]
    Open,
    Draft,
    Closed,
    Merged,
}

impl PrState {
    /// Open, as a draft or not.
    pub fn is_open(self) -> bool {
        matches!(self, Self::Open | Self::Draft)
    }
}

/// An issue's state or a pull request's: what its icon and chip show.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Status {
    Issue(IssueState),
    Pr(PrState),
}

/// A pull request's state with its draft flag. Every query spreads this
/// in, and only it makes a [`PrState`], so none can get the state without
/// the flag or forget that an open draft is a draft.
#[derive(cynic::QueryFragment, Debug)]
#[cynic(graphql_type = "PullRequest")]
pub struct PrStatus {
    is_draft: bool,
    state: q::PullRequestState,
}

impl From<PrStatus> for PrState {
    fn from(pr: PrStatus) -> Self {
        match pr.state {
            q::PullRequestState::Open if pr.is_draft => Self::Draft,
            q::PullRequestState::Open => Self::Open,
            q::PullRequestState::Closed => Self::Closed,
            q::PullRequestState::Merged => Self::Merged,
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum ChecksState {
    Passing,
    Failing,
    Pending,
}

/// Whether a pull request can merge now, and if not, why.
#[derive(cynic::Enum, Debug, Clone, Default, Copy, PartialEq, Eq)]
#[cynic(graphql_type = "MergeStateStatus")]
pub enum MergeState {
    /// Its branch is behind its base, which requires it to be up to date.
    Behind,
    /// Something it needs is missing: approvals, checks.
    Blocked,
    Clean,
    /// It conflicts with its base.
    Dirty,
    Draft,
    HasHooks,
    #[default]
    Unknown,
    /// Some checks didn't pass, but they aren't required.
    Unstable,
}

#[derive(cynic::Enum, Debug, Clone, Default, Copy, PartialEq, Eq)]
#[cynic(graphql_type = "MergeableState")]
pub enum Mergeable {
    #[cynic(rename = "MERGEABLE")]
    Yes,
    Conflicting,
    #[default]
    Unknown,
}

#[derive(cynic::Enum, Debug, Clone, Copy, PartialEq, Eq)]
#[cynic(graphql_type = "PullRequestReviewState")]
pub enum ReviewState {
    Approved,
    ChangesRequested,
    Commented,
    Dismissed,
    Pending,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Label {
    pub name: String,
    /// `rrggbb`, as GitHub returns it.
    pub color: String,
}

/// A pull request, as its page shows it. Where it is (a [`PrRef`]) is
/// what it's fetched and kept by, not part of it.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct PrDetail {
    /// What changes name it by.
    pub id: NodeId,
    pub title: String,
    pub author: String,
    pub state: PrState,
    /// ISO 8601.
    pub updated_at: String,
    pub additions: u64,
    pub deletions: u64,
    pub review: Option<ReviewDecision>,
    pub checks: Option<ChecksState>,
    pub body: String,
    pub created_at: String,
    pub base_ref: String,
    pub head_ref: String,
    pub base_oid: String,
    pub head_oid: String,
    /// `owner/name` of the head repository; `None` if it was deleted.
    pub head_repo: Option<String>,
    pub changed_files: u64,
    pub mergeable: Mergeable,
    pub merge_state: MergeState,
    /// Commits on its base its branch doesn't have; `None` once it's
    /// closed, or if GitHub couldn't compare them.
    pub behind_by: Option<u64>,
    /// The ways the repository allows merging, yours first.
    pub merge_methods: Vec<MergeMethod>,
    /// The repository allows merging once every requirement is met.
    pub auto_merge_allowed: bool,
    /// Set to merge once every requirement is met.
    pub auto_merge: Option<AutoMerge>,
    /// Its base branch merges through a merge queue.
    pub merge_queue: bool,
    /// Its place in that queue, once it's in it.
    pub queued: Option<Queued>,
    pub labels: Capped<Label>,
    pub milestone: Option<MilestoneRef>,
    pub assignees: Capped<String>,
    /// What GitHub lets you do to it.
    pub may: PrPermits,
    /// Its description, as edits name it.
    pub editable: Editable,
    pub sidebar: SidebarPermits,
    /// Its head branch is gone (deleted, or its fork is).
    pub head_gone: bool,
    /// Its conversation is locked: only collaborators comment.
    pub locked: Option<crate::api::manage::Locked>,
}

/// Your pending review on a pull request: what you started and haven't
/// submitted, here or on github.com.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PendingReview {
    pub id: NodeId,
    /// The commit its comments are on.
    pub commit: Option<String>,
    /// Comments in it, which submitting it publishes.
    pub comments: u64,
}

/// What GitHub lets you do to a pull request.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct PrPermits {
    /// Merge it: you can write to the repository.
    pub merge: bool,
    /// Merge it though branch protection blocks it.
    pub merge_as_admin: bool,
    pub close: bool,
    pub reopen: bool,
    /// Edit it, which marking a draft ready for review is.
    pub edit: bool,
    /// Push to its branch, which updating the branch does.
    pub push_head: bool,
    pub enable_auto_merge: bool,
    pub disable_auto_merge: bool,
    /// Delete its head branch.
    pub delete_head: bool,
}

/// Auto-merge, turned on: by whom, and how it will merge.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct AutoMerge {
    pub by: String,
    pub method: MergeMethod,
}

/// A pull request's place in its base branch's merge queue.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub struct Queued {
    /// 1 is next.
    pub position: u64,
    pub state: QueueState,
}

#[derive(cynic::Enum, Debug, Clone, Copy, PartialEq, Eq)]
#[cynic(graphql_type = "MergeQueueEntryState")]
pub enum QueueState {
    /// Its checks in the queue are running.
    AwaitingChecks,
    /// Being merged.
    Locked,
    Mergeable,
    /// Waiting its turn.
    Queued,
    Unmergeable,
}

/// Whether GitHub would merge a pull request now, and if not, the first
/// reason. The merge box and the merge action both read it, so they agree.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Readiness {
    Merged,
    Closed,
    Draft,
    Conflicts,
    /// GitHub is still working out whether it conflicts.
    Checking,
    /// The repository requires its branch to be up to date, and it isn't.
    Behind,
    /// A required review or check is missing.
    Blocked,
    /// Merging would work; failed checks that aren't required don't stop it.
    Ready,
}

impl PrDetail {
    pub fn readiness(&self) -> Readiness {
        match (self.state, self.mergeable, self.merge_state) {
            (PrState::Merged, ..) => Readiness::Merged,
            (PrState::Closed, ..) => Readiness::Closed,
            (PrState::Draft, ..) | (_, _, MergeState::Draft) => Readiness::Draft,
            (_, Mergeable::Conflicting, _) | (_, _, MergeState::Dirty) => Readiness::Conflicts,
            (_, Mergeable::Unknown, _) | (_, _, MergeState::Unknown) => Readiness::Checking,
            (.., MergeState::Behind) => Readiness::Behind,
            (.., MergeState::Blocked) => Readiness::Blocked,
            (.., MergeState::Clean | MergeState::HasHooks | MergeState::Unstable) => {
                Readiness::Ready
            }
        }
    }

    /// It's open and GitHub hasn't settled what it shows: whether it can
    /// merge, its checks, or its place in the merge queue. A page showing
    /// it fetches it again until it has.
    pub fn settling(&self) -> bool {
        self.state.is_open()
            && (self.mergeable == Mergeable::Unknown
                || self.merge_state == MergeState::Unknown
                || self.checks == Some(ChecksState::Pending)
                || self.queued.is_some())
    }
}

/// The milestone an issue or pull request is in.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct MilestoneRef {
    pub number: u64,
    pub title: String,
}

impl MilestoneRef {
    pub(crate) fn from_wire(m: q::MilestoneName) -> Self {
        Self {
            number: count(m.number),
            title: m.title,
        }
    }
}

#[derive(cynic::Enum, Debug, Clone, Copy, PartialEq, Eq, Default)]
#[cynic(graphql_type = "FileViewedState")]
pub enum ViewedState {
    #[default]
    Unviewed,
    Viewed,
    /// Viewed, but the file changed since.
    Dismissed,
}

/// Per-file viewed state for one PR, and the PR's node ID (needed to change
/// it).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ViewedFiles {
    pub pull_request_id: NodeId,
    pub states: std::collections::HashMap<String, ViewedState>,
}

#[derive(cynic::Enum, Debug, Clone, Default, Copy, PartialEq, Eq, Hash)]
#[cynic(graphql_type = "DiffSide")]
pub enum Side {
    /// Base (old) lines.
    Left,
    /// Head (new) lines.
    #[default]
    Right,
}

#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct ReviewComment {
    pub id: NodeId,
    pub author: String,
    pub body: String,
    /// ISO 8601.
    pub created_at: String,
    pub url: String,
    /// The commit the comment was originally made on.
    pub original_commit: Option<String>,
    /// Part of the viewer's unsubmitted review on GitHub.
    pub pending: bool,
    pub editable: Editable,
    /// The review it was made in, by GitHub's number for it.
    pub review: Option<u64>,
}

#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct ReviewThread {
    pub id: NodeId,
    pub path: String,
    pub side: Side,
    pub start_side: Option<Side>,
    /// Current line; `None` when the thread is outdated.
    pub line: Option<u32>,
    pub start_line: Option<u32>,
    /// Line on the comment's original commit.
    pub original_line: Option<u32>,
    pub original_start_line: Option<u32>,
    pub outdated: bool,
    pub resolved: bool,
    /// A comment on the whole file rather than a line.
    pub file_level: bool,
    pub can_reply: bool,
    pub can_resolve: bool,
    pub can_unresolve: bool,
    /// The first comment and the newest replies.
    pub comments: Capped<ReviewComment>,
    /// The diff the first comment was made on, as GitHub kept it: the
    /// lines it's about come last.
    pub diff_hunk: String,
}

/// GitHub's patch for one file (from REST `pulls/{n}/files`).
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
pub struct PatchFile {
    pub filename: String,
    #[serde(default)]
    pub previous_filename: Option<String>,
    /// Missing for binary and very large diffs.
    #[serde(default)]
    pub patch: Option<String>,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum ReviewEvent {
    Comment,
    Approve,
    RequestChanges,
}

/// A new thread in a pending review.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct NewThread {
    pub path: String,
    pub body: String,
    /// `None` for a file-level comment.
    pub line: Option<u32>,
    pub side: Side,
    pub start_line: Option<u32>,
    pub start_side: Option<Side>,
}

// ---- conversions from the wire types ---------------------------------------

pub(crate) fn checks(commits: &q::CommitRollupConnection) -> Option<ChecksState> {
    let rollup = commits
        .nodes
        .as_ref()?
        .iter()
        .flatten()
        .last()?
        .commit
        .status_check_rollup
        .as_ref()?;
    Some(rollup.state.into())
}

/// The one reading of a commit status, for a PR's rollup and for each
/// status among a commit's checks.
impl From<q::StatusState> for ChecksState {
    fn from(state: q::StatusState) -> Self {
        match state {
            q::StatusState::Success => Self::Passing,
            q::StatusState::Failure | q::StatusState::Error => Self::Failing,
            q::StatusState::Pending | q::StatusState::Expected => Self::Pending,
        }
    }
}

/// A login; a deleted account is GitHub's own "ghost" user.
pub(crate) fn author(actor: Option<q::Actor>) -> String {
    actor.map_or_else(|| "ghost".to_owned(), |a| a.login)
}

pub(crate) fn labels(labels: Option<q::LabelConnection>) -> Capped<Label> {
    labels.map_or_else(Capped::default, |l| {
        Capped::from_nodes(l.total_count, l.nodes, |l| Label {
            name: l.name,
            color: l.color,
        })
    })
}

pub(crate) fn count(n: i32) -> u64 {
    u64::try_from(n).unwrap_or(0)
}

impl PrDetail {
    pub(crate) fn from_wire(repo: q::RepositoryWithPr) -> Option<Self> {
        let default = repo.viewer_default_merge_method;
        let allowed = [
            (MergeMethod::Merge, repo.merge_commit_allowed),
            (MergeMethod::Squash, repo.squash_merge_allowed),
            (MergeMethod::Rebase, repo.rebase_merge_allowed),
        ];
        let mut merge_methods: Vec<MergeMethod> = allowed
            .into_iter()
            .filter_map(|(m, ok)| ok.then_some(m))
            .collect();
        merge_methods.sort_by_key(|m| *m != default);
        let writes = q::RepositoryPermission::writes(repo.viewer_permission);
        let pr = repo.pull_request?;
        Some(Self {
            id: pr.id.clone().into(),
            title: pr.summary.title,
            author: author(pr.summary.author),
            state: pr.summary.status.into(),
            updated_at: pr.summary.updated_at.0,
            additions: count(pr.summary.additions),
            deletions: count(pr.summary.deletions),
            review: pr.summary.review_decision,
            checks: checks(&pr.summary.commits),
            body: pr.body,
            created_at: pr.created_at.0,
            base_ref: pr.base_ref_name,
            head_ref: pr.head_ref_name,
            base_oid: pr.base_ref_oid.0,
            head_oid: pr.head_ref_oid.0,
            head_repo: pr.head_repository.map(|r| r.name_with_owner),
            changed_files: count(pr.changed_files),
            mergeable: pr.mergeable,
            merge_state: pr.merge_state_status,
            behind_by: None,
            merge_methods,
            auto_merge_allowed: repo.auto_merge_allowed,
            auto_merge: pr.auto_merge_request.map(|a| AutoMerge {
                by: author(a.enabled_by),
                method: a.merge_method,
            }),
            merge_queue: pr.is_merge_queue_enabled,
            queued: pr.merge_queue_entry.map(|e| Queued {
                position: count(e.position),
                state: e.state,
            }),
            labels: labels(pr.labels),
            milestone: pr.milestone.map(MilestoneRef::from_wire),
            assignees: Capped::from_nodes(pr.assignees.total_count, pr.assignees.nodes, |u| {
                u.login
            }),
            editable: Editable {
                id: pr.id.into(),
                can_update: pr.viewer_can_update,
                can_delete: false,
                can_react: pr.viewer_can_react,
                reactions: reactions(pr.reaction_groups),
            },
            // GitHub doesn't say who may set a pull request's milestone
            // or ask for reviews: both take triage access, as labelling does.
            sidebar: SidebarPermits {
                labels: pr.viewer_can_label,
                assignees: pr.viewer_can_assign,
                milestone: pr.viewer_can_label,
                reviewers: pr.viewer_can_label,
            },
            may: PrPermits {
                merge: writes,
                merge_as_admin: pr.viewer_can_merge_as_admin,
                close: pr.viewer_can_close,
                reopen: pr.viewer_can_reopen,
                edit: pr.viewer_can_update,
                push_head: if pr.is_cross_repository {
                    pr.viewer_did_author || (pr.maintainer_can_modify && writes)
                } else {
                    writes
                },
                enable_auto_merge: pr.viewer_can_enable_auto_merge,
                disable_auto_merge: pr.viewer_can_disable_auto_merge,
                delete_head: pr.viewer_can_delete_head_ref,
            },
            head_gone: pr.head_ref.is_none(),
            locked: (pr.locked).then_some(crate::api::manage::Locked {
                reason: pr.active_lock_reason,
            }),
        })
    }
}

impl ReviewThread {
    pub(crate) fn from_wire(t: q::ReviewThread) -> Self {
        let line = |n: Option<i32>| n.and_then(|n| u32::try_from(n).ok());
        let mut diff_hunk = String::new();
        Self {
            id: t.id.into(),
            path: t.path,
            side: t.diff_side,
            start_side: t.start_diff_side,
            line: line(t.line),
            start_line: line(t.start_line),
            original_line: line(t.original_line),
            original_start_line: line(t.original_start_line),
            outdated: t.is_outdated,
            resolved: t.is_resolved,
            file_level: t.subject_type == q::ThreadSubjectType::File,
            can_reply: t.viewer_can_reply,
            can_resolve: t.viewer_can_resolve,
            can_unresolve: t.viewer_can_unresolve,
            comments: {
                let comment = |c: q::ReviewComment| ReviewComment {
                    editable: Editable {
                        id: c.id.clone().into(),
                        can_update: c.viewer_can_update,
                        can_delete: c.viewer_can_delete,
                        can_react: c.viewer_can_react,
                        reactions: reactions(c.reaction_groups),
                    },
                    id: c.id.into(),
                    author: author(c.author),
                    body: c.body,
                    created_at: c.created_at.0,
                    url: c.url.0,
                    original_commit: c.original_commit.map(|o| o.oid.0),
                    pending: c.state == q::ReviewCommentState::Pending,
                    review: (c.pull_request_review)
                        .and_then(|r| r.full_database_id?.0.parse().ok()),
                };
                let mut items: Vec<ReviewComment> = nodes(t.first_comment.nodes)
                    .map(|first| {
                        diff_hunk = first.diff_hunk;
                        comment(first.comment)
                    })
                    .collect();
                let first = items.first().map(|c| c.id.clone());
                // In a short thread the first is among the newest too.
                items.extend(
                    nodes(t.comments.nodes)
                        .map(comment)
                        .filter(|c| first.as_ref() != Some(&c.id)),
                );
                Capped::new(
                    items,
                    u64::try_from(t.comments.total_count).unwrap_or_default(),
                )
            },
            diff_hunk,
        }
    }
}

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

    /// Every query's pull request state comes through one fragment, and
    /// an open draft is a draft.
    #[test]
    fn an_open_draft_is_a_draft() {
        let state = |json| PrState::from(serde_json::from_value::<PrStatus>(json).unwrap());
        let open = serde_json::json!({ "isDraft": true, "state": "OPEN" });
        assert_eq!(state(open), PrState::Draft);
        let open = serde_json::json!({ "isDraft": false, "state": "OPEN" });
        assert_eq!(state(open), PrState::Open);
        let merged = serde_json::json!({ "isDraft": true, "state": "MERGED" });
        assert_eq!(state(merged), PrState::Merged);
    }

    /// A count decoded as fewer than its items still reads as no fewer.
    #[test]
    fn a_decoded_count_is_never_fewer_than_its_items() {
        let list: Capped<u8> = serde_json::from_str(r#"{"items":[1,2,3],"total":1}"#).unwrap();
        assert_eq!((list.total(), list.left_out()), (3, 0));
    }

    #[test]
    fn parses_short_refs() {
        let pr = PrRef::parse("rust-lang/rust#12345").unwrap();
        assert_eq!(pr.repo, RepoId::new("rust-lang", "rust"));
        assert_eq!(pr.number, 12345);
        assert_eq!(pr.to_string(), "rust-lang/rust#12345");
    }

    #[test]
    fn parses_urls() {
        for url in [
            "https://github.com/ratatui/ratatui/pull/42",
            "https://github.com/ratatui/ratatui/pull/42/files",
            "https://github.com/ratatui/ratatui/pull/42/files#diff-abc",
            "https://www.github.com/ratatui/ratatui/pull/42?w=1",
        ] {
            let pr = PrRef::parse(url).unwrap_or_else(|| panic!("{url}"));
            assert_eq!(pr.to_string(), "ratatui/ratatui#42");
        }
    }

    #[test]
    fn rejects_malformed_refs() {
        for bad in [
            "",
            "rust",
            "rust#1",
            "a/b#",
            "a/b#0",
            "a/b#x",
            "a/b/c#1",
            "../b#1",
            "https://gitlab.com/a/b/pull/1",
            "https://github.com/a/b/issues/1",
            "https://github.com/a/b",
            "ftp://github.com/a/b/pull/1",
        ] {
            assert_eq!(PrRef::parse(bad), None, "{bad}");
        }
    }

    #[test]
    fn repo_parse_strips_git_suffix() {
        assert_eq!(RepoId::parse("a/b.git"), Some(RepoId::new("a", "b")));
    }
}