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
//! Repository housekeeping on GitHub: labels, milestones, branches and
//! tags, forks, new repositories, and files committed. What git does in
//! your clone is [`crate::housekeeping::git`]'s; this is what GitHub's API
//! does where there's no clone, and what only GitHub knows.

use serde::{Deserialize, Serialize};

use crate::api::browse::{Results, wire};
use crate::api::client::{ApiError, GitHub, encode_path};
use crate::api::model::{NodeId, RepoId};

// ---- labels ---------------------------------------------------------------------------

/// A repository's label, as its labels page lists it.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct LabelInfo {
    pub name: String,
    /// `rrggbb`, as GitHub keeps it.
    pub color: String,
    pub description: String,
    /// Its open issues and pull requests.
    pub open: u64,
}

/// A label as it's to be: made, or what one becomes.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct LabelChange {
    pub name: String,
    /// `rrggbb`, without `#`.
    pub color: String,
    pub description: String,
}

/// A repository's labels by name, 100 at a time from `after`, with how
/// many open issues and pull requests each has.
pub(crate) const LABELS: &str = "query($owner: String!, $name: String!, $after: String) { repository(owner: $owner, name: $name) { labels(first: 100, after: $after, orderBy: {field: NAME, direction: ASC}) { totalCount pageInfo { hasNextPage endCursor } nodes { name color description issues(states: OPEN) { totalCount } pullRequests(states: OPEN) { totalCount } } } } }";

/// Who you may make a repository for: you, and the organizations that
/// let you.
pub(crate) const OWNERS: &str = "query { viewer { login organizations(first: 100) { totalCount nodes { login viewerCanCreateRepositories } } } }";

/// What a file's form starts from: the repository, the branch's tip (or
/// the commit a tag or SHA names), and the file there.
pub(crate) const FILE_LOOK: &str = "query($owner: String!, $name: String!, $qualified: String!, $rev: String!, $spec: String!) { repository(owner: $owner, name: $name) { id ref(qualifiedName: $qualified) { target { oid } } commit: object(expression: $rev) { ... on Commit { oid } ... on Tag { target { oid } } } file: object(expression: $spec) { ... on Blob { oid text isBinary isTruncated } } } }";

/// One commit on a branch, made only if the branch is still at
/// `expectedHeadOid`.
pub(crate) const COMMIT_ON_BRANCH: &str = "mutation($input: CreateCommitOnBranchInput!) { createCommitOnBranch(input: $input) { commit { oid } } }";

/// This module's GraphQL, for the schema checks.
#[cfg(test)]
pub(crate) fn queries() -> Vec<(&'static str, String)> {
    vec![
        ("LABELS", LABELS.to_owned()),
        ("OWNERS", OWNERS.to_owned()),
        ("FILE_LOOK", FILE_LOOK.to_owned()),
        ("COMMIT_ON_BRANCH", COMMIT_ON_BRANCH.to_owned()),
    ]
}

// ---- milestones --------------------------------------------------------------------

/// A milestone as it's to be.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct MilestoneChange {
    pub title: String,
    pub description: String,
    /// `YYYY-MM-DD`; none for no due date.
    pub due_on: Option<String>,
}

/// What GitHub made: its number.
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
pub struct MadeMilestone {
    pub number: u64,
}

// ---- branches and tags ---------------------------------------------------------------

/// Whether a branch is a tag's or a branch's, for its ref's name.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum RefKind {
    Branch,
    Tag,
}

impl RefKind {
    /// Its refs' prefix below `refs/`.
    pub fn prefix(self) -> &'static str {
        match self {
            RefKind::Branch => "heads",
            RefKind::Tag => "tags",
        }
    }

    pub fn noun(self) -> &'static str {
        match self {
            RefKind::Branch => "branch",
            RefKind::Tag => "tag",
        }
    }

    /// `refs/heads/name`.
    pub fn full(self, name: &str) -> String {
        format!("refs/{}/{name}", self.prefix())
    }
}

