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
//! Managing an issue, a pull request or a discussion, as GitHub's sidebar
//! and menus do: a pull request's branch after it's merged, back to
//! draft, its base; locking and pinning; hiding a comment; sub-issues and
//! what blocks an issue; closing as a duplicate; closing a discussion.
//! Each is a [`Manage`], sent as
//! [`Change::Manage`](crate::api::change::Change::Manage). What makes
//! something new (a revert, a transfer, a branch, a discussion) is a call
//! of its own, which answers with what it made.

use serde::{Deserialize, Serialize};
use serde_json::{Value, json};

use crate::api::client::{ApiError, GitHub};
use crate::api::model::{Capped, NodeId, RepoId};
use crate::api::raw;
pub use crate::api::timeline::LockReason;

/// An issue by its repository and number.
#[derive(Debug, Clone, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
pub struct IssueAt {
    pub repo: RepoId,
    pub number: u64,
}

impl IssueAt {
    /// `#12` or `12` (in `here`), `owner/name#12`, or an issue's link.
    pub fn parse(text: &str, here: &RepoId) -> Option<Self> {
        let text = text.trim();
        let number = |s: &str| s.parse::<u64>().ok().filter(|n| *n > 0);
        if let Some(n) = number(text.strip_prefix('#').unwrap_or(text)) {
            return Some(Self {
                repo: here.clone(),
                number: n,
            });
        }
        if let Some((repo, n)) = text.split_once('#')
            && let (Some(repo), Some(number)) = (RepoId::parse(repo), number(n))
        {
            return Some(Self { repo, number });
        }
        // A link: …/owner/name/issues/12 (or pull/12), on any host.
        let path = text.split_once("://").map_or(text, |(_, rest)| rest);
        let parts: Vec<&str> = path.trim_end_matches('/').split('/').collect();
        match parts.as_slice() {
            [.., owner, name, "issues" | "pull", n] => Some(Self {
                repo: RepoId::parse(&format!("{owner}/{name}"))?,
                number: number(n.split(['#', '?']).next().unwrap_or(n))?,
            }),
            _ => None,
        }
    }

    /// `#12` in `here`, else `owner/name#12`.
    pub fn named(&self, here: &RepoId) -> String {
        if self.repo == *here {
            format!("#{}", self.number)
        } else {
            self.to_string()
        }
    }
}

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

/// Why a comment is hidden, as GitHub's "Hide" menu offers.
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub enum HideReason {
    Spam,
    Abuse,
    OffTopic,
    Outdated,
    Duplicate,
    Resolved,
}

impl HideReason {
    pub const ALL: [HideReason; 6] = [
        HideReason::Spam,
        HideReason::Abuse,
        HideReason::OffTopic,
        HideReason::Outdated,
        HideReason::Duplicate,
        HideReason::Resolved,
    ];

    fn wire(self) -> &'static str {
        match self {
            HideReason::Spam => "SPAM",
            HideReason::Abuse => "ABUSE",
            HideReason::OffTopic => "OFF_TOPIC",
            HideReason::Outdated => "OUTDATED",
            HideReason::Duplicate => "DUPLICATE",
            HideReason::Resolved => "RESOLVED",
        }
    }

    /// As GitHub's menu says it.
    pub fn label(self) -> &'static str {
        match self {
            HideReason::Spam => "Spam",
            HideReason::Abuse => "Abuse",
            HideReason::OffTopic => "Off Topic",
            HideReason::Outdated => "Outdated",
            HideReason::Duplicate => "Duplicate",
            HideReason::Resolved => "Resolved",
        }
    }

    /// GitHub's `minimizedReason` for it ("off-topic"), which differs from
    /// what's sent.
    pub fn said(self) -> &'static str {
        match self {
            HideReason::Spam => "spam",
            HideReason::Abuse => "abuse",
            HideReason::OffTopic => "off-topic",
            HideReason::Outdated => "outdated",
            HideReason::Duplicate => "duplicate",
            HideReason::Resolved => "resolved",
        }
    }
}

/// A locked conversation, and GitHub's reason.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub struct Locked {
    pub reason: Option<LockReason>,
}

/// Whether a comment is hidden (and why, in GitHub's words: "off-topic";
/// empty where it doesn't say), and whether you may hide or unhide it.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct Hiding {
    pub reason: Option<String>,
    pub can_hide: bool,
    pub can_unhide: bool,
}

/// "off-topic", "too heated".
pub fn lock_said(reason: LockReason) -> &'static str {
    match reason {
        LockReason::OffTopic => "off-topic",
        LockReason::Resolved => "resolved",
        LockReason::Spam => "spam",
        LockReason::TooHeated => "too heated",
    }
}

/// Why a discussion is closed.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum DiscussionReason {
    Resolved,
    Outdated,
    Duplicate,
}

impl DiscussionReason {
    pub const ALL: [DiscussionReason; 3] = [
        DiscussionReason::Resolved,
        DiscussionReason::Outdated,
        DiscussionReason::Duplicate,
    ];

    fn wire(self) -> &'static str {
        match self {
            DiscussionReason::Resolved => "RESOLVED",
            DiscussionReason::Outdated => "OUTDATED",
            DiscussionReason::Duplicate => "DUPLICATE",
        }
    }

    /// "resolved".
    pub fn said(self) -> &'static str {
        match self {
            DiscussionReason::Resolved => "resolved",
            DiscussionReason::Outdated => "outdated",
            DiscussionReason::Duplicate => "duplicate",
        }
    }

    /// A closed discussion's `stateReason`.
    pub fn from_wire(reason: Option<&str>) -> Option<Self> {
        Self::ALL.into_iter().find(|r| Some(r.wire()) == reason)
    }
}

/// A change to an issue, a pull request or a discussion.
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub enum Manage {
    /// Delete a pull request's head branch.
    DeleteBranch {
        repo: RepoId,
        branch: String,
    },
    /// Make it again at the commit it was at.
    RestoreBranch {
        repo: RepoId,
        branch: String,
        oid: String,
    },
    ConvertToDraft {
        pr: NodeId,
    },
    /// Point a pull request at another base branch.
    ChangeBase {
        pr: NodeId,
        base: String,
    },
    /// Lock an issue's, a pull request's or a discussion's conversation.
    Lock {
        subject: NodeId,
        reason: Option<LockReason>,
    },
    Unlock {
        subject: NodeId,
    },
    /// Pin an issue to its repository's Issues tab (`on`), or unpin it.
    Pin {
        issue: NodeId,
        on: bool,
    },
    Hide {
        comment: NodeId,
        reason: HideReason,
    },
    Unhide {
        comment: NodeId,
    },
    /// Close an issue as a duplicate of `of` (`None`: one to choose).
    CloseAsDuplicate {
        issue: NodeId,
        of: Option<IssueAt>,
    },
    /// Revert a merged pull request: a branch and a pull request of it.
    Revert {
        pr: NodeId,
    },
    /// Move an issue to another repository (`to`, by its node ID).
    Transfer {
        issue: NodeId,
        to: NodeId,
        repo: RepoId,
    },
    /// Add `child` to `parent`'s sub-issues, or remove it.
    SubIssue {
        parent: NodeId,
        child: IssueAt,
        add: bool,
    },
    /// Move a sub-issue to just before (or after) another.
    MoveSubIssue {
        parent: NodeId,
        child: IssueAt,
        sibling: IssueAt,
        before: bool,
    },
    /// Mark `issue` blocked by `by`, or no longer.
    BlockedBy {
        issue: NodeId,
        by: IssueAt,
        add: bool,
    },
    /// Make a branch for an issue, at its repository's default branch,
    /// linked to it (its Development).
    LinkBranch {
        issue: NodeId,
        repo: RepoId,
        name: String,
    },
    CloseDiscussion {
        discussion: NodeId,
        reason: DiscussionReason,
    },
    ReopenDiscussion {
        discussion: NodeId,
    },
}

/// A repository an issue can move to.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Target {
    pub repo: RepoId,
    pub id: NodeId,
}

/// A repository's discussion category, and the form a new discussion
/// in it starts from.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Category {
    pub id: NodeId,
    pub name: String,
    pub slug: String,
    pub description: String,
    pub answerable: bool,
    /// Its form (`.github/DISCUSSION_TEMPLATE/<slug>.yml`), if it has one.
    pub form: Option<String>,
}

/// Where new discussions go: the repository's ID, and its categories.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Categories {
    pub repo: NodeId,
    pub categories: Capped<Category>,
}

#[derive(Deserialize)]
struct Id {
    id: NodeId,
}

impl GitHub {
    /// An issue's node ID.
    async fn issue_id(&self, at: &IssueAt) -> Result<NodeId, ApiError> {
        let vars = json!({ "owner": at.repo.owner, "name": at.repo.name, "number": at.number });
        let found: Id = (self.graphql_json(
            raw::ISSUE_OR_PR_ID,
            vars,
            at,
            "/repository/issueOrPullRequest",
        ))
        .await?;
        Ok(found.id)
    }

    pub(crate) async fn manage(&self, change: &Manage) -> Result<(), ApiError> {
        let (query, vars) = match change {
            Manage::DeleteBranch { repo, branch } => {
                let path = format!("/repos/{repo}/git/refs/heads/{branch}");
                return self.rest_write(http::Method::DELETE, &path, None).await;
            }
            Manage::RestoreBranch { repo, branch, oid } => {
                let body = json!({ "ref": format!("refs/heads/{branch}"), "sha": oid });
                let path = format!("/repos/{repo}/git/refs");
                return self
                    .rest_write(http::Method::POST, &path, Some(&body))
                    .await;
            }
            Manage::ConvertToDraft { pr } => (raw::CONVERT_TO_DRAFT, json!({ "id": pr.as_str() })),
            Manage::ChangeBase { pr, base } => {
                (raw::CHANGE_BASE, json!({ "id": pr.as_str(), "base": base }))
            }
            Manage::Lock { subject, reason } => (
                raw::LOCK,
                json!({ "id": subject.as_str(), "reason": reason.map(lock_wire) }),
            ),
            Manage::Unlock { subject } => (raw::UNLOCK, json!({ "id": subject.as_str() })),
            Manage::Pin { issue, on } => (
                if *on {
                    raw::PIN_ISSUE
                } else {
                    raw::UNPIN_ISSUE
                },
                json!({ "id": issue.as_str() }),
            ),
            Manage::Hide { comment, reason } => (
                raw::HIDE_COMMENT,
                json!({ "id": comment.as_str(), "reason": reason.wire() }),
            ),
            Manage::Unhide { comment } => (raw::UNHIDE_COMMENT, json!({ "id": comment.as_str() })),
            Manage::Revert { pr } => return self.revert(pr).await.map(drop),
            Manage::Transfer { issue, to, .. } => return self.transfer(issue, to).await.map(drop),
            Manage::CloseAsDuplicate { issue, of } => {
                let of = of
                    .as_ref()
                    .ok_or_else(|| ApiError::Internal("no issue it duplicates".into()))?;
                let of = self.issue_id(of).await?;
                (
                    raw::CLOSE_AS_DUPLICATE,
                    json!({ "id": issue.as_str(), "of": of.as_str() }),
                )
            }
            Manage::SubIssue { parent, child, add } => {
                let child = self.issue_id(child).await?;
                let query = if *add {
                    raw::ADD_SUB_ISSUE
                } else {
                    raw::REMOVE_SUB_ISSUE
                };
                (
                    query,
                    json!({ "id": parent.as_str(), "child": child.as_str() }),
                )
            }
            Manage::MoveSubIssue {
                parent,
                child,
                sibling,
                before,
            } => {
                let child = self.issue_id(child).await?;
                let sibling = self.issue_id(sibling).await?;
                let (before, after) = if *before {
                    (Some(sibling.as_str()), None)
                } else {
                    (None, Some(sibling.as_str()))
                };
                (
                    raw::MOVE_SUB_ISSUE,
                    json!({ "id": parent.as_str(), "child": child.as_str(), "before": before, "after": after }),
                )
            }
            Manage::BlockedBy { issue, by, add } => {
                let by = self.issue_id(by).await?;
                let query = if *add {
                    raw::ADD_BLOCKED_BY
                } else {
                    raw::REMOVE_BLOCKED_BY
                };
                (query, json!({ "id": issue.as_str(), "by": by.as_str() }))
            }
            Manage::LinkBranch { issue, repo, name } => {
                let vars = json!({ "owner": repo.owner, "name": repo.name });
                let oid: String = (self.graphql_json(
                    raw::DEFAULT_BRANCH_OID,
                    vars,
                    format!("{repo}'s default branch"),
                    "/repository/defaultBranchRef/target/oid",
                ))
                .await?;
                (
                    raw::LINK_BRANCH,
                    json!({ "id": issue.as_str(), "oid": oid, "name": name }),
                )
            }
            Manage::CloseDiscussion { discussion, reason } => (
                raw::CLOSE_DISCUSSION,
                json!({ "id": discussion.as_str(), "reason": reason.wire() }),
            ),
            Manage::ReopenDiscussion { discussion } => {
                (raw::REOPEN_DISCUSSION, json!({ "id": discussion.as_str() }))
            }
        };
        self.mutate_json(query, vars).await
    }

    /// Reverts a merged pull request: GitHub makes a branch reverting it
    /// and a pull request of it, whose number this answers.
    pub async fn revert(&self, pr: &NodeId) -> Result<u64, ApiError> {
        let made: Value = self
            .mutate_json_for(raw::REVERT_PR, json!({ "id": pr.as_str() }))
            .await?;
        made.pointer("/revertPullRequest/revertPullRequest/number")
            .and_then(Value::as_u64)
            .ok_or_else(|| ApiError::Internal("GitHub didn't say which pull request".into()))
    }

    /// Moves an issue to another repository: where it is now.
    pub async fn transfer(&self, issue: &NodeId, to: &NodeId) -> Result<IssueAt, ApiError> {
        let vars = json!({ "id": issue.as_str(), "repo": to.as_str() });
        let made: Value = self.mutate_json_for(raw::TRANSFER_ISSUE, vars).await?;
        let issue = made.pointer("/transferIssue/issue");
        let repo = (issue.and_then(|i| i.pointer("/repository/nameWithOwner")))
            .and_then(Value::as_str)
            .and_then(RepoId::parse);
        let number = issue.and_then(|i| i.get("number")).and_then(Value::as_u64);
        match (repo, number) {
            (Some(repo), Some(number)) => Ok(IssueAt { repo, number }),
            _ => Err(ApiError::Internal(
                "GitHub didn't say where the issue went".into(),
            )),
        }
    }

    /// Starts a discussion: its number.
    pub async fn start_discussion(
        &self,
        repo: &NodeId,
        category: &NodeId,
        title: &str,
        body: &str,
    ) -> Result<u64, ApiError> {
        let vars = json!({ "repo": repo.as_str(), "category": category.as_str(), "title": title, "body": body });
        let made: Value = self.mutate_json_for(raw::START_DISCUSSION, vars).await?;
        made.pointer("/createDiscussion/discussion/number")
            .and_then(Value::as_u64)
            .ok_or_else(|| ApiError::Internal("GitHub didn't say which discussion".into()))
    }

    /// The repositories of `owner` an issue can move to: those you can
    /// write to with issues on, most recently pushed first, of the first
    /// 100.
    pub async fn transfer_targets(&self, owner: &str) -> Result<Capped<Target>, ApiError> {
        #[derive(Deserialize)]
        #[serde(rename_all = "camelCase")]
        struct Repo {
            id: NodeId,
            name_with_owner: String,
            has_issues_enabled: bool,
            is_archived: bool,
            viewer_permission: Option<String>,
        }
        let found: crate::api::browse::wire::Counted<Repo> = (self.graphql_json(
            raw::TRANSFER_TARGETS,
            json!({ "login": owner }),
            format!("{owner}'s repositories"),
            "/repositoryOwner/repositories",
        ))
        .await?;
        let total = found.total_count;
        let items = (found.nodes.into_iter().flatten())
            .filter(|r| {
                let writes = matches!(
                    r.viewer_permission.as_deref(),
                    Some("ADMIN" | "MAINTAIN" | "WRITE")
                );
                writes && r.has_issues_enabled && !r.is_archived
            })
            .filter_map(|r| {
                Some(Target {
                    repo: RepoId::parse(&r.name_with_owner)?,
                    id: r.id,
                })
            })
            .collect::<Vec<_>>();
        // Those left out by permission aren't "more": only those past the
        // first page may be.
        let more = total.saturating_sub(100);
        let n = items.len() as u64;
        Ok(Capped::new(items, n + more))
    }

    /// A repository's open issues, most recently updated first: number and
    /// title.
    pub async fn open_issues(&self, repo: &RepoId) -> Result<Capped<(u64, String)>, ApiError> {
        #[derive(Deserialize)]
        struct Issue {
            number: u64,
            title: String,
        }
        let found: crate::api::browse::wire::Counted<Issue> = (self.graphql_json(
            raw::OPEN_ISSUES,
            json!({ "owner": repo.owner, "name": repo.name }),
            repo,
            "/repository/issues",
        ))
        .await?;
        Ok(found.into_capped(|i| Some((i.number, i.title))))
    }

    /// A repository's discussion categories, with their forms.
    pub async fn categories(&self, repo: &RepoId) -> Result<Categories, ApiError> {
        #[derive(Deserialize)]
        #[serde(rename_all = "camelCase")]
        struct Wire {
            id: NodeId,
            discussion_categories: crate::api::browse::wire::Counted<WireCategory>,
            templates: Option<Tree>,
        }
        #[derive(Deserialize)]
        #[serde(rename_all = "camelCase")]
        struct WireCategory {
            id: NodeId,
            name: String,
            slug: String,
            description: Option<String>,
            is_answerable: bool,
        }
        #[derive(Deserialize)]
        struct Tree {
            entries: Option<Vec<Entry>>,
        }
        #[derive(Deserialize)]
        struct Entry {
            name: String,
            object: Option<Blob>,
        }
        #[derive(Deserialize)]
        struct Blob {
            text: Option<String>,
        }
        let found: Wire = (self.graphql_json(
            raw::DISCUSSION_FORMS,
            json!({ "owner": repo.owner, "name": repo.name }),
            repo,
            "/repository",
        ))
        .await?;
        let files: Vec<(String, String)> = (found.templates)
            .and_then(|t| t.entries)
            .unwrap_or_default()
            .into_iter()
            .filter_map(|e| Some((e.name, e.object?.text?)))
            .collect();
        let form = |slug: &str| {
            (files.iter())
                .find(|(name, _)| {
                    name.rsplit_once('.').is_some_and(|(stem, ext)| {
                        stem.eq_ignore_ascii_case(slug) && matches!(ext, "yml" | "yaml")
                    })
                })
                .map(|(_, text)| text.clone())
        };
        let categories = found.discussion_categories.into_capped(|c| {
            Some(Category {
                form: form(&c.slug),
                id: c.id,
                name: c.name,
                slug: c.slug,
                description: c.description.unwrap_or_default(),
                answerable: c.is_answerable,
            })
        });
        Ok(Categories {
            repo: found.id,
            categories,
        })
    }
}

fn lock_wire(reason: LockReason) -> &'static str {
    match reason {
        LockReason::OffTopic => "OFF_TOPIC",
        LockReason::Resolved => "RESOLVED",
        LockReason::Spam => "SPAM",
        LockReason::TooHeated => "TOO_HEATED",
    }
}

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

    #[test]
    fn an_issue_is_named_as_people_write_it() {
        let here = RepoId::new("o", "r");
        let at = |n| {
            Some(IssueAt {
                repo: here.clone(),
                number: n,
            })
        };
        assert_eq!(IssueAt::parse("#12", &here), at(12));
        assert_eq!(IssueAt::parse(" 7 ", &here), at(7));
        assert_eq!(
            IssueAt::parse("a/b#3", &here),
            Some(IssueAt {
                repo: RepoId::new("a", "b"),
                number: 3
            })
        );
        assert_eq!(
            IssueAt::parse("https://github.com/a/b/issues/9#issuecomment-1", &here),
            Some(IssueAt {
                repo: RepoId::new("a", "b"),
                number: 9
            })
        );
        assert_eq!(IssueAt::parse("#0", &here), None);
        assert_eq!(IssueAt::parse("fix it", &here), None);
    }
}