thirdshift 0.6.0

Turn a GitHub issue into a ready-for-review pull request, unattended
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
//! Asking GitHub, through `gh`, about issues, pull requests and the signed-in
//! user.

use std::fmt;
use std::process::Command;

use anyhow::{Context, Result, bail};
use chrono::{DateTime, Utc};
use serde_json::Value;

use crate::issue::IssueUrl;

/// The `fields` of `issue`, as JSON.
fn issue_view(issue: &IssueUrl, fields: &str) -> Result<Value> {
    gh_json(&[
        "issue",
        "view",
        &issue.number.to_string(),
        "--repo",
        &issue.repo_slug(),
        "--json",
        fields,
    ])
}

/// Whether the issue `json` describes, with its `state`, is open.
fn state_is_open(json: &Value) -> Result<bool> {
    Ok(json["state"].as_str().context("gh output has no state")? == "OPEN")
}

/// Whether `issue` is open.
pub fn issue_is_open(issue: &IssueUrl) -> Result<bool> {
    state_is_open(&issue_view(issue, "state")?)
}

/// The title of `issue`.
pub fn issue_title(issue: &IssueUrl) -> Result<String> {
    let json = issue_view(issue, "title")?;
    Ok(json["title"]
        .as_str()
        .context("gh output has no title")?
        .to_string())
}

/// An issue as an Architect run reads the plan its Architecture review
/// published.
pub struct Issue {
    pub is_open: bool,
    pub labels: Vec<String>,
    pub created: DateTime<Utc>,
}

/// `issue`'s state, labels and when it was created.
pub fn issue(issue: &IssueUrl) -> Result<Issue> {
    let json = issue_view(issue, "state,labels,createdAt")?;
    let created = json["createdAt"]
        .as_str()
        .context("gh output has no createdAt")?;
    Ok(Issue {
        is_open: state_is_open(&json)?,
        labels: json["labels"]
            .as_array()
            .context("gh output has no labels")?
            .iter()
            .filter_map(|label| label["name"].as_str().map(String::from))
            .collect(),
        created: DateTime::parse_from_rfc3339(created)
            .with_context(|| format!("gh output has an unreadable createdAt {created}"))?
            .to_utc(),
    })
}

/// Set `issue`'s labels to exactly `labels`, in one request, so a swap of
/// one label for another can't stop halfway. Through the REST API: `gh issue
/// edit` fails on the GitHub Projects (classic) sunset in older `gh`.
pub fn set_labels(issue: &IssueUrl, labels: &[&str]) -> Result<()> {
    let path = format!("repos/{}/issues/{}/labels", issue.repo_slug(), issue.number);
    let fields: Vec<String> = labels
        .iter()
        .map(|label| format!("labels[]={label}"))
        .collect();
    let mut args = vec!["api", "--method", "PUT", &path, "--silent"];
    for field in &fields {
        args.extend(["-f", field]);
    }
    gh(&args)
}

/// A Spec's sub-issue, as a Spec run reads it.
pub struct Ticket {
    pub number: u64,
    pub is_open: bool,
    pub labels: Vec<String>,
    /// It has sub-issues of its own.
    pub has_sub_issues: bool,
    /// The numbers of the issues it is blocked by, in the Spec or not.
    pub blockers: Vec<u64>,
    /// The numbers of those blockers that are open.
    pub open_blockers: Vec<u64>,
}

/// Every sub-issue of `issue`, open or closed, with its labels, whether it
/// has sub-issues of its own and the issues it is blocked by: its GitHub
/// "blocked by" links, never the text of its body.
const TICKETS_QUERY: &str = "\
query($owner: String!, $repo: String!, $number: Int!) {
  repository(owner: $owner, name: $repo) {
    issue(number: $number) {
      subIssues(first: 100) {
        nodes {
          number
          state
          labels(first: 100) { nodes { name } }
          subIssues { totalCount }
          blockedBy(first: 100) { nodes { number state } }
        }
      }
    }
  }
}";