/// What GitHub's rules say of deleting a branch.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct BranchRules {
    /// A branch protection rule covers it.
    pub protected: bool,
    /// A ruleset forbids deleting it.
    pub undeletable: bool,
}

// ---- forks and new repositories ---------------------------------------------------------

/// Who a repository can be made for.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Owners {
    pub viewer: String,
    /// Organizations, and whether you may make repositories there.
    pub orgs: Vec<(String, bool)>,
    /// Organizations GitHub didn't list (past its first 100).
    pub more: u64,
}

/// GitHub's templates for a new repository: `.gitignore`s by name, and
/// licences by key and name.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Templates {
    pub gitignores: Vec<String>,
    pub licenses: Vec<(String, String)>,
}

/// A fork to make.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct NewFork {
    pub repo: RepoId,
    /// An organization; none for your account.
    pub org: Option<String>,
    pub name: String,
    pub default_branch_only: bool,
}

/// A repository to make.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct NewRepo {
    /// An organization; none for your account.
    pub org: Option<String>,
    pub name: String,
    pub description: String,
    pub private: bool,
    pub readme: bool,
    pub gitignore: Option<String>,
    pub license: Option<String>,
}

/// A repository GitHub made (or is making: a fork arrives later).
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
pub struct MadeRepo {
    pub full_name: String,
    pub clone_url: String,
}

impl MadeRepo {
    pub fn repo(&self) -> Option<RepoId> {
        RepoId::parse(&self.full_name)
    }
}

// ---- files -------------------------------------------------------------------------------------

/// Where a file's form starts: the repository's ID, the branch's tip (or
/// the commit a tag or SHA names: then it isn't a branch), and the file
/// there.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FileLook {
    pub repo_id: NodeId,
    /// The branch's tip, when the revision is a branch.
    pub branch_head: Option<String>,
    /// The commit the revision names.
    pub commit: String,
    pub file: Option<FileAt>,
}

/// A file at a commit.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FileAt {
    /// Its blob: what says whether it changed.
    pub oid: String,
    /// `None` for a binary file, or one too big for GitHub's API.
    pub text: Option<String>,
}

/// One commit of files on a branch.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FileCommit {
    pub repo: RepoId,
    pub branch: String,
    /// The tip it's made on: GitHub refuses it if the branch moved since.
    pub head: String,
    pub headline: String,
    pub body: String,
    /// Paths and their new text.
    pub additions: Vec<(String, String)>,
    pub deletions: Vec<String>,
}

/// The token's `workflow` scope, which changing a workflow's file takes.
pub fn workflow_scoped(err: ApiError) -> ApiError {
    let lacks = |m: &str| m.contains("workflow") && m.contains("scope");
    let denied = || {
        ApiError::Denied(crate::api::scope_missing(
            "Changing a workflow's file",
            "workflow",
        ))
    };
    match &err {
        ApiError::GraphQl(m) if m.iter().any(|m| lacks(m)) => denied(),
        ApiError::Http { message, .. } if lacks(message) => denied(),
        _ => err,
    }
}

/// A ref's path below `/git/refs/` or a label's name, each segment
/// escaped.
fn segments(path: &str) -> String {
    path.split('/')
        .map(encode_path)
        .collect::<Vec<_>>()
        .join("/")
}

impl GitHub {
    /// A repository's labels by name, 100 at a time from `after`.
    pub async fn labels(
        &self,
        repo: &RepoId,
        after: Option<String>,
    ) -> Result<Results<LabelInfo>, ApiError> {
        #[derive(Deserialize)]
        #[serde(rename_all = "camelCase")]
        struct Wire {
            name: String,
            color: String,
            description: Option<String>,
            issues: wire::Count,
            pull_requests: wire::Count,
        }
        let vars = serde_json::json!({ "owner": repo.owner, "name": repo.name, "after": after });
        let page: wire::Connection<Wire> = self
            .graphql_json(LABELS, vars, repo, "/repository/labels")
            .await?;
        self.check_connection(&page, 100, format!("{repo}'s labels"));
        let labels = page.into_results(|l| LabelInfo {
            name: l.name,
            color: l.color,
            description: l.description.unwrap_or_default(),
            open: l.issues.total_count + l.pull_requests.total_count,
        });
        Ok(labels)
    }

    pub async fn create_label(&self, repo: &RepoId, label: &LabelChange) -> Result<(), ApiError> {
        let body = serde_json::json!({
            "name": label.name,
            "color": label.color,
            "description": label.description,
        });
        let path = format!("/repos/{repo}/labels");
        self.rest_write(http::Method::POST, &path, Some(&body))
            .await
    }

    /// Changes label `was` into `label`: its name, colour and description.
    pub async fn update_label(
        &self,
        repo: &RepoId,
        was: &str,
        label: &LabelChange,
    ) -> Result<(), ApiError> {
        let body = serde_json::json!({
            "new_name": label.name,
            "color": label.color,
            "description": label.description,
        });
        let path = format!("/repos/{repo}/labels/{}", encode_path(was));
        self.rest_write(http::Method::PATCH, &path, Some(&body))
            .await
    }

    pub async fn delete_label(&self, repo: &RepoId, name: &str) -> Result<(), ApiError> {
        let path = format!("/repos/{repo}/labels/{}", encode_path(name));
        self.rest_write(http::Method::DELETE, &path, None).await
    }

    pub async fn create_milestone(
        &self,
        repo: &RepoId,
        m: &MilestoneChange,
    ) -> Result<MadeMilestone, ApiError> {
        let path = format!("/repos/{repo}/milestones");
        self.rest_write_json(http::Method::POST, &path, Some(&milestone_body(m)))
            .await
    }

    pub async fn update_milestone(
        &self,
        repo: &RepoId,
        number: u64,
        m: &MilestoneChange,
    ) -> Result<(), ApiError> {
        let path = format!("/repos/{repo}/milestones/{number}");
        self.rest_write(http::Method::PATCH, &path, Some(&milestone_body(m)))
            .await
    }

    /// Closes milestone `number`, or reopens it.
    pub async fn set_milestone_closed(
        &self,
        repo: &RepoId,
        number: u64,
        closed: bool,
    ) -> Result<(), ApiError> {
        let state = if closed { "closed" } else { "open" };
        let body = serde_json::json!({ "state": state });
        let path = format!("/repos/{repo}/milestones/{number}");
        self.rest_write(http::Method::PATCH, &path, Some(&body))
            .await
    }

    pub async fn delete_milestone(&self, repo: &RepoId, number: u64) -> Result<(), ApiError> {
        let path = format!("/repos/{repo}/milestones/{number}");
        self.rest_write(http::Method::DELETE, &path, None).await
    }

    /// The commit `rev` (a branch, a tag or a SHA) names, as GitHub has it.
    pub async fn commit_of(&self, repo: &RepoId, rev: &str) -> Result<String, ApiError> {
        #[derive(Deserialize)]
        struct Wire {
            sha: String,
        }
        let path = format!("/repos/{repo}/commits/{}", segments(rev));
        let answer = self.rest_get(&path, format!("{rev} in {repo}")).await?;
        Ok(serde_json::from_str::<Wire>(&answer)?.sha)
    }

    /// Makes branch or tag `name` at commit `sha`.
    pub async fn create_ref(
        &self,
        repo: &RepoId,
        kind: RefKind,
        name: &str,
        sha: &str,
    ) -> Result<(), ApiError> {
        let body = serde_json::json!({ "ref": kind.full(name), "sha": sha });
        let path = format!("/repos/{repo}/git/refs");
        self.rest_write(http::Method::POST, &path, Some(&body))
            .await
    }

    pub async fn delete_ref(
        &self,
        repo: &RepoId,
        kind: RefKind,
        name: &str,
    ) -> Result<(), ApiError> {
        let path = format!(
            "/repos/{repo}/git/refs/{}/{}",
            kind.prefix(),
            segments(name)
        );
        self.rest_write(http::Method::DELETE, &path, None).await
    }

    /// Whether GitHub's rules keep branch `name` from being deleted: a
    /// branch protection rule, or a ruleset's.
    pub async fn branch_rules(&self, repo: &RepoId, name: &str) -> Result<BranchRules, ApiError> {
        #[derive(Deserialize)]
        struct Branch {
            protected: bool,
        }
        #[derive(Deserialize)]
        struct Rule {
            #[serde(rename = "type")]
            kind: String,
        }
        let path = format!("/repos/{repo}/branches/{}", segments(name));
        let branch: Branch = serde_json::from_str(&self.rest_get(&path, name).await?)?;
        // Rulesets: GitHub lists the rules that apply to the branch.
        let path = format!("/repos/{repo}/rules/branches/{}", segments(name));
        let rules: Vec<Rule> = match self.rest_get(&path, name).await {
            Ok(body) => serde_json::from_str(&body)?,
            // An older Enterprise Server has no rulesets.
            Err(ApiError::NotFound(_)) => Vec::new(),
            Err(err) => return Err(err),
        };
        Ok(BranchRules {
            protected: branch.protected,
            undeletable: rules.iter().any(|r| r.kind == "deletion"),
        })
    }

    /// You, and the organizations you're in.
    pub async fn owners(&self) -> Result<Owners, ApiError> {
        #[derive(Deserialize)]
        #[serde(rename_all = "camelCase")]
        struct Org {
            login: String,
            viewer_can_create_repositories: bool,
        }
        #[derive(Deserialize)]
        #[serde(rename_all = "camelCase")]
        struct Viewer {
            login: String,
            organizations: wire::Counted<Org>,
        }
        let viewer: Viewer = self
            .graphql_json(OWNERS, serde_json::json!({}), "your account", "/viewer")
            .await?;
        let orgs: Vec<(String, bool)> = (viewer.organizations.nodes.into_iter().flatten())
            .map(|o| (o.login, o.viewer_can_create_repositories))
            .collect();
        let more = (viewer.organizations.total_count).saturating_sub(orgs.len() as u64);
        Ok(Owners {
            viewer: viewer.login,
            orgs,
            more,
        })
    }

    /// GitHub's `.gitignore` and licence templates.
    pub async fn templates(&self) -> Result<Templates, ApiError> {
        #[derive(Deserialize)]
        struct License {
            key: String,
            name: String,
        }
        let gitignores = self.rest_get("/gitignore/templates", "templates").await?;
        let licenses = self.rest_get("/licenses", "licences").await?;
        let licenses: Vec<License> = serde_json::from_str(&licenses)?;
        Ok(Templates {
            gitignores: serde_json::from_str(&gitignores)?,
            licenses: licenses.into_iter().map(|l| (l.key, l.name)).collect(),
        })
    }

    pub async fn fork(&self, new: &NewFork) -> Result<MadeRepo, ApiError> {
        let mut body = serde_json::json!({
            "name": new.name,
            "default_branch_only": new.default_branch_only,
        });
        if let (Some(org), Some(map)) = (&new.org, body.as_object_mut()) {
            map.insert("organization".into(), org.clone().into());
        }
        let path = format!("/repos/{}/forks", new.repo);
        self.rest_write_json(http::Method::POST, &path, Some(&body))
            .await
    }

    pub async fn create_repo(&self, new: &NewRepo) -> Result<MadeRepo, ApiError> {
        let mut body = serde_json::json!({
            "name": new.name,
            "description": new.description,
            "private": new.private,
            "auto_init": new.readme,
        });
        if let Some(map) = body.as_object_mut() {
            if let Some(g) = &new.gitignore {
                map.insert("gitignore_template".into(), g.clone().into());
            }
            if let Some(l) = &new.license {
                map.insert("license_template".into(), l.clone().into());
            }
        }
        let path = match &new.org {
            Some(org) => format!("/orgs/{}/repos", encode_path(org)),
            None => "/user/repos".to_owned(),
        };
        self.rest_write_json(http::Method::POST, &path, Some(&body))
            .await
    }

    /// Where a file's form starts: `rev`'s commit (a branch's tip when
    /// it's a branch), and the file at `path` there, if there's one.
    pub async fn file_look(
        &self,
        repo: &RepoId,
        rev: &str,
        path: &str,
    ) -> Result<FileLook, ApiError> {
        #[derive(Deserialize)]
        struct Oid {
            oid: String,
        }
        #[derive(Deserialize)]
        struct Target {
            target: Oid,
        }
        #[derive(Deserialize)]
        #[serde(untagged)]
        enum Commit {
            Commit(Oid),
            Tag(Target),
        }
        #[derive(Deserialize)]
        #[serde(rename_all = "camelCase")]
        struct Blob {
            /// None when the path is a folder.
            oid: Option<String>,
            text: Option<String>,
            is_binary: Option<bool>,
            #[serde(default)]
            is_truncated: bool,
        }
        #[derive(Deserialize)]
        struct Wire {
            id: NodeId,
            #[serde(rename = "ref")]
            branch: Option<Target>,
            commit: Option<Commit>,
            file: Option<Blob>,
        }
        let vars = serde_json::json!({
            "owner": repo.owner,
            "name": repo.name,
            "qualified": format!("refs/heads/{rev}"),
            "rev": rev,
            "spec": format!("{rev}:{path}"),
        });
        let wire: Wire = self
            .graphql_json(FILE_LOOK, vars, repo, "/repository")
            .await?;
        let commit = match wire.commit {
            Some(Commit::Commit(c)) => c.oid,
            Some(Commit::Tag(t)) => t.target.oid,
            None => return Err(ApiError::NotFound(format!("{rev} in {repo}"))),
        };
        let file = (wire.file).and_then(|b| {
            Some(FileAt {
                oid: b.oid?,
                text: (b.text).filter(|_| !b.is_truncated && b.is_binary != Some(true)),
            })
        });
        Ok(FileLook {
            repo_id: wire.id,
            branch_head: wire.branch.map(|b| b.target.oid),
            commit,
            file,
        })
    }

    /// Commits files on a branch, as GitHub's website does: only while
    /// the branch is still at the tip it was made on.
    pub async fn commit_files(&self, c: &FileCommit) -> Result<(), ApiError> {
        use base64::Engine;
        let b64 = |text: &str| base64::engine::general_purpose::STANDARD.encode(text);
        let additions: Vec<serde_json::Value> = (c.additions.iter())
            .map(|(path, text)| serde_json::json!({ "path": path, "contents": b64(text) }))
            .collect();
        let deletions: Vec<serde_json::Value> = (c.deletions.iter())
            .map(|path| serde_json::json!({ "path": path }))
            .collect();
        let mut message = serde_json::json!({ "headline": c.headline });
        if !c.body.is_empty()
            && let Some(map) = message.as_object_mut()
        {
            map.insert("body".into(), c.body.clone().into());
        }
        let input = serde_json::json!({
            "branch": {
                "repositoryNameWithOwner": c.repo.to_string(),
                "branchName": c.branch,
            },
            "expectedHeadOid": c.head,
            "message": message,
            "fileChanges": { "additions": additions, "deletions": deletions },
        });
        let vars = serde_json::json!({ "input": input });
        self.mutate_json(COMMIT_ON_BRANCH, vars)
            .await
            .map_err(workflow_scoped)
    }
}

/// A milestone's fields as GitHub's REST API takes them. A due date is
/// sent at noon UTC, which is that day wherever GitHub reads it.
fn milestone_body(m: &MilestoneChange) -> serde_json::Value {
    let due = m.due_on.as_ref().map(|d| format!("{d}T12:00:00Z"));
    serde_json::json!({
        "title": m.title,
        "description": m.description,
        "due_on": due,
    })
}