/// The sub-issues of `issue`, its Tickets if it has any, in one query.
pub fn tickets(issue: &IssueUrl) -> Result<Vec<Ticket>> {
    let json = gh_json(&[
        "api",
        "graphql",
        "-f",
        &format!("query={TICKETS_QUERY}"),
        "-f",
        &format!("owner={}", issue.owner),
        "-f",
        &format!("repo={}", issue.repo),
        "-F",
        &format!("number={}", issue.number),
    ])?;
    let nodes = |value: &Value, what: &str| -> Result<Vec<Value>> {
        value["nodes"]
            .as_array()
            .cloned()
            .with_context(|| format!("gh api graphql output has no {what}"))
    };
    let is_open = |node: &Value| -> Result<bool> {
        Ok(node["state"]
            .as_str()
            .context("gh api graphql output has an issue with no state")?
            == "OPEN")
    };
    let number = |node: &Value| {
        node["number"]
            .as_u64()
            .context("gh api graphql output has an issue with no number")
    };
    nodes(
        &json["data"]["repository"]["issue"]["subIssues"],
        "subIssues",
    )?
    .iter()
    .map(|node| {
        let mut blockers = Vec::new();
        let mut open_blockers = Vec::new();
        for blocker in nodes(&node["blockedBy"], "blockedBy")? {
            blockers.push(number(&blocker)?);
            if is_open(&blocker)? {
                open_blockers.push(number(&blocker)?);
            }
        }
        Ok(Ticket {
            number: number(node)?,
            is_open: is_open(node)?,
            labels: nodes(&node["labels"], "labels")?
                .iter()
                .filter_map(|label| label["name"].as_str().map(String::from))
                .collect(),
            has_sub_issues: node["subIssues"]["totalCount"]
                .as_u64()
                .context("gh api graphql output has an issue with no subIssues count")?
                > 0,
            blockers,
            open_blockers,
        })
    })
    .collect()
}

/// Close `issue` with `comment`.
pub fn close_issue(issue: &IssueUrl, comment: &str) -> Result<()> {
    gh(&[
        "issue",
        "close",
        &issue.number.to_string(),
        "--repo",
        &issue.repo_slug(),
        "--comment",
        comment,
    ])
}

/// Every open issue labelled `label` in the repository of `issue`, with its
/// title. They come from GitHub's issue list, not its search, whose index can
/// be a while behind an issue just opened.
pub fn open_issues_labelled(issue: &IssueUrl, label: &str) -> Result<Vec<(IssueUrl, String)>> {
    let json = gh_json(&[
        "issue",
        "list",
        "--repo",
        &issue.repo_slug(),
        "--label",
        label,
        "--state",
        "open",
        "--json",
        "url,title",
        "--limit",
        "1000",
    ])?;
    json.as_array()
        .context("gh issue list did not return a list")?
        .iter()
        .map(|listed| {
            let field = |name: &str| {
                listed[name]
                    .as_str()
                    .with_context(|| format!("gh issue list output has no {name}"))
            };
            Ok((IssueUrl::parse(field("url")?)?, field("title")?.to_string()))
        })
        .collect()
}

/// Open an issue titled `title`, with `body` and `labels`, in the repository
/// of `issue`, and return it. Each label is first added to the repository,
/// with its description, if the repository lacks it: `gh` refuses a label it
/// doesn't know.
pub fn create_issue(
    issue: &IssueUrl,
    title: &str,
    body: &str,
    labels: &[(&str, &str)],
) -> Result<IssueUrl> {
    let repo = issue.repo_slug();
    let known = gh_json(&[
        "label", "list", "--repo", &repo, "--json", "name", "--limit", "1000",
    ])?;
    let known: Vec<&str> = known
        .as_array()
        .context("gh label list did not return a list")?
        .iter()
        .filter_map(|label| label["name"].as_str())
        .collect();
    for (name, description) in labels {
        // GitHub's label names are case-insensitive.
        if !known.iter().any(|known| known.eq_ignore_ascii_case(name)) {
            gh(&[
                "label",
                "create",
                name,
                "--repo",
                &repo,
                "--description",
                description,
            ])?;
        }
    }
    let names: Vec<&str> = labels.iter().map(|(name, _)| *name).collect();
    let url = gh_stdout(&[
        "issue",
        "create",
        "--repo",
        &repo,
        "--title",
        title,
        "--body",
        body,
        "--label",
        &names.join(","),
    ])?;
    IssueUrl::parse(&url).context("gh issue create did not print the issue's URL")
}

/// The public email of the signed-in user's GitHub profile, or `None` if it
/// is private. Private addresses need the `user` scope, which a default
/// `gh auth login` token lacks, so thirdshift never asks for them.
pub fn profile_email() -> Result<Option<String>> {
    let json = gh_json(&["api", "user"])?;
    Ok(json["email"].as_str().map(str::to_string))
}

const PR_FIELDS: &str = "number,url,state,headRefName,baseRefName,isDraft";

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PrState {
    Open,
    Closed,
    Merged,
}

impl fmt::Display for PrState {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(match self {
            PrState::Open => "open",
            PrState::Closed => "closed",
            PrState::Merged => "merged",
        })
    }
}

pub struct PullRequest {
    pub number: u64,
    pub url: String,
    pub state: PrState,
    pub head: String,
    pub base: String,
    pub is_draft: bool,
}

impl PullRequest {
    pub fn is_open(&self) -> bool {
        self.state == PrState::Open
    }

    fn from_json(json: &Value) -> Result<Self> {
        let field = |name: &str| -> Result<String> {
            json[name]
                .as_str()
                .map(String::from)
                .with_context(|| format!("gh output has no {name}"))
        };
        let state = match field("state")?.as_str() {
            "OPEN" => PrState::Open,
            "CLOSED" => PrState::Closed,
            "MERGED" => PrState::Merged,
            other => bail!("gh output has an unknown PR state {other}"),
        };
        Ok(PullRequest {
            number: json["number"].as_u64().context("gh output has no number")?,
            url: field("url")?,
            state,
            head: field("headRefName")?,
            base: field("baseRefName")?,
            is_draft: json["isDraft"]
                .as_bool()
                .context("gh output has no isDraft")?,
        })
    }
}

/// The `fields` of the pull request `pr`, its head branch or its number, as
/// JSON.
fn pr_view(issue: &IssueUrl, pr: &str, fields: &str) -> Result<Value> {
    gh_json(&[
        "pr",
        "view",
        pr,
        "--repo",
        &issue.repo_slug(),
        "--json",
        fields,
    ])
}

/// The pull request whose head is `branch`, if `gh` finds one.
pub fn pull_request_for(issue: &IssueUrl, branch: &str) -> Result<Option<PullRequest>> {
    let json = match pr_view(issue, branch, PR_FIELDS) {
        Ok(json) => json,
        Err(error) if format!("{error:#}").contains("no pull requests found") => return Ok(None),
        Err(error) => return Err(error),
    };
    PullRequest::from_json(&json).map(Some)
}

/// Every pull request in this repository, in any state, whose head branch
/// starts with `prefix`. PRs from forks are left out: their heads are not
/// this repository's branches.
pub fn pull_requests_with_head_prefix(issue: &IssueUrl, prefix: &str) -> Result<Vec<PullRequest>> {
    let json = gh_json(&[
        "pr",
        "list",
        "--repo",
        &issue.repo_slug(),
        "--state",
        "all",
        "--search",
        &format!("head:{prefix}"),
        "--limit",
        "1000",
        "--json",
        &format!("{PR_FIELDS},isCrossRepository"),
    ])?;
    json.as_array()
        .context("gh pr list did not return a list")?
        .iter()
        .filter(|pr| pr["isCrossRepository"] != Value::Bool(true))
        .map(PullRequest::from_json)
        .collect()
}

/// Open a draft pull request from `head` into `base`, and return its URL.
pub fn create_draft_pr(
    issue: &IssueUrl,
    head: &str,
    base: &str,
    title: &str,
    body: &str,
) -> Result<String> {
    gh_stdout(&[
        "pr",
        "create",
        "--repo",
        &issue.repo_slug(),
        "--head",
        head,
        "--base",
        base,
        "--title",
        title,
        "--body",
        body,
        "--draft",
    ])
}

/// The body of pull request `number`.
pub fn pr_body(issue: &IssueUrl, number: u64) -> Result<String> {
    let json = pr_view(issue, &number.to_string(), "body")?;
    Ok(json["body"]
        .as_str()
        .context("gh output has no body")?
        .to_string())
}

/// Set the body of pull request `number` to `body`, through the REST API:
/// `gh pr edit` fails on the GitHub Projects (classic) sunset in older `gh`.
pub fn set_pr_body(issue: &IssueUrl, number: u64, body: &str) -> Result<()> {
    gh(&[
        "api",
        "--method",
        "PATCH",
        &format!("repos/{}/pulls/{number}", issue.repo_slug()),
        "-f",
        &format!("body={body}"),
        "--silent",
    ])
}

/// Mark the pull request whose head is `branch` ready for review.
pub fn mark_ready(issue: &IssueUrl, branch: &str) -> Result<()> {
    gh(&["pr", "ready", branch, "--repo", &issue.repo_slug()])
}

/// Convert the pull request whose head is `branch` back to a draft.
pub fn convert_to_draft(issue: &IssueUrl, branch: &str) -> Result<()> {
    gh(&[
        "pr",
        "ready",
        branch,
        "--undo",
        "--repo",
        &issue.repo_slug(),
    ])
}

/// Merge the pull request whose head is `branch` into its base with a merge
/// commit, but only if its head is still `head`. Never GitHub's auto-merge
/// (ADR-0004), and never `--delete-branch`, whose local deletion would
/// interfere with the worktree. If `gh` fails but the pull request merged at
/// `head` anyway, e.g. because `gh` was interrupted once GitHub had merged,
/// that is a merge.
pub fn merge(issue: &IssueUrl, branch: &str, head: &str) -> Result<()> {
    let Err(error) = gh(&[
        "pr",
        "merge",
        branch,
        "--repo",
        &issue.repo_slug(),
        "--merge",
        "--match-head-commit",
        head,
    ]) else {
        return Ok(());
    };
    match merged_head(issue, branch) {
        Ok(Some(merged)) if merged == head => Ok(()),
        _ => Err(error),
    }
}

/// The head commit the pull request whose head is `branch` was merged at, if
/// it is merged.
fn merged_head(issue: &IssueUrl, branch: &str) -> Result<Option<String>> {
    let json = pr_view(issue, branch, "state,headRefOid")?;
    if json["state"] != "MERGED" {
        return Ok(None);
    }
    let head = json["headRefOid"]
        .as_str()
        .context("gh output has no headRefOid")?;
    Ok(Some(head.to_string()))
}

/// Whether a pull request can be merged into its base.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Mergeable {
    Yes,
    /// It conflicts with its base.
    No,
    /// GitHub is still working it out.
    Unknown,
}

/// Whether the pull request whose head is `branch` can be merged.
pub fn mergeable(issue: &IssueUrl, branch: &str) -> Result<Mergeable> {
    let json = pr_view(issue, branch, "mergeable")?;
    match json["mergeable"].as_str() {
        Some("MERGEABLE") => Ok(Mergeable::Yes),
        Some("CONFLICTING") => Ok(Mergeable::No),
        Some("UNKNOWN") => Ok(Mergeable::Unknown),
        other => bail!("gh output has an unknown mergeable state {other:?}"),
    }
}

/// Where a check or status stands.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CheckState {
    Pending,
    Passed,
    Failed,
}

/// A check run or a commit status.
pub struct Check {
    pub name: String,
    pub state: CheckState,
    pub url: Option<String>,
}

/// Every check run and commit status on commit `sha`.
pub fn checks_on(issue: &IssueUrl, sha: &str) -> Result<Vec<Check>> {
    let commit = format!("repos/{}/commits/{sha}", issue.repo_slug());
    let runs = gh_api_items(&format!("{commit}/check-runs?per_page=100"), "check_runs")?;
    let statuses = gh_api_items(&format!("{commit}/status?per_page=100"), "statuses")?;
    let url = |value: &Value| {
        value
            .as_str()
            .filter(|url| !url.is_empty())
            .map(String::from)
    };

    let mut checks = Vec::new();
    for run in &runs {
        let state = match (run["status"].as_str(), run["conclusion"].as_str()) {
            (Some("completed"), Some("success" | "neutral" | "skipped")) => CheckState::Passed,
            (Some("completed"), _) => CheckState::Failed,
            _ => CheckState::Pending,
        };
        checks.push(Check {
            name: run["name"]
                .as_str()
                .context("a check run has no name")?
                .to_string(),
            state,
            url: url(&run["details_url"]).or_else(|| url(&run["html_url"])),
        });
    }
    for status in &statuses {
        let state = match status["state"].as_str() {
            Some("success") => CheckState::Passed,
            Some("pending") => CheckState::Pending,
            _ => CheckState::Failed,
        };
        checks.push(Check {
            name: status["context"]
                .as_str()
                .context("a commit status has no context")?
                .to_string(),
            state,
            url: url(&status["target_url"]),
        });
    }
    Ok(checks)
}

/// Run `gh <args>`, failing with its stderr if it exits non-zero.
fn gh(args: &[&str]) -> Result<()> {
    gh_stdout(args).map(drop)
}

/// Run `gh <args>` and return its trimmed stdout, failing with its stderr if
/// it exits non-zero.
fn gh_stdout(args: &[&str]) -> Result<String> {
    let output = Command::new("gh")
        .args(args)
        .output()
        .context("could not run gh")?;
    if !output.status.success() {
        bail!(
            "gh {} failed: {}",
            args.join(" "),
            String::from_utf8_lossy(&output.stderr).trim()
        );
    }
    Ok(String::from_utf8_lossy(&output.stdout).trim().to_string())
}

/// Every item of the `field` list of the GitHub API's `path`, across all its
/// pages.
fn gh_api_items(path: &str, field: &str) -> Result<Vec<Value>> {
    let output = Command::new("gh")
        .args(["api", "--paginate", "--jq", &format!(".{field}[]"), path])
        .output()
        .context("could not run gh")?;
    if !output.status.success() {
        bail!(
            "gh api {path} failed: {}",
            String::from_utf8_lossy(&output.stderr).trim()
        );
    }
    serde_json::Deserializer::from_slice(&output.stdout)
        .into_iter()
        .collect::<Result<_, _>>()
        .with_context(|| format!("gh api {path} returned invalid JSON"))
}

/// Run `gh <args>` and parse its stdout as JSON, failing with gh's stderr if
/// it exits non-zero.
fn gh_json(args: &[&str]) -> Result<Value> {
    let command = format!("gh {}", args[..2].join(" "));
    let output = Command::new("gh")
        .args(args)
        .output()
        .context("could not run gh")?;
    if !output.status.success() {
        bail!(
            "{command} failed: {}",
            String::from_utf8_lossy(&output.stderr).trim()
        );
    }
    serde_json::from_slice(&output.stdout)
        .with_context(|| format!("{command} returned invalid JSON"))
}