Initial public release

Luxe 0.1.0: a coding agent harness for the terminal. See README.md to get started and CHANGELOG.md for releases.
This commit is contained in:
Evan Whittaker
2026-10-17 12:08:30 -05:00
commit 09a7de2520
1730 changed files with 412952 additions and 0 deletions

View File

@@ -0,0 +1,144 @@
//! Branch heads — where the checked-out branch is published, which decides its pull request.
//!
//! A pull request is found by its head branch's name, and on a popular repository many forks push
//! a branch called `fix-typo`. What makes one of them yours is the repository you push to, so the
//! head carries that owner, read from git's own idea of where `git push` goes (`@{push}`).
use super::gh::local_remotes;
use super::remote::parse_remote_url;
use super::BranchHead;
use crate::program::{captured_command, run_bounded};
use std::path::{Path, PathBuf};
use std::time::Duration;
/// How long a local git read may take. It reads config and refs; anything slower is stuck.
const GIT_DEADLINE: Duration = Duration::from_secs(10);
/// The branch checked out in `cwd` and where it is pushed, or `None` on a detached `HEAD` or
/// outside a repository.
pub async fn branch_head(cwd: &Path) -> Option<BranchHead> {
let local = git(cwd, &["symbolic-ref", "--quiet", "--short", "HEAD"]).await?;
let push = git(cwd, &["rev-parse", "--symbolic-full-name", "@{push}"]).await;
Some(head_from(&local, push.as_deref(), &local_remotes(cwd).await))
}
/// Where `local` is pushed, given git's `@{push}` ref and the checkout's remotes.
///
/// A branch with nowhere to push keeps its own name and no owner. So does one pushed to a remote
/// that is not a hosted repository, since no pull request can have it as its head.
fn head_from(local: &str, push_ref: Option<&str>, remotes: &[(String, String)]) -> BranchHead {
let unpublished = || BranchHead { name: local.to_string(), owner: None };
let Some(tracking) = push_ref.and_then(|push| push.strip_prefix("refs/remotes/")) else {
return unpublished();
};
// The longest remote name that prefixes the ref, since a remote may be named `a` and `a/b`
let found = remotes
.iter()
.filter_map(|(remote, url)| {
let name = tracking.strip_prefix(remote.as_str())?.strip_prefix('/')?;
(!name.is_empty()).then_some((remote.len(), name, url))
})
.max_by_key(|(length, ..)| *length);
match found {
Some((_, name, url)) => BranchHead {
name: name.to_string(),
owner: parse_remote_url(url).map(|parsed| parsed.owner),
},
None => unpublished(),
}
}
/// One line of git's output in `cwd`, or `None` when it fails or prints nothing.
async fn git(cwd: &Path, args: &[&str]) -> Option<String> {
let program = crate::program::resolve("git").unwrap_or_else(|| PathBuf::from("git"));
let output = run_bounded(captured_command(program, args, cwd), GIT_DEADLINE).await.ok()?;
let line = String::from_utf8_lossy(&output.stdout).trim().to_string();
(output.status.success() && !line.is_empty()).then_some(line)
}
#[cfg(test)]
mod tests {
use super::*;
fn remotes(pairs: &[(&str, &str)]) -> Vec<(String, String)> {
pairs.iter().map(|(name, url)| ((*name).to_string(), (*url).to_string())).collect()
}
#[test]
fn the_push_target_names_the_owner_and_the_remote_branch() {
let remotes = remotes(&[
("origin", "git@github.com:me/luxe.git"),
("upstream", "https://github.com/acme/luxe"),
]);
let head = head_from("topic", Some("refs/remotes/origin/feat/topic"), &remotes);
assert_eq!(head, BranchHead { name: "feat/topic".into(), owner: Some("me".into()) });
}
#[test]
fn the_longest_remote_name_wins() {
let remotes = remotes(&[
("fork", "https://github.com/short/luxe"),
("fork/team", "https://github.com/team/luxe"),
]);
let head = head_from("x", Some("refs/remotes/fork/team/x"), &remotes);
assert_eq!(head, BranchHead { name: "x".into(), owner: Some("team".into()) });
}
#[test]
fn nowhere_to_push_keeps_the_local_name_and_no_owner() {
let remotes = remotes(&[("origin", "git@github.com:me/luxe.git")]);
let unpublished = BranchHead { name: "topic".into(), owner: None };
assert_eq!(head_from("topic", None, &remotes), unpublished);
assert_eq!(head_from("topic", Some("refs/heads/topic"), &remotes), unpublished);
assert_eq!(head_from("topic", Some("refs/remotes/gone/topic"), &remotes), unpublished);
assert_eq!(head_from("topic", Some("refs/remotes/origin/"), &remotes), unpublished);
}
#[test]
fn a_remote_that_is_not_hosted_has_no_owner() {
let remotes = remotes(&[("local", "/srv/git/luxe.git")]);
let head = head_from("topic", Some("refs/remotes/local/topic"), &remotes);
assert_eq!(head, BranchHead { name: "topic".into(), owner: None });
}
/// Against a real repository: a branch pushed to a remote reports that remote's owner and the
/// branch's name there, and a detached `HEAD` has no head at all.
#[tokio::test]
async fn a_real_checkout_reports_where_it_pushes() {
let dir = tempfile::tempdir().unwrap();
let root = dir.path();
let run = |args: &[&str]| {
let output =
std::process::Command::new("git").args(args).current_dir(root).output().unwrap();
assert!(output.status.success(), "{args:?}: {output:?}");
};
run(&["init", "-q", "-b", "topic"]);
run(&[
"-c",
"user.name=t",
"-c",
"user.email=t@t",
"commit",
"-q",
"--allow-empty",
"-m",
"a",
]);
run(&["remote", "add", "origin", "git@github.com:me/luxe.git"]);
run(&["update-ref", "refs/remotes/origin/topic", "HEAD"]);
run(&["branch", "-q", "--set-upstream-to=origin/topic"]);
// Whatever the machine's own config says about where pushes go
run(&["config", "push.default", "simple"]);
run(&["config", "remote.pushDefault", "origin"]);
let head = branch_head(root).await.expect("a branch is checked out");
assert_eq!(head, BranchHead { name: "topic".into(), owner: Some("me".into()) });
run(&["checkout", "-q", "--detach"]);
assert_eq!(branch_head(root).await, None);
// A read that succeeds with nothing to say, and one that fails after printing
assert_eq!(git(root, &["rev-parse", "--show-prefix"]).await, None);
assert_eq!(git(root, &["rev-parse", "no-such-ref"]).await, None);
}
}

View File

@@ -0,0 +1 @@
{"data":{"repository":{"pullRequests":{"nodes":[{"number":119,"title":"deps: bump the cargo group across 1 directory with 3 updates","url":"https://github.com/nora-quinn/luxe-dev/pull/119","state":"CLOSED","isDraft":false,"headRefOid":"a0f2256655346be410b6303e10509a36af011880","headRepositoryOwner":{"login":"nora-quinn"},"reviewDecision":null,"commits":{"nodes":[{"commit":{"statusCheckRollup":{"contexts":{"checkRunCountsByState":[{"state":"ACTION_REQUIRED","count":0},{"state":"CANCELLED","count":0},{"state":"COMPLETED","count":0},{"state":"FAILURE","count":1},{"state":"IN_PROGRESS","count":0},{"state":"NEUTRAL","count":0},{"state":"PENDING","count":0},{"state":"QUEUED","count":0},{"state":"SKIPPED","count":0},{"state":"STALE","count":0},{"state":"STARTUP_FAILURE","count":0},{"state":"SUCCESS","count":4},{"state":"TIMED_OUT","count":0},{"state":"WAITING","count":0}],"statusContextCountsByState":[{"state":"EXPECTED","count":0},{"state":"ERROR","count":0},{"state":"FAILURE","count":0},{"state":"PENDING","count":0},{"state":"SUCCESS","count":0}]}}}}]},"reviewThreads":{"totalCount":0,"nodes":[]}}]}},"rateLimit":{"remaining":4996,"resetAt":"2026-09-24T20:18:36Z"}}}

View File

@@ -0,0 +1 @@
{"data":{"repository":{"pullRequests":{"nodes":[{"number":13340,"title":"Paginate files and commits in `gh pr view --json`","url":"https://github.com/cli/cli/pull/13340","state":"OPEN","isDraft":false,"headRefOid":"57c0c3d4b56970689ca401aecfe1a053ac705833","headRepositoryOwner":{"login":"SebTardif"},"reviewDecision":"REVIEW_REQUIRED","commits":{"nodes":[{"commit":{"statusCheckRollup":null}}]},"reviewThreads":{"totalCount":2,"nodes":[{"isResolved":false},{"isResolved":false}]}}]}},"rateLimit":{"remaining":4992,"resetAt":"2026-09-24T20:18:36Z"}}}

View File

@@ -0,0 +1 @@
{"data":{"repository":{"pullRequests":{"nodes":[{"number":139,"title":"Read any pull request in Guided Review: /diff pr","url":"https://github.com/nora-quinn/luxe-dev/pull/139","state":"OPEN","isDraft":false,"headRefOid":"152d65cfcad40bf804cb407c7bb6a14d856ed5a2","headRepositoryOwner":{"login":"nora-quinn"},"reviewDecision":null,"commits":{"nodes":[{"commit":{"statusCheckRollup":null}}]},"reviewThreads":{"totalCount":0,"nodes":[]}}]}},"rateLimit":{"remaining":4995,"resetAt":"2026-09-24T20:18:36Z"}}}

View File

@@ -0,0 +1 @@
{"data":{"repository":{"pullRequests":{"nodes":[]}},"rateLimit":{"remaining":4997,"resetAt":"2026-09-24T20:18:36Z"}}}

View File

@@ -0,0 +1 @@
{"data":{"repository":{"pullRequests":{"nodes":[{"number":138,"title":"Groundwork for pull requests: GitHub writes ask first, one forge seam, and two cleanups","url":"https://github.com/nora-quinn/luxe-dev/pull/138","state":"OPEN","isDraft":false,"headRefOid":"399286814564627352030020a163bfcbaeafe166","headRepositoryOwner":{"login":"nora-quinn"},"reviewDecision":null,"commits":{"nodes":[{"commit":{"statusCheckRollup":{"contexts":{"checkRunCountsByState":[{"state":"ACTION_REQUIRED","count":0},{"state":"CANCELLED","count":0},{"state":"COMPLETED","count":0},{"state":"FAILURE","count":0},{"state":"IN_PROGRESS","count":0},{"state":"NEUTRAL","count":0},{"state":"PENDING","count":0},{"state":"QUEUED","count":0},{"state":"SKIPPED","count":0},{"state":"STALE","count":0},{"state":"STARTUP_FAILURE","count":0},{"state":"SUCCESS","count":5},{"state":"TIMED_OUT","count":0},{"state":"WAITING","count":0}],"statusContextCountsByState":[{"state":"EXPECTED","count":0},{"state":"ERROR","count":0},{"state":"FAILURE","count":0},{"state":"PENDING","count":0},{"state":"SUCCESS","count":0}]}}}}]},"reviewThreads":{"totalCount":0,"nodes":[]}}]}},"rateLimit":{"remaining":4998,"resetAt":"2026-09-24T20:18:36Z"}}}

View File

@@ -0,0 +1 @@
{"data":{"repository":{"defaultBranchRef":{"name":"master"},"pullRequests":{"nodes":[{"number":149,"title":"Give a session a checkout of its own","url":"https://github.com/nora-quinn/luxe-dev/pull/149","state":"OPEN","isDraft":false,"headRefOid":"a701ed279ca36be0c4595d04dfc0dd5a236f1fdb","baseRefName":"fix/refresh-during-save","headRepositoryOwner":{"login":"nora-quinn"},"reviewDecision":null,"commits":{"nodes":[{"commit":{"statusCheckRollup":null}}]},"reviewThreads":{"totalCount":0,"nodes":[]}}]},"stack":{"nodes":[{"number":156,"title":"Fix someone else's pull request in a worktree: luxe --pr, and Alt+U from the review","isDraft":false,"headRefName":"feat/fix-their-pull-request","baseRefName":"feat/issue-to-pull-request","headRepositoryOwner":{"login":"nora-quinn"},"commits":{"nodes":[{"commit":{"statusCheckRollup":null}}]}},{"number":154,"title":"Text fields jump and delete by word and by line","isDraft":false,"headRefName":"polish/composer-text-navigation","baseRefName":"master","headRepositoryOwner":{"login":"nora-quinn"},"commits":{"nodes":[{"commit":{"statusCheckRollup":{"state":"SUCCESS"}}}]}},{"number":153,"title":"Take an issue to a pull request: luxe --issue, and Open pull request from the review","isDraft":false,"headRefName":"feat/issue-to-pull-request","baseRefName":"feat/session-worktrees","headRepositoryOwner":{"login":"nora-quinn"},"commits":{"nodes":[{"commit":{"statusCheckRollup":null}}]}},{"number":149,"title":"Give a session a checkout of its own","isDraft":false,"headRefName":"feat/session-worktrees","baseRefName":"fix/refresh-during-save","headRepositoryOwner":{"login":"nora-quinn"},"commits":{"nodes":[{"commit":{"statusCheckRollup":null}}]}},{"number":148,"title":"Reconcile a refresh that lands during a save","isDraft":false,"headRefName":"fix/refresh-during-save","baseRefName":"feat/pull-request-round-trip","headRepositoryOwner":{"login":"nora-quinn"},"commits":{"nodes":[{"commit":{"statusCheckRollup":null}}]}},{"number":147,"title":"Work your own pull request's review threads through, round trip","isDraft":false,"headRefName":"feat/pull-request-round-trip","baseRefName":"feat/pull-request-status","headRepositoryOwner":{"login":"nora-quinn"},"commits":{"nodes":[{"commit":{"statusCheckRollup":null}}]}},{"number":145,"title":"Keep the branch's pull request on the bar, and read why CI fails","isDraft":false,"headRefName":"feat/pull-request-status","baseRefName":"feat/pull-request-posting","headRepositoryOwner":{"login":"nora-quinn"},"commits":{"nodes":[{"commit":{"statusCheckRollup":null}}]}},{"number":143,"title":"Post a pull request's review to GitHub","isDraft":false,"headRefName":"feat/pull-request-posting","baseRefName":"feat/pull-request-threads","headRepositoryOwner":{"login":"nora-quinn"},"commits":{"nodes":[{"commit":{"statusCheckRollup":null}}]}},{"number":140,"title":"Earlier review threads on a pull request, placed on the code","isDraft":false,"headRefName":"feat/pull-request-threads","baseRefName":"feat/pull-request-review","headRepositoryOwner":{"login":"nora-quinn"},"commits":{"nodes":[{"commit":{"statusCheckRollup":null}}]}},{"number":138,"title":"Groundwork for pull requests: GitHub writes ask first, one forge seam, and two cleanups","isDraft":false,"headRefName":"feat/pull-request-groundwork","baseRefName":"master","headRepositoryOwner":{"login":"nora-quinn"},"commits":{"nodes":[{"commit":{"statusCheckRollup":{"state":"SUCCESS"}}}]}},{"number":139,"title":"Read any pull request in Guided Review: /diff pr","isDraft":false,"headRefName":"feat/pull-request-review","baseRefName":"feat/pull-request-groundwork","headRepositoryOwner":{"login":"nora-quinn"},"commits":{"nodes":[{"commit":{"statusCheckRollup":null}}]}}]}},"rateLimit":{"remaining":4996,"resetAt":"2026-09-25T16:18:15Z","cost":1}}}

View File

@@ -0,0 +1 @@
{"data":{"repository":{"defaultBranchRef":{"name":"master"},"pullRequests":{"nodes":[{"number":154,"title":"Text fields jump and delete by word and by line","url":"https://github.com/nora-quinn/luxe-dev/pull/154","state":"OPEN","isDraft":false,"headRefOid":"c96c8232da0ee74ba6a7a26aa4af77fadc992099","baseRefName":"master","headRepositoryOwner":{"login":"nora-quinn"},"reviewDecision":null,"commits":{"nodes":[{"commit":{"statusCheckRollup":{"contexts":{"checkRunCountsByState":[{"state":"ACTION_REQUIRED","count":0},{"state":"CANCELLED","count":0},{"state":"COMPLETED","count":0},{"state":"FAILURE","count":0},{"state":"IN_PROGRESS","count":0},{"state":"NEUTRAL","count":0},{"state":"PENDING","count":0},{"state":"QUEUED","count":0},{"state":"SKIPPED","count":0},{"state":"STALE","count":0},{"state":"STARTUP_FAILURE","count":0},{"state":"SUCCESS","count":5},{"state":"TIMED_OUT","count":0},{"state":"WAITING","count":0}],"statusContextCountsByState":[{"state":"EXPECTED","count":0},{"state":"ERROR","count":0},{"state":"FAILURE","count":0},{"state":"PENDING","count":0},{"state":"SUCCESS","count":0}]}}}}]},"reviewThreads":{"totalCount":0,"nodes":[]}}]},"stack":{"nodes":[{"number":156,"title":"Fix someone else's pull request in a worktree: luxe --pr, and Alt+U from the review","isDraft":false,"headRefName":"feat/fix-their-pull-request","baseRefName":"feat/issue-to-pull-request","headRepositoryOwner":{"login":"nora-quinn"},"commits":{"nodes":[{"commit":{"statusCheckRollup":null}}]}},{"number":154,"title":"Text fields jump and delete by word and by line","isDraft":false,"headRefName":"polish/composer-text-navigation","baseRefName":"master","headRepositoryOwner":{"login":"nora-quinn"},"commits":{"nodes":[{"commit":{"statusCheckRollup":{"state":"SUCCESS"}}}]}},{"number":153,"title":"Take an issue to a pull request: luxe --issue, and Open pull request from the review","isDraft":false,"headRefName":"feat/issue-to-pull-request","baseRefName":"feat/session-worktrees","headRepositoryOwner":{"login":"nora-quinn"},"commits":{"nodes":[{"commit":{"statusCheckRollup":null}}]}},{"number":149,"title":"Give a session a checkout of its own","isDraft":false,"headRefName":"feat/session-worktrees","baseRefName":"fix/refresh-during-save","headRepositoryOwner":{"login":"nora-quinn"},"commits":{"nodes":[{"commit":{"statusCheckRollup":null}}]}},{"number":148,"title":"Reconcile a refresh that lands during a save","isDraft":false,"headRefName":"fix/refresh-during-save","baseRefName":"feat/pull-request-round-trip","headRepositoryOwner":{"login":"nora-quinn"},"commits":{"nodes":[{"commit":{"statusCheckRollup":null}}]}},{"number":147,"title":"Work your own pull request's review threads through, round trip","isDraft":false,"headRefName":"feat/pull-request-round-trip","baseRefName":"feat/pull-request-status","headRepositoryOwner":{"login":"nora-quinn"},"commits":{"nodes":[{"commit":{"statusCheckRollup":null}}]}},{"number":145,"title":"Keep the branch's pull request on the bar, and read why CI fails","isDraft":false,"headRefName":"feat/pull-request-status","baseRefName":"feat/pull-request-posting","headRepositoryOwner":{"login":"nora-quinn"},"commits":{"nodes":[{"commit":{"statusCheckRollup":null}}]}},{"number":143,"title":"Post a pull request's review to GitHub","isDraft":false,"headRefName":"feat/pull-request-posting","baseRefName":"feat/pull-request-threads","headRepositoryOwner":{"login":"nora-quinn"},"commits":{"nodes":[{"commit":{"statusCheckRollup":null}}]}},{"number":140,"title":"Earlier review threads on a pull request, placed on the code","isDraft":false,"headRefName":"feat/pull-request-threads","baseRefName":"feat/pull-request-review","headRepositoryOwner":{"login":"nora-quinn"},"commits":{"nodes":[{"commit":{"statusCheckRollup":null}}]}},{"number":138,"title":"Groundwork for pull requests: GitHub writes ask first, one forge seam, and two cleanups","isDraft":false,"headRefName":"feat/pull-request-groundwork","baseRefName":"master","headRepositoryOwner":{"login":"nora-quinn"},"commits":{"nodes":[{"commit":{"statusCheckRollup":{"state":"SUCCESS"}}}]}},{"number":139,"title":"Read any pull request in Guided Review: /diff pr","isDraft":false,"headRefName":"feat/pull-request-review","baseRefName":"feat/pull-request-groundwork","headRepositoryOwner":{"login":"nora-quinn"},"commits":{"nodes":[{"commit":{"statusCheckRollup":null}}]}}]}},"rateLimit":{"remaining":4995,"resetAt":"2026-09-25T16:18:15Z","cost":1}}}

View File

@@ -0,0 +1,5 @@
{"app":"github-actions","conclusion":"success","details_url":"https://github.com/nora-quinn/luxe-dev/actions/runs/35801682338/job/106993218172","html_url":"https://github.com/nora-quinn/luxe-dev/actions/runs/35801682338/job/106993218172","name":"web build","status":"completed","summary":null,"title":null}
{"app":"github-actions","conclusion":"failure","details_url":"https://github.com/nora-quinn/luxe-dev/actions/runs/35801682338/job/106993218139","html_url":"https://github.com/nora-quinn/luxe-dev/actions/runs/35801682338/job/106993218139","name":"build · clippy · test (macos-latest)","status":"completed","summary":null,"title":null}
{"app":"github-actions","conclusion":"failure","details_url":"https://github.com/nora-quinn/luxe-dev/actions/runs/35801682338/job/106993218126","html_url":"https://github.com/nora-quinn/luxe-dev/actions/runs/35801682338/job/106993218126","name":"build · test · clippy · fmt","status":"completed","summary":null,"title":null}
{"app":"github-actions","conclusion":"success","details_url":"https://github.com/nora-quinn/luxe-dev/actions/runs/35801682338/job/106993218113","html_url":"https://github.com/nora-quinn/luxe-dev/actions/runs/35801682338/job/106993218113","name":"cargo-deny","status":"completed","summary":null,"title":null}
{"app":"github-actions","conclusion":"failure","details_url":"https://github.com/nora-quinn/luxe-dev/actions/runs/35801682338/job/106993217890","html_url":"https://github.com/nora-quinn/luxe-dev/actions/runs/35801682338/job/106993217890","name":"build · clippy · test (windows-latest)","status":"completed","summary":null,"title":null}

View File

@@ -0,0 +1,13 @@
{"context":"buildbot/ARM64 MacOS M1 NoGIL 3.x","description":"Build done.","state":"success","target_url":"https://buildbot.python.org/#/builders/1270/builds/8723"}
{"context":"buildbot/x86 Debian Installed with X 3.x","description":"Build done.","state":"success","target_url":"https://buildbot.python.org/#/builders/1244/builds/9703"}
{"context":"buildbot/aarch64 Ubuntu Oddballs 3.x","description":"Build done.","state":"success","target_url":"https://buildbot.python.org/#/builders/1868/builds/2298"}
{"context":"buildbot/AMD64 CentOS9 NoGIL 3.x","description":"Build done.","state":"success","target_url":"https://buildbot.python.org/#/builders/1609/builds/7154"}
{"context":"buildbot/AMD64 Alpine Linux 3.x","description":"Build done.","state":"success","target_url":"https://buildbot.python.org/#/builders/301/builds/16364"}
{"context":"buildbot/x86 Debian Non-Debug with X 3.x","description":"Build done.","state":"success","target_url":"https://buildbot.python.org/#/builders/1245/builds/9595"}
{"context":"buildbot/ARM Raspbian 3.x","description":"Build done.","state":"success","target_url":"https://buildbot.python.org/#/builders/424/builds/15113"}
{"context":"buildbot/wasm32-wasi 3.x","description":"Build done.","state":"success","target_url":"https://buildbot.python.org/#/builders/1046/builds/13190"}
{"context":"buildbot/AMD64 Alpine Linux NoGIL 3.x","description":"Build done.","state":"success","target_url":"https://buildbot.python.org/#/builders/1819/builds/3211"}
{"context":"buildbot/AMD64 Windows PGO NoGIL 3.x","description":"Build done.","state":"success","target_url":"https://buildbot.python.org/#/builders/1622/builds/5722"}
{"context":"Azure Pipelines CI","description":"#20260924.53 failed","state":"failure","target_url":"https://dev.azure.com/Python/8e426817-76c0-4b99-ba9e-a48a1e4bd5db/_build/results?buildId=175169"}
{"context":"buildbot/AMD64 Debian root 3.x","description":"Build done.","state":"success","target_url":"https://buildbot.python.org/#/builders/345/builds/15495"}
{"context":"buildbot/WASM Emscripten 3.x","description":"Build done.","state":"success","target_url":"https://buildbot.python.org/#/builders/1810/builds/3947"}

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1 @@
{"data":{"repository":{"nameWithOwner":"cli/cli","issue":{"number":14015,"title":"Support Discussion Templates","body":"### Describe the feature or problem you’d like to solve\n\nIn a similar vein to #5865, we should support Discussion Templates in the newly added `gh discussion create` subcommand.\n\nThis would make it easier to work with repositories that have strict templates, as without it, the `gh discussion create` subcommand only provides free-text entry, which breaks adherence to the templates.\n\n### Proposed solution\n\nUsers who interact with projects with Discussion Templates will receive a fully guided experience to filling in their Discussion.\n\n### Additional context\n\nI've previously built this in https://github.com/jamietanna/gh-discussion (which now is being shadowed by the GitHub CLI's upstream support for `gh discussion`.\n\nA [screen recording of my extension](https://www.jvt.me/posts/2025/09/22/gh-discussions/) shows an interactive example of it working.\n\nRaised as a follow-up to https://github.com/cli/cli/issues/9644","url":"https://github.com/cli/cli/issues/14015","state":"OPEN","updatedAt":"2026-09-30T13:26:35Z","author":{"__typename":"User","login":"jamietanna"},"labels":{"nodes":[{"name":"enhancement","color":"0dd8ac"},{"name":"needs-investigation","color":"d45bd8"},{"name":"stale","color":"333333"},{"name":"gh-discussion","color":"7bb1ad"}]},"assignees":{"nodes":[]},"milestone":null,"closedByPullRequestsReferences":{"nodes":[{"number":14017,"title":"feat(discussion): add support for Discussion Templates","state":"OPEN","isDraft":true,"author":{"login":"jamietanna"}}]},"comments":{"totalCount":5}}},"rateLimit":{"cost":1,"remaining":4979}}}

View File

@@ -0,0 +1 @@
{"data":{"repository":{"nameWithOwner":"rust-lang/rust","issue":{"number":163381,"title":"Tracking issue for release notes of #163366: Stabilize SyncView","body":"\nThis issue tracks the release notes text for #163366.\n\ncc @tisonkun, @clarfonthey -- original issue/PR authors and assignees for drafting text\n\nSee the forge.rust-lang.org chapter about [release notes](https://forge.rust-lang.org/release/release-notes.html#preparing-release-notes) for an overview of how the release team makes use of these tracking issues.\n\n### Release notes text\n\nThis section should be edited to specify the correct category(s) for the change, with succinct description(s) of what changed. Some things worth considering:\n- Does this need an additional compat notes section?\n- Was this a libs stabilization that should have additional headers to list new APIs under `Stabilized APIs` and `Const Stabilized APIs`?\n\n\n````markdown\n# Stabilized APIs\n- [`std::sync::SyncView`](https://doc.rust-lang.org/stable/std/sync/struct.SyncView.html)\n````\n\n> [!TIP]\n> Use the [previous releases](https://doc.rust-lang.org/nightly/releases.html) for inspiration on how to write the release notes text and which categories to pick.\n\n### Release blog section\n\nIf this change is notable enough for inclusion in the blog post then this section should be edited to contain a draft for the blog post. *Otherwise leave it empty.*\n\n\n````markdown\n````\n\n> [!NOTE]\n>\n> If a blog post section is required the `release-blog-post` label should be added (`@rustbot label +release-blog-post`) to this issue as otherwise it may be missed by the release team.\n","url":"https://github.com/rust-lang/rust/issues/163381","state":"OPEN","updatedAt":"2026-10-01T23:10:02Z","author":{"__typename":"User","login":"rustbot"},"labels":{"nodes":[{"name":"relnotes","color":"fad8c7"},{"name":"T-libs","color":"bfd4f2"},{"name":"relnotes-tracking-issue","color":"fad8c7"},{"name":"release-blog-post","color":"fad8c7"},{"name":"relnotes-needs-review","color":"fad8c7"}]},"assignees":{"nodes":[{"login":"clarfonthey"}]},"milestone":{"title":"1.101.0"},"closedByPullRequestsReferences":{"nodes":[]},"comments":{"totalCount":0}}},"rateLimit":{"cost":1,"remaining":4974}}}

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,61 @@
build · test · clippy · fmt Clippy (deny warnings) 2026-09-23T00:21:52.1237712Z ##[group]Run cargo clippy --workspace --all-targets --locked -- -D warnings
build · test · clippy · fmt Clippy (deny warnings) 2026-09-23T00:21:52.1238219Z ^[[36;1mcargo clippy --workspace --all-targets --locked -- -D warnings^[[0m
build · test · clippy · fmt Clippy (deny warnings) 2026-09-23T00:21:52.1273268Z shell: /usr/bin/bash -e {0}
build · test · clippy · fmt Clippy (deny warnings) 2026-09-23T00:21:52.1273424Z env:
build · test · clippy · fmt Clippy (deny warnings) 2026-09-23T00:21:52.1273537Z CARGO_TERM_COLOR: always
build · test · clippy · fmt Clippy (deny warnings) 2026-09-23T00:21:52.1273671Z CARGO_NET_RETRY: 3
build · test · clippy · fmt Clippy (deny warnings) 2026-09-23T00:21:52.1273809Z CARGO_PROFILE_DEV_DEBUG: line-tables-only
build · test · clippy · fmt Clippy (deny warnings) 2026-09-23T00:21:52.1273993Z CARGO_PROFILE_TEST_DEBUG: line-tables-only
build · test · clippy · fmt Clippy (deny warnings) 2026-09-23T00:21:52.1274151Z CARGO_HOME: /home/runner/.cargo
build · test · clippy · fmt Clippy (deny warnings) 2026-09-23T00:21:52.1274301Z CARGO_INCREMENTAL: 0
build · test · clippy · fmt Clippy (deny warnings) 2026-09-23T00:21:52.1274421Z CACHE_ON_FAILURE: false
build · test · clippy · fmt Clippy (deny warnings) 2026-09-23T00:21:52.1274547Z ##[endgroup]
build · test · clippy · fmt Clippy (deny warnings) 2026-09-23T00:21:52.8991052Z ^[[1m^[[92m Updating^[[0m crates.io index
build · test · clippy · fmt Clippy (deny warnings) 2026-09-23T00:21:53.7728577Z ^[[1m^[[92m Downloading^[[0m crates ...
build · test · clippy · fmt Clippy (deny warnings) 2026-09-23T00:21:54.6356120Z ^[[1m^[[92m Downloaded^[[0m clap_derive v4.6.7
build · test · clippy · fmt Clippy (deny warnings) 2026-09-23T00:21:54.6371332Z ^[[1m^[[92m Downloaded^[[0m clap v4.6.7
build · test · clippy · fmt Clippy (deny warnings) 2026-09-23T00:21:54.6446961Z ^[[1m^[[92m Downloaded^[[0m clap_builder v4.6.7
build · test · clippy · fmt Clippy (deny warnings) 2026-09-23T00:21:54.6494519Z ^[[1m^[[92m Downloaded^[[0m dom_smoothie v0.18.1
build · test · clippy · fmt Clippy (deny warnings) 2026-09-23T00:21:54.6514279Z ^[[1m^[[92m Downloaded^[[0m flate2 v1.1.10
build · test · clippy · fmt Clippy (deny warnings) 2026-09-23T00:21:54.6549748Z ^[[1m^[[92m Downloaded^[[0m miniz_oxide v0.9.1
build · test · clippy · fmt Clippy (deny warnings) 2026-09-23T00:21:54.6567677Z ^[[1m^[[92m Downloaded^[[0m uuid v1.26.1
build · test · clippy · fmt Clippy (deny warnings) 2026-09-23T00:21:54.6589502Z ^[[1m^[[92m Downloaded^[[0m zlib-rs v0.6.8
build · test · clippy · fmt Clippy (deny warnings) 2026-09-23T00:21:54.8890334Z ^[[1m^[[92m Compiling^[[0m serde_json v1.0.151
build · test · clippy · fmt Clippy (deny warnings) 2026-09-23T00:21:54.8933397Z ^[[1m^[[92m Checking^[[0m uuid v1.26.1
build · test · clippy · fmt Clippy (deny warnings) 2026-09-23T00:21:57.3749054Z ^[[1m^[[92m Checking^[[0m miniz_oxide v0.9.1
build · test · clippy · fmt Clippy (deny warnings) 2026-09-23T00:21:57.4442376Z ^[[1m^[[92m Checking^[[0m luxe-core v0.1.0 (/home/runner/work/luxe-dev/luxe-dev/crates/luxe-core)
build · test · clippy · fmt Clippy (deny warnings) 2026-09-23T00:21:57.5906933Z ^[[1m^[[92m Checking^[[0m flate2 v1.1.10
build · test · clippy · fmt Clippy (deny warnings) 2026-09-23T00:21:57.7572311Z ^[[1m^[[92m Checking^[[0m png v0.18.1
build · test · clippy · fmt Clippy (deny warnings) 2026-09-23T00:21:58.2207526Z ^[[1m^[[92m Checking^[[0m image v0.25.10
build · test · clippy · fmt Clippy (deny warnings) 2026-09-23T00:21:59.2831850Z ^[[1m^[[92m Checking^[[0m compression-codecs v0.4.38
build · test · clippy · fmt Clippy (deny warnings) 2026-09-23T00:21:59.3583644Z ^[[1m^[[92m Checking^[[0m syntect v5.3.0
build · test · clippy · fmt Clippy (deny warnings) 2026-09-23T00:21:59.9915550Z ^[[1m^[[92m Checking^[[0m arboard v3.6.1
build · test · clippy · fmt Clippy (deny warnings) 2026-09-23T00:22:00.1382015Z ^[[1m^[[92m Checking^[[0m async-compression v0.4.42
build · test · clippy · fmt Clippy (deny warnings) 2026-09-23T00:22:00.3048443Z ^[[1m^[[92m Checking^[[0m tower-http v0.6.11
build · test · clippy · fmt Clippy (deny warnings) 2026-09-23T00:22:00.4773065Z ^[[1m^[[92m Checking^[[0m reqwest v0.12.28
build · test · clippy · fmt Clippy (deny warnings) 2026-09-23T00:22:02.3302231Z ^[[1m^[[92m Compiling^[[0m tree-sitter v0.26.13
build · test · clippy · fmt Clippy (deny warnings) 2026-09-23T00:22:03.9306449Z ^[[1m^[[92m Checking^[[0m dom_smoothie v0.18.1
build · test · clippy · fmt Clippy (deny warnings) 2026-09-23T00:22:04.1531944Z ^[[1m^[[92m Compiling^[[0m tree-sitter-typescript v0.23.2
build · test · clippy · fmt Clippy (deny warnings) 2026-09-23T00:22:05.8653516Z ^[[1m^[[92m Checking^[[0m luxe-tui v0.1.0 (/home/runner/work/luxe-dev/luxe-dev/crates/luxe-tui)
build · test · clippy · fmt Clippy (deny warnings) 2026-09-23T00:22:07.3602389Z ^[[1m^[[92m Checking^[[0m luxe-tools v0.1.0 (/home/runner/work/luxe-dev/luxe-dev/crates/luxe-tools)
build · test · clippy · fmt Clippy (deny warnings) 2026-09-23T00:22:08.7953233Z ^[[1m^[[92m Checking^[[0m luxe-lsp v0.1.0 (/home/runner/work/luxe-dev/luxe-dev/crates/luxe-lsp)
build · test · clippy · fmt Clippy (deny warnings) 2026-09-23T00:22:09.3956294Z ^[[1m^[[92m Checking^[[0m luxe-providers v0.1.0 (/home/runner/work/luxe-dev/luxe-dev/crates/luxe-providers)
build · test · clippy · fmt Clippy (deny warnings) 2026-09-23T00:22:09.7167169Z ^[[1m^[[91merror[E0425]^[[0m^[[1m: cannot find function `getrandom` in crate `getrandom`^[[0m
build · test · clippy · fmt Clippy (deny warnings) 2026-09-23T00:22:09.7191569Z ^[[1m^[[94m--> ^[[0mcrates/luxe-providers/src/auth/oauth.rs:85:16
build · test · clippy · fmt Clippy (deny warnings) 2026-09-23T00:22:09.7192240Z ^[[1m^[[94m|^[[0m
build · test · clippy · fmt Clippy (deny warnings) 2026-09-23T00:22:09.7216955Z ^[[1m^[[94m85^[[0m ^[[1m^[[94m|^[[0m getrandom::getrandom(&mut buffer).expect("OS randomness unavailable");
build · test · clippy · fmt Clippy (deny warnings) 2026-09-23T00:22:09.7241197Z ^[[1m^[[94m|^[[0m ^[[1m^[[91m^^^^^^^^^^[[0m ^[[1m^[[91mnot found in `getrandom`^[[0m
build · test · clippy · fmt Clippy (deny warnings) 2026-09-23T00:22:09.7241620Z
build · test · clippy · fmt Clippy (deny warnings) 2026-09-23T00:22:10.1612206Z ^[[1m^[[92m Checking^[[0m luxe-dap v0.1.0 (/home/runner/work/luxe-dev/luxe-dev/crates/luxe-dap)
build · test · clippy · fmt Clippy (deny warnings) 2026-09-23T00:22:10.6962191Z ^[[1m^[[92m Checking^[[0m luxe-mcp v0.1.0 (/home/runner/work/luxe-dev/luxe-dev/crates/luxe-mcp)
build · test · clippy · fmt Clippy (deny warnings) 2026-09-23T00:22:10.7831959Z ^[[1m^[[91merror[E0425]^[[0m^[[1m: cannot find function `getrandom` in crate `getrandom`^[[0m
build · test · clippy · fmt Clippy (deny warnings) 2026-09-23T00:22:10.7871280Z ^[[1m^[[94m--> ^[[0mcrates/luxe-mcp/src/oauth.rs:444:16
build · test · clippy · fmt Clippy (deny warnings) 2026-09-23T00:22:10.7874093Z ^[[1m^[[94m|^[[0m
build · test · clippy · fmt Clippy (deny warnings) 2026-09-23T00:22:10.7891512Z ^[[1m^[[94m444^[[0m ^[[1m^[[94m|^[[0m getrandom::getrandom(&mut bytes).expect("OS randomness unavailable");
build · test · clippy · fmt Clippy (deny warnings) 2026-09-23T00:22:10.7911112Z ^[[1m^[[94m|^[[0m ^[[1m^[[91m^^^^^^^^^^[[0m ^[[1m^[[91mnot found in `getrandom`^[[0m
build · test · clippy · fmt Clippy (deny warnings) 2026-09-23T00:22:10.7911357Z
build · test · clippy · fmt Clippy (deny warnings) 2026-09-23T00:22:11.4452182Z ^[[1mFor more information about this error, try `rustc --explain E0425`.^[[0m
build · test · clippy · fmt Clippy (deny warnings) 2026-09-23T00:22:11.5096658Z ^[[1m^[[91merror^[[0m: could not compile `luxe-mcp` (lib) due to 1 previous error
build · test · clippy · fmt Clippy (deny warnings) 2026-09-23T00:22:11.5103967Z ^[[1m^[[33mwarning^[[0m: build failed, waiting for other jobs to finish...
build · test · clippy · fmt Clippy (deny warnings) 2026-09-23T00:22:11.5111432Z ^[[1m^[[91merror^[[0m: could not compile `luxe-providers` (lib) due to 1 previous error
build · test · clippy · fmt Clippy (deny warnings) 2026-09-23T00:22:11.5453006Z ##[error]Process completed with exit code 101.

View File

@@ -0,0 +1 @@
{"data":{"repository":{"pullRequest":{"timelineItems":{"nodes":[]}},"merged":{"nodes":[]}}}}

View File

@@ -0,0 +1 @@
{"data":{"repository":{"pullRequest":{"timelineItems":{"nodes":[]}},"merged":{"nodes":[{"number":158,"headRefOid":"e934880d96cdfd85a9b9771a086c152d84ab142f","baseRefName":"scratch/stack-trunk"}]}}}}

View File

@@ -0,0 +1 @@
{"data":{"disablePullRequestAutoMerge":{"pullRequest":{"autoMergeRequest":null}}}}

View File

@@ -0,0 +1 @@
{"data":{"enablePullRequestAutoMerge":{"pullRequest":{"autoMergeRequest":{"mergeMethod":"SQUASH"}}}}}

View File

@@ -0,0 +1 @@
{"data":{"disablePullRequestAutoMerge":null},"errors":[{"type":"FORBIDDEN","path":["disablePullRequestAutoMerge"],"locations":[{"line":1,"column":19}],"message":"nora-quinn does not have the correct permissions to execute `DisablePullRequestAutoMerge`"}]}

View File

@@ -0,0 +1 @@
{"data":{"enablePullRequestAutoMerge":null},"errors":[{"type":"UNPROCESSABLE","path":["enablePullRequestAutoMerge"],"locations":[{"line":1,"column":70}],"message":"Failed to add PR #1: expected head oid does not match the current head oid"}]}

View File

@@ -0,0 +1 @@
{"html_url":"https://github.com/nora-quinn/luxe-dev/pull/169#issuecomment-5840873033"}

View File

@@ -0,0 +1,2 @@
{"filename":"rustfmt.toml","patch":"@@ -1,4 +1,4 @@\n-edition = \"2021\"\n+# rustfmt configuration (scratch edit, reverted with the pull request)\n use_small_heuristics = \"Max\"\n max_width = 100\n use_try_shorthand = true","previous_filename":null,"status":"modified"}
{"filename":"scratch-review-fixture.txt","patch":"@@ -0,0 +1,8 @@\n+Scratch file for capturing GitHub review responses.\n+It is deleted with its pull request.\n+\n+line four\n+line five\n+line six\n+line seven\n+line eight","previous_filename":null,"status":"added"}

View File

@@ -0,0 +1 @@
{"data":{"repository":{"viewerPermission":"READ","defaultBranchRef":{"name":"trunk"},"pullRequest":{"headRefName":"remove-claude-md","isCrossRepository":true,"maintainerCanModify":true,"headRepositoryOwner":{"login":"jarrensj"},"headRepository":{"name":"gh-cli","viewerPermission":"READ"}}}}}

View File

@@ -0,0 +1 @@
{"data":{"repository":{"viewerPermission":"READ","defaultBranchRef":{"name":"trunk"},"pullRequest":{"headRefName":"trunk","isCrossRepository":true,"maintainerCanModify":false,"headRepositoryOwner":{"login":"HIHACK1911"},"headRepository":{"name":"cli-go","viewerPermission":"READ"}}}}}

View File

@@ -0,0 +1 @@
{"data":{"repository":{"viewerPermission":"READ","defaultBranchRef":{"name":"trunk"},"pullRequest":{"headRefName":"patch-1","isCrossRepository":true,"maintainerCanModify":false,"headRepositoryOwner":{"login":"DynamoIVII"},"headRepository":{"name":"cli","viewerPermission":"READ"}}}}}

View File

@@ -0,0 +1 @@
{"data":{"repository":{"viewerPermission":"ADMIN","defaultBranchRef":{"name":"master"},"pullRequest":{"headRefName":"feat/issue-to-pull-request","isCrossRepository":false,"maintainerCanModify":false,"headRepositoryOwner":{"login":"nora-quinn"},"headRepository":{"name":"luxe-dev","viewerPermission":"ADMIN"}}}}}

View File

@@ -0,0 +1 @@
{"sha":"abce6b1396d97556c3a8f0beafbb681b5963d714","merged":true,"message":"Pull Request successfully merged"}

View File

@@ -0,0 +1 @@
{"message":"Head branch was modified. Review and try the merge again.","documentation_url":"https://docs.github.com/rest/pulls/pulls#merge-a-pull-request","status":"409"}

View File

@@ -0,0 +1 @@
{"sha":"abce6b1396d97556c3a8f0beafbb681b5963d714","merged":true,"message":"Pull Request successfully merged"}

View File

@@ -0,0 +1 @@
{"html_url":"https://github.com/nora-quinn/luxe-dev/pull/150","number":150}

View File

@@ -0,0 +1 @@
{"message":"Validation Failed","errors":[{"resource":"PullRequest","code":"custom","message":"A pull request already exists for nora-quinn:scratch/open-pr-fixture."}],"documentation_url":"https://docs.github.com/rest/pulls/pulls#create-a-pull-request","status":"422"}

View File

@@ -0,0 +1 @@
{"message":"Validation Failed","errors":[{"resource":"PullRequest","code":"custom","message":"No commits between master and master"}],"documentation_url":"https://docs.github.com/rest/pulls/pulls#create-a-pull-request","status":"422"}

View File

@@ -0,0 +1 @@
{"data":{"repository":{"nameWithOwner":"nora-quinn/luxe-scratch-automerge","viewerPermission":"ADMIN","mergeCommitAllowed":true,"squashMergeAllowed":true,"rebaseMergeAllowed":true,"viewerDefaultMergeMethod":"MERGE","deleteBranchOnMerge":false,"pullRequest":{"id":"PR_kwDOU5qvE88AAAABGZIsWQ","number":1,"viewerCanEnableAutoMerge":true,"viewerCanDisableAutoMerge":false,"autoMergeRequest":null,"title":"Add notes","body":"Scratch pull request for capturing auto-merge.","url":"https://github.com/nora-quinn/luxe-scratch-automerge/pull/1","state":"OPEN","isDraft":false,"baseRefName":"main","headRefName":"scratch/change","headRefOid":"55f2b9b2710b981e905bcc64ec50632aa99c0a5e","additions":1,"deletions":0,"changedFiles":1,"updatedAt":"2026-10-03T04:13:55Z","mergeStateStatus":"BLOCKED","mergeable":"MERGEABLE","reviewDecision":null,"viewerDidAuthor":true,"isCrossRepository":false,"maintainerCanModify":false,"headRepository":{"viewerPermission":"ADMIN"},"author":{"__typename":"User","login":"nora-quinn"},"labels":{"nodes":[]},"commitCount":{"totalCount":1},"head":{"nodes":[{"commit":{"statusCheckRollup":null}}]},"reviewRequests":{"nodes":[]},"latestOpinionatedReviews":{"nodes":[]},"latestReviews":{"nodes":[]},"reviewThreads":{"totalCount":0,"nodes":[]},"comments":{"totalCount":0},"reviews":{"totalCount":0}}},"rateLimit":{"cost":1,"remaining":4987,"resetAt":"2026-10-03T05:11:04Z"}}}

View File

@@ -0,0 +1 @@
{"data":{"repository":{"nameWithOwner":"nora-quinn/luxe-scratch-automerge","viewerPermission":"ADMIN","mergeCommitAllowed":true,"squashMergeAllowed":true,"rebaseMergeAllowed":true,"viewerDefaultMergeMethod":"MERGE","deleteBranchOnMerge":false,"pullRequest":{"id":"PR_kwDOU5qvE88AAAABGZIsWQ","number":1,"viewerCanEnableAutoMerge":false,"viewerCanDisableAutoMerge":true,"autoMergeRequest":{"mergeMethod":"SQUASH"},"title":"Add notes","body":"Scratch pull request for capturing auto-merge.","url":"https://github.com/nora-quinn/luxe-scratch-automerge/pull/1","state":"OPEN","isDraft":false,"baseRefName":"main","headRefName":"scratch/change","headRefOid":"55f2b9b2710b981e905bcc64ec50632aa99c0a5e","additions":1,"deletions":0,"changedFiles":1,"updatedAt":"2026-10-03T04:13:55Z","mergeStateStatus":"BLOCKED","mergeable":"MERGEABLE","reviewDecision":null,"viewerDidAuthor":true,"isCrossRepository":false,"maintainerCanModify":false,"headRepository":{"viewerPermission":"ADMIN"},"author":{"__typename":"User","login":"nora-quinn"},"labels":{"nodes":[]},"commitCount":{"totalCount":1},"head":{"nodes":[{"commit":{"statusCheckRollup":null}}]},"reviewRequests":{"nodes":[]},"latestOpinionatedReviews":{"nodes":[]},"latestReviews":{"nodes":[]},"reviewThreads":{"totalCount":0,"nodes":[]},"comments":{"totalCount":0},"reviews":{"totalCount":0}}},"rateLimit":{"cost":1,"remaining":4985,"resetAt":"2026-10-03T05:11:04Z"}}}

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1 @@
{"data":{"repository":{"nameWithOwner":"cli/cli","viewerPermission":"READ","mergeCommitAllowed":true,"squashMergeAllowed":true,"rebaseMergeAllowed":true,"viewerDefaultMergeMethod":"MERGE","deleteBranchOnMerge":true,"pullRequest":{"id":"PR_kwDODKw3uc7mrzaT","number":13665,"viewerCanEnableAutoMerge":false,"viewerCanDisableAutoMerge":false,"autoMergeRequest":null,"title":"Update build and release workflow to use Actions network firewall private preview","body":"We're doing a private preview of the Actions network firewall that logs all outbound network activity and uploads it as an Actions workflow artifact to the job. See for example https://github.com/steiza/sigstore-go/actions/runs/27418947268 (scroll down to \"Artifacts\").\r\n\r\nI added github.com/cli to the feature flag so that it can use the private preview. If there are any issues, simply revert the `runs-on:` back to `ubuntu-latest`.","url":"https://github.com/cli/cli/pull/13665","state":"OPEN","isDraft":false,"baseRefName":"trunk","headRefName":"use-actions-firewall","headRefOid":"1f937060b1954355c563203902e0fdaa3d07356b","additions":6,"deletions":6,"changedFiles":2,"updatedAt":"2026-09-03T15:21:05Z","mergeStateStatus":"BLOCKED","mergeable":"MERGEABLE","reviewDecision":"APPROVED","viewerDidAuthor":false,"isCrossRepository":false,"maintainerCanModify":false,"headRepository":{"viewerPermission":"READ"},"author":{"__typename":"User","login":"steiza"},"labels":{"nodes":[]},"commitCount":{"totalCount":1},"head":{"nodes":[{"commit":{"statusCheckRollup":{"contexts":{"checkRunCountsByState":[{"state":"ACTION_REQUIRED","count":0},{"state":"CANCELLED","count":0},{"state":"COMPLETED","count":0},{"state":"FAILURE","count":0},{"state":"IN_PROGRESS","count":0},{"state":"NEUTRAL","count":0},{"state":"PENDING","count":0},{"state":"QUEUED","count":0},{"state":"SKIPPED","count":6},{"state":"STALE","count":0},{"state":"STARTUP_FAILURE","count":0},{"state":"SUCCESS","count":10},{"state":"TIMED_OUT","count":0},{"state":"WAITING","count":0}],"statusContextCountsByState":[{"state":"EXPECTED","count":0},{"state":"ERROR","count":0},{"state":"FAILURE","count":0},{"state":"PENDING","count":0},{"state":"SUCCESS","count":0}],"nodes":[{"__typename":"CheckRun","name":"CodeQL-Build (go)","conclusion":"SUCCESS","status":"COMPLETED","isRequired":false},{"__typename":"CheckRun","name":"label-external / label_issues","conclusion":"SUCCESS","status":"COMPLETED","isRequired":false},{"__typename":"CheckRun","name":"build (ubuntu-24.04-firewall)","conclusion":"SUCCESS","status":"COMPLETED","isRequired":false},{"__typename":"CheckRun","name":"CodeQL-Build (actions)","conclusion":"SUCCESS","status":"COMPLETED","isRequired":false},{"__typename":"CheckRun","name":"build (windows-latest)","conclusion":"SUCCESS","status":"COMPLETED","isRequired":true},{"__typename":"CheckRun","name":"build (macos-latest)","conclusion":"SUCCESS","status":"COMPLETED","isRequired":true},{"__typename":"CheckRun","name":"close-from-default-branch / close-from-default-branch","conclusion":"SKIPPED","status":"COMPLETED","isRequired":false},{"__typename":"CheckRun","name":"integration-tests (ubuntu-24.04-firewall)","conclusion":"SUCCESS","status":"COMPLETED","isRequired":false},{"__typename":"CheckRun","name":"integration-tests (windows-latest)","conclusion":"SUCCESS","status":"COMPLETED","isRequired":false},{"__typename":"CheckRun","name":"integration-tests (macos-latest)","conclusion":"SUCCESS","status":"COMPLETED","isRequired":false},{"__typename":"CheckRun","name":"check-requirements / check-requirements","conclusion":"SKIPPED","status":"COMPLETED","isRequired":false},{"__typename":"CheckRun","name":"check-requirements / close-unmet-requirements","conclusion":"SKIPPED","status":"COMPLETED","isRequired":false},{"__typename":"CheckRun","name":"close-unmet-requirements","conclusion":"SKIPPED","status":"COMPLETED","isRequired":false},{"__typename":"CheckRun","name":"close-no-help-wanted","conclusion":"SKIPPED","status":"COMPLETED","isRequired":false},{"__typename":"CheckRun","name":"ready-for-review","conclusion":"SKIPPED","status":"COMPLETED","isRequired":false},{"__typename":"CheckRun","name":"CodeQL","conclusion":"SUCCESS","status":"COMPLETED","isRequired":false}]}}}}]},"reviewRequests":{"nodes":[]},"latestOpinionatedReviews":{"nodes":[{"author":{"__typename":"User","login":"BagToad"},"state":"APPROVED","submittedAt":"2026-06-15T18:54:17Z"}]},"latestReviews":{"nodes":[{"author":{"__typename":"Bot","login":"copilot-pull-request-reviewer"},"state":"COMMENTED","submittedAt":"2026-06-15T18:51:50Z"},{"author":{"__typename":"User","login":"BagToad"},"state":"APPROVED","submittedAt":"2026-06-15T18:54:17Z"}]},"reviewThreads":{"totalCount":0,"nodes":[]},"comments":{"totalCount":1},"reviews":{"totalCount":2}}},"rateLimit":{"cost":1,"remaining":4992,"resetAt":"2026-10-03T00:52:19Z"}}}

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1 @@
{"data":{"repository":{"nameWithOwner":"cli/cli","viewerPermission":"READ","mergeCommitAllowed":true,"squashMergeAllowed":true,"rebaseMergeAllowed":true,"viewerDefaultMergeMethod":"MERGE","deleteBranchOnMerge":true,"pullRequest":{"id":"PR_kwDODKw3uc72-fmP","number":13982,"viewerCanEnableAutoMerge":false,"viewerCanDisableAutoMerge":false,"autoMergeRequest":null,"title":"Add --latest-pre-release and --pin flags to gh extension upgrade","body":"Add some gh extension upgrade support for prereleases:\r\n- `--latest-pre-release` to make it easier to keep abreast of extension development\r\n- `--pin` to work with an explicit version, prerelease or otherwise, of an extension\r\n\r\nFixes https://github.com/cli/cli/issues/13968","url":"https://github.com/cli/cli/pull/13982","state":"OPEN","isDraft":false,"baseRefName":"trunk","headRefName":"o1/add-latest-pre-release-and-pin-flags-to-gh-extension-upgrade/nysoxynolqlo","headRefOid":"a560bea91b8cd58b3c0d78e5db98c7fdc8e5036b","additions":874,"deletions":80,"changedFiles":9,"updatedAt":"2026-08-03T15:58:40Z","mergeStateStatus":"DIRTY","mergeable":"CONFLICTING","reviewDecision":"CHANGES_REQUESTED","viewerDidAuthor":false,"isCrossRepository":true,"maintainerCanModify":true,"headRepository":{"viewerPermission":"READ"},"author":{"__typename":"User","login":"offbyone"},"labels":{"nodes":[]},"commitCount":{"totalCount":1},"head":{"nodes":[{"commit":{"statusCheckRollup":null}}]},"reviewRequests":{"nodes":[]},"latestOpinionatedReviews":{"nodes":[{"author":{"__typename":"User","login":"BagToad"},"state":"CHANGES_REQUESTED","submittedAt":"2026-07-28T05:42:11Z"}]},"latestReviews":{"nodes":[{"author":{"__typename":"Bot","login":"copilot-pull-request-reviewer"},"state":"COMMENTED","submittedAt":"2026-07-27T15:11:14Z"},{"author":{"__typename":"User","login":"BagToad"},"state":"CHANGES_REQUESTED","submittedAt":"2026-07-28T05:42:11Z"}]},"reviewThreads":{"totalCount":14,"nodes":[{"isResolved":false},{"isResolved":false},{"isResolved":false},{"isResolved":false},{"isResolved":false},{"isResolved":false},{"isResolved":false},{"isResolved":false},{"isResolved":false},{"isResolved":false},{"isResolved":false},{"isResolved":false},{"isResolved":false},{"isResolved":false}]},"comments":{"totalCount":2},"reviews":{"totalCount":4}}},"rateLimit":{"cost":1,"remaining":4993,"resetAt":"2026-10-03T00:52:19Z"}}}

View File

@@ -0,0 +1 @@
{"data":{"repository":{"nameWithOwner":"cli/cli","viewerPermission":"READ","mergeCommitAllowed":true,"squashMergeAllowed":true,"rebaseMergeAllowed":true,"viewerDefaultMergeMethod":"MERGE","deleteBranchOnMerge":true,"pullRequest":{"id":"PR_kwDODKw3uc7M4C9c","number":13013,"viewerCanEnableAutoMerge":false,"viewerCanDisableAutoMerge":false,"autoMergeRequest":null,"title":"fix: handle non-zipped artifact downloads","body":"<!--\r\n Thank you for contributing to GitHub CLI!\r\n To reference an open issue, please write this in your description: `Fixes #NUMBER`\r\n-->\r\n\r\nFixes #13012.","url":"https://github.com/cli/cli/pull/13013","state":"OPEN","isDraft":false,"baseRefName":"trunk","headRefName":"fix-non-zipped-artifact-download","headRefOid":"b724142758f68492eef5d82b5be203727c134e17","additions":78,"deletions":8,"changedFiles":5,"updatedAt":"2026-07-21T00:32:56Z","mergeStateStatus":"DIRTY","mergeable":"CONFLICTING","reviewDecision":"REVIEW_REQUIRED","viewerDidAuthor":false,"isCrossRepository":true,"maintainerCanModify":true,"headRepository":{"viewerPermission":"READ"},"author":{"__typename":"User","login":"dsanders11"},"labels":{"nodes":[{"name":"external","color":"2700AF"},{"name":"ready-for-review","color":"39d965"}]},"commitCount":{"totalCount":2},"head":{"nodes":[{"commit":{"statusCheckRollup":{"contexts":{"checkRunCountsByState":[{"state":"ACTION_REQUIRED","count":0},{"state":"CANCELLED","count":0},{"state":"COMPLETED","count":0},{"state":"FAILURE","count":1},{"state":"IN_PROGRESS","count":0},{"state":"NEUTRAL","count":0},{"state":"PENDING","count":0},{"state":"QUEUED","count":0},{"state":"SKIPPED","count":6},{"state":"STALE","count":0},{"state":"STARTUP_FAILURE","count":0},{"state":"SUCCESS","count":11},{"state":"TIMED_OUT","count":0},{"state":"WAITING","count":0}],"statusContextCountsByState":[{"state":"EXPECTED","count":0},{"state":"ERROR","count":0},{"state":"FAILURE","count":0},{"state":"PENDING","count":0},{"state":"SUCCESS","count":0}],"nodes":[{"__typename":"CheckRun","name":"label-external","conclusion":"SKIPPED","status":"COMPLETED","isRequired":false},{"__typename":"CheckRun","name":"discuss","conclusion":"SKIPPED","status":"COMPLETED","isRequired":false},{"__typename":"CheckRun","name":"CodeQL-Build (go)","conclusion":"SUCCESS","status":"COMPLETED","isRequired":false},{"__typename":"CheckRun","name":"lint","conclusion":"SUCCESS","status":"COMPLETED","isRequired":false},{"__typename":"CheckRun","name":"build (ubuntu-latest)","conclusion":"SUCCESS","status":"COMPLETED","isRequired":true},{"__typename":"CheckRun","name":"CodeQL-Build (actions)","conclusion":"SUCCESS","status":"COMPLETED","isRequired":false},{"__typename":"CheckRun","name":"build (windows-latest)","conclusion":"SUCCESS","status":"COMPLETED","isRequired":true},{"__typename":"CheckRun","name":"build (macos-latest)","conclusion":"SUCCESS","status":"COMPLETED","isRequired":true},{"__typename":"CheckRun","name":"govulncheck","conclusion":"FAILURE","status":"COMPLETED","isRequired":false},{"__typename":"CheckRun","name":"close-from-default-branch","conclusion":"SKIPPED","status":"COMPLETED","isRequired":false},{"__typename":"CheckRun","name":"integration-tests (ubuntu-latest)","conclusion":"SUCCESS","status":"COMPLETED","isRequired":false},{"__typename":"CheckRun","name":"integration-tests (windows-latest)","conclusion":"SUCCESS","status":"COMPLETED","isRequired":false},{"__typename":"CheckRun","name":"integration-tests (macos-latest)","conclusion":"SUCCESS","status":"COMPLETED","isRequired":false},{"__typename":"CheckRun","name":"check-requirements","conclusion":"SKIPPED","status":"COMPLETED","isRequired":false},{"__typename":"CheckRun","name":"close-unmet-requirements","conclusion":"SKIPPED","status":"COMPLETED","isRequired":false},{"__typename":"CheckRun","name":"close-no-help-wanted / close-no-help-wanted","conclusion":"SKIPPED","status":"COMPLETED","isRequired":false},{"__typename":"CheckRun","name":"ready-for-review / ready-for-review","conclusion":"SUCCESS","status":"COMPLETED","isRequired":false},{"__typename":"CheckRun","name":"CodeQL","conclusion":"SUCCESS","status":"COMPLETED","isRequired":false}]}}}}]},"reviewRequests":{"nodes":[{"requestedReviewer":null},{"requestedReviewer":{"__typename":"User","login":"williammartin"}},{"requestedReviewer":{"__typename":"User","login":"BagToad"}}]},"latestOpinionatedReviews":{"nodes":[]},"latestReviews":{"nodes":[{"author":{"__typename":"Bot","login":"copilot-pull-request-reviewer"},"state":"COMMENTED","submittedAt":"2026-03-24T04:09:29Z"},{"author":{"__typename":"User","login":"ke66344060-ship-it"},"state":"COMMENTED","submittedAt":"2026-07-15T16:11:38Z"}]},"reviewThreads":{"totalCount":3,"nodes":[{"isResolved":true},{"isResolved":false},{"isResolved":true}]},"comments":{"totalCount":5},"reviews":{"totalCount":4}}},"rateLimit":{"cost":1,"remaining":4991,"resetAt":"2026-10-03T00:52:19Z"}}}

View File

@@ -0,0 +1 @@
{"data":{"repository":{"nameWithOwner":"nora-quinn/luxe-dev","viewerPermission":"ADMIN","mergeCommitAllowed":true,"squashMergeAllowed":true,"rebaseMergeAllowed":true,"viewerDefaultMergeMethod":"MERGE","deleteBranchOnMerge":false,"pullRequest":{"id":"PR_kwDOTyoMn88AAAABGOjG4w","number":198,"viewerCanEnableAutoMerge":false,"viewerCanDisableAutoMerge":false,"autoMergeRequest":null,"title":"Guided Review's footer rule starts a cell clear of the divider","body":"Flush with the diff pane, the rule over the review's keys all but met the vertical divider beside it. It now starts one cell in, where the keys under it and the rule under the narration do. Screenshots regenerated.","url":"https://github.com/nora-quinn/luxe-dev/pull/198","state":"MERGED","isDraft":false,"baseRefName":"master","headRefName":"polish/review-footer-rule","headRefOid":"32814a75df579afc3febad3ca1c8ca4dc84a0081","additions":14,"deletions":15,"changedFiles":4,"updatedAt":"2026-10-02T05:17:57Z","mergeStateStatus":"UNKNOWN","mergeable":"UNKNOWN","reviewDecision":null,"viewerDidAuthor":true,"isCrossRepository":false,"maintainerCanModify":false,"headRepository":{"viewerPermission":"ADMIN"},"author":{"__typename":"User","login":"nora-quinn"},"labels":{"nodes":[]},"commitCount":{"totalCount":1},"head":{"nodes":[{"commit":{"statusCheckRollup":{"contexts":{"checkRunCountsByState":[{"state":"ACTION_REQUIRED","count":0},{"state":"CANCELLED","count":0},{"state":"COMPLETED","count":0},{"state":"FAILURE","count":0},{"state":"IN_PROGRESS","count":0},{"state":"NEUTRAL","count":0},{"state":"PENDING","count":0},{"state":"QUEUED","count":0},{"state":"SKIPPED","count":0},{"state":"STALE","count":0},{"state":"STARTUP_FAILURE","count":0},{"state":"SUCCESS","count":5},{"state":"TIMED_OUT","count":0},{"state":"WAITING","count":0}],"statusContextCountsByState":[{"state":"EXPECTED","count":0},{"state":"ERROR","count":0},{"state":"FAILURE","count":0},{"state":"PENDING","count":0},{"state":"SUCCESS","count":0}],"nodes":[{"__typename":"CheckRun","name":"build · test · clippy · fmt","conclusion":"SUCCESS","status":"COMPLETED","isRequired":false},{"__typename":"CheckRun","name":"build · clippy · test (macos-latest)","conclusion":"SUCCESS","status":"COMPLETED","isRequired":false},{"__typename":"CheckRun","name":"build · clippy · test (windows-latest)","conclusion":"SUCCESS","status":"COMPLETED","isRequired":false},{"__typename":"CheckRun","name":"cargo-deny","conclusion":"SUCCESS","status":"COMPLETED","isRequired":false},{"__typename":"CheckRun","name":"web build","conclusion":"SUCCESS","status":"COMPLETED","isRequired":false}]}}}}]},"reviewRequests":{"nodes":[]},"latestOpinionatedReviews":{"nodes":[]},"latestReviews":{"nodes":[]},"reviewThreads":{"totalCount":0,"nodes":[]},"comments":{"totalCount":0},"reviews":{"totalCount":0}}},"rateLimit":{"cost":1,"remaining":4994,"resetAt":"2026-10-03T00:52:19Z"}}}

View File

@@ -0,0 +1 @@
{"message":"Updating pull request branch.","url":"https://api.github.com/repos/nora-quinn/luxe-dev/pulls/199"}

View File

@@ -0,0 +1 @@
{"message":"expected head sha didn’t match current head ref.","documentation_url":"https://docs.github.com/rest/pulls/pulls#update-a-pull-request-branch","status":"422"}

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1 @@
{"id":5307695620,"node_id":"PRR_kwDOTyoMn88AAAABPF0CBA","user":{"login":"nora-quinn","id":10000001,"node_id":"MDQ6VXNlcjEwMDAwMDAx","avatar_url":"https://avatars.githubusercontent.com/u/10000001?v=4","gravatar_id":"","url":"https://api.github.com/users/nora-quinn","html_url":"https://github.com/nora-quinn","followers_url":"https://api.github.com/users/nora-quinn/followers","following_url":"https://api.github.com/users/nora-quinn/following{/other_user}","gists_url":"https://api.github.com/users/nora-quinn/gists{/gist_id}","starred_url":"https://api.github.com/users/nora-quinn/starred{/owner}{/repo}","subscriptions_url":"https://api.github.com/users/nora-quinn/subscriptions","organizations_url":"https://api.github.com/users/nora-quinn/orgs","repos_url":"https://api.github.com/users/nora-quinn/repos","events_url":"https://api.github.com/users/nora-quinn/events{/privacy}","received_events_url":"https://api.github.com/users/nora-quinn/received_events","type":"User","user_view_type":"public","site_admin":false},"body":"Fixture review: a body and two line comments, one on each side.","state":"COMMENTED","html_url":"https://github.com/nora-quinn/luxe-dev/pull/141#pullrequestreview-5307695620","pull_request_url":"https://api.github.com/repos/nora-quinn/luxe-dev/pulls/141","author_association":"OWNER","_links":{"html":{"href":"https://github.com/nora-quinn/luxe-dev/pull/141#pullrequestreview-5307695620"},"pull_request":{"href":"https://api.github.com/repos/nora-quinn/luxe-dev/pulls/141"}},"submitted_at":"2026-09-24T17:10:42Z","commit_id":"6277c5f225665e1d99617a5dbe7d0a416e4c3697"}

View File

@@ -0,0 +1 @@
{"message":"Unprocessable Entity","errors":["Variable $comments of type [DraftPullRequestReviewComment] was provided invalid value for 0.subjectType (Field is not defined on DraftPullRequestReviewComment), 0.position (Expected value to not be null)"],"documentation_url":"https://docs.github.com/rest/pulls/reviews#create-a-review-for-a-pull-request","status":"422"}

View File

@@ -0,0 +1 @@
{"message":"Unprocessable Entity","errors":["Line could not be resolved"],"documentation_url":"https://docs.github.com/rest/pulls/reviews#create-a-review-for-a-pull-request","status":"422"}

View File

@@ -0,0 +1 @@
{"message":"Unprocessable Entity","errors":["Review Can not approve your own pull request"],"documentation_url":"https://docs.github.com/rest/pulls/reviews#create-a-review-for-a-pull-request","status":"422"}

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1 @@
{"data":{"repository":{"pullRequest":{"reviewThreads":{"totalCount":1,"nodes":[{"id":"PRRT_kwDOBC3Cis6mLaj-","isResolved":false,"isOutdated":false,"path":"docs/01-app/02-guides/incremental-static-regeneration-cache-components.mdx","line":229,"originalLine":230,"startLine":219,"diffSide":"RIGHT","startDiffSide":"RIGHT","subjectType":"LINE","viewerCanReply":true,"viewerCanResolve":false,"comments":{"totalCount":1,"nodes":[{"author":{"login":"vercel"},"body":"Docs example imports and calls `navigation` from `next/cache`\\, but the only exported API is `unstable_navigation`\\, so the code sample would fail\\.\n\n<!-- VADE-CATEGORY: typo -->\n<!-- VADE-GITHUB-SUGGESTION-ID:6de0f067b6cf88eefd4a22ff881bac583de3ce855589f3be0a274e64f827bcb5 -->\n\n<!-- VADE-RECOMMENDATION: FIX -->\n<a href=\"https://vercel.com/vercel/~/agent/tasks/2e7889ba-b8c7-47cd-9ebb-21319cf0477d#suggestion-6de0f067b6cf88eefd4a22ff881bac583de3ce855589f3be0a274e64f827bcb5\" rel=\"noreferrer\"><picture>\n <source media=\"(prefers-color-scheme: dark)\" srcset=\"https://vercel.com/vercel-agent-view-suggestion-dark\">\n <source media=\"(prefers-color-scheme: light)\" srcset=\"https://vercel.com/vercel-agent-view-suggestion-light\">\n <img src=\"https://vercel.com/vercel-agent-view-suggestion-light\" alt=\"Fix on Vercel\" width=\"127\" height=\"28\" />\n </picture></a>","createdAt":"2026-09-25T22:49:48Z","url":"https://github.com/vercel/next.js/pull/99263#discussion_r4109226930","diffHunk":"@@ -216,6 +214,64 @@ After the first visit, Next.js renders the page in the background with the known\n - If all params are resolved but the render still hits uncached data or runtime APIs (`cookies`, `headers`) wrapped in `<Suspense>` boundaries, the upgrade produces a **cached page with those fallbacks**. The uncached or runtime parts stream in at request time.\n - Params are resolved in route order. A param value not returned by `generateStaticParams` stays unresolved and prevents any deeper params from upgrading.\n \n+### Deferring expensive content\n+\n+Because links to these pages use `prefetch={true}`, each prefetch also prepares content that depends on `cookies` or `headers`. Consider showing each price in the visitor's currency. The currency comes from a cookie, and converting the price calls an exchange-rate service, so every prefetch of a product link would run that conversion. Use [`await navigation()`](/docs/app/api-reference/functions/navigation) before it. The prefetch leaves the converted price out, and it renders when the user navigates.\n+\n+```tsx filename=\"app/[category]/[product]/page.tsx\" highlight={1-2,4,6-24,32-34}\n+import { cookies } from 'next/headers'\n+import { navigation } from 'next/cache'\n+import { Suspense } from 'react'\n+import { getProduct, getExchangeRate } from '../../lib/data'\n+\n+async function LocalPrice({\n+ params,\n+}: Pick<PageProps<'/[category]/[product]'>, 'params'>) {\n+ await navigation()"}]}}]},"comments":{"nodes":[{"id":"IC_kwDOBC3Cis8AAAABXCIlJg","author":{"__typename":"Bot","login":"github-actions"},"body":"<!-- __NEXT_TEST_REPORT_COMMENT__ -->\n## Tests Passed\n\n<!-- ## Failing test suites -->\nCommit: 913e460cc0dc72ba9bed387469f24ad2fd425733\n","createdAt":"2026-09-25T22:47:56Z","url":"https://github.com/vercel/next.js/pull/99263#issuecomment-5840708902","isMinimized":false,"viewerDidAuthor":false}]},"reviews":{"nodes":[{"id":"PRR_kwDOBC3Cis8AAAABPUyQkw","author":{"__typename":"Bot","login":"vercel"},"body":"","createdAt":"2026-09-25T22:49:48Z","url":"https://github.com/vercel/next.js/pull/99263#pullrequestreview-5323395219","viewerDidAuthor":false}]}}},"rateLimit":{"cost":1,"remaining":4960,"resetAt":"2026-09-25T23:57:50Z"}}}

View File

@@ -0,0 +1 @@
{"data":{"repository":{"pullRequest":{"reviewThreads":{"totalCount":0,"nodes":[]},"comments":{"nodes":[{"id":"IC_kwDOTyoMn88AAAABXB8h6w","author":{"__typename":"User","login":"nora-quinn"},"body":"In `scratch-note.md`, please change \"Hello\" to \"Hello from the other side!\"","createdAt":"2026-09-25T22:26:35Z","url":"https://github.com/nora-quinn/luxe-dev/pull/169#issuecomment-5840511467","isMinimized":false,"viewerDidAuthor":true},{"id":"IC_kwDOTyoMn88AAAABXCSRPQ","author":{"__typename":"User","login":"nora-quinn"},"body":"Ignore this one, posted by mistake.","createdAt":"2026-09-25T23:07:15Z","url":"https://github.com/nora-quinn/luxe-dev/pull/169#issuecomment-5840867645","isMinimized":true,"viewerDidAuthor":true},{"id":"IC_kwDOTyoMn88AAAABXCSmSQ","author":{"__typename":"User","login":"nora-quinn"},"body":"> In `scratch-note.md`, please change \"Hello\" to \"Hello from the other side!\"\n\nRecorded for a test fixture.","createdAt":"2026-09-25T23:07:56Z","url":"https://github.com/nora-quinn/luxe-dev/pull/169#issuecomment-5840873033","isMinimized":true,"viewerDidAuthor":true},{"id":"IC_kwDOTyoMn88AAAABXCnvuQ","author":{"__typename":"User","login":"nora-quinn"},"body":"> In `scratch-note.md`, please change \"Hello\" to \"Hello from the other side!\"\n\nChanged it in the next push.","createdAt":"2026-09-25T23:51:45Z","url":"https://github.com/nora-quinn/luxe-dev/pull/169#issuecomment-5841219513","isMinimized":false,"viewerDidAuthor":true}]},"reviews":{"nodes":[{"id":"PRR_kwDOTyoMn88AAAABPU2kMA","author":{"__typename":"User","login":"nora-quinn"},"body":"Also, end the file with a newline.","createdAt":"2026-09-25T23:07:14Z","url":"https://github.com/nora-quinn/luxe-dev/pull/169#pullrequestreview-5323465776","viewerDidAuthor":true}]}}},"rateLimit":{"cost":1,"remaining":4961,"resetAt":"2026-09-25T23:57:50Z"}}}

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1 @@
{"data":{"repository":{"pullRequest":{"reviewThreads":{"totalCount":3,"nodes":[{"id":"PRRT_kwDOTyoMn86lxn7W","isResolved":false,"isOutdated":false,"path":"scratch_round_trip.py","line":7,"originalLine":7,"startLine":7,"diffSide":"RIGHT","startDiffSide":null,"subjectType":"LINE","viewerCanReply":true,"viewerCanResolve":true,"comments":{"totalCount":1,"nodes":[{"author":{"login":"nora-quinn"},"body":"This starts at 1, so the first number is never added: `total([5])` is 0.","createdAt":"2026-09-24T21:28:56Z","url":"https://github.com/nora-quinn/luxe-dev/pull/146#discussion_r4098668311","diffHunk":"@@ -0,0 +1,14 @@\n+\"\"\"Scratch file for a review round trip. It is deleted with its pull request.\"\"\"\n+\n+\n+def total(numbers):\n+ \"\"\"Adds up every number in the list.\"\"\"\n+ result = 0\n+ for index in range(1, len(numbers)):"}]}},{"id":"PRRT_kwDOTyoMn86lxn7Z","isResolved":false,"isOutdated":false,"path":"scratch_round_trip.py","line":14,"originalLine":14,"startLine":14,"diffSide":"RIGHT","startDiffSide":null,"subjectType":"LINE","viewerCanReply":true,"viewerCanResolve":true,"comments":{"totalCount":1,"nodes":[{"author":{"login":"nora-quinn"},"body":"An empty list divides by zero here, whatever the docstring says.","createdAt":"2026-09-24T21:28:56Z","url":"https://github.com/nora-quinn/luxe-dev/pull/146#discussion_r4098668317","diffHunk":"@@ -0,0 +1,14 @@\n+\"\"\"Scratch file for a review round trip. It is deleted with its pull request.\"\"\"\n+\n+\n+def total(numbers):\n+ \"\"\"Adds up every number in the list.\"\"\"\n+ result = 0\n+ for index in range(1, len(numbers)):\n+ result += numbers[index]\n+ return result\n+\n+\n+def mean(numbers):\n+ \"\"\"The average of the numbers, or zero for an empty list.\"\"\"\n+ return total(numbers) / len(numbers)"}]}},{"id":"PRRT_kwDOTyoMn86lxn7g","isResolved":false,"isOutdated":false,"path":"scratch_round_trip.py","line":1,"originalLine":1,"startLine":1,"diffSide":"RIGHT","startDiffSide":null,"subjectType":"LINE","viewerCanReply":true,"viewerCanResolve":true,"comments":{"totalCount":1,"nodes":[{"author":{"login":"nora-quinn"},"body":"Fixture thread: replied to and resolved while capturing responses.","createdAt":"2026-09-24T21:28:56Z","url":"https://github.com/nora-quinn/luxe-dev/pull/146#discussion_r4098668327","diffHunk":"@@ -0,0 +1,14 @@\n+\"\"\"Scratch file for a review round trip. It is deleted with its pull request.\"\"\""}]}}]}}},"rateLimit":{"cost":1,"remaining":4994,"resetAt":"2026-09-24T22:28:38Z"}}}

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1 @@
{"data":{"addPullRequestReviewThreadReply":{"comment":{"url":"https://github.com/nora-quinn/luxe-dev/pull/146#discussion_r4098691176"}}}}

View File

@@ -0,0 +1 @@
{"data":{"resolveReviewThread":{"thread":{"isResolved":true}}}}

View File

@@ -0,0 +1 @@
{"body":"Fixture review: a body and two line comments, one on each side.","commit_id":"6277c5f225665e1d99617a5dbe7d0a416e4c3697","html_url":"https://github.com/nora-quinn/luxe-dev/pull/141#pullrequestreview-5307695620","id":5307695620,"state":"COMMENTED","submitted_at":"2026-09-24T17:10:42Z","user":"nora-quinn"}

View File

@@ -0,0 +1,369 @@
//! GhCli — [`GitHub`](super::GitHub) over the user's own `gh`.
//!
//! Every call is a bounded, non-interactive subprocess ([`crate::program::run_bounded`]): stdin
//! closed, prompts disabled, output captured, the tree killed at the deadline. `gh` is resolved
//! through [`crate::program::resolve`], so a copy installed by scoop, winget or Homebrew outside
//! the inherited `PATH` is still found.
mod branches;
mod checks;
mod conversation;
mod discovery;
mod issue_overview;
mod overview;
mod pull_requests;
mod reviews;
mod search;
mod threads;
mod writes;
use search::parse_search;
#[cfg(test)]
use {
branches::*, checks::*, discovery::*, pull_requests::*, reviews::*, threads::*,
writes::parse_opened,
};
use super::remote::{matching_remote, parse_remote_url, parse_remotes};
use super::{
Account, Author, BranchHead, BranchStatus, Branches, CheckLog, CheckRollup, Checks,
CommentableLines, ConversationComment, Discovery, ExistingReview, FailedStep, FailingCheck,
FilePatch, GitHubError, Issue, IssueComment, IssueRef, NewPullRequest, OpenedPullRequest,
PostedReview, PullRequest, PullRequestHead, PullRequestState, PullRequestStatus, PullRequests,
PushAccess, RateLimit, Repository, ReviewDecision, ReviewEvent, ReviewThread, ReviewThreads,
Reviews, SearchPage, Stack, StackEntry, SubmitReview, ThreadComment, ThreadSide, Threads,
Writes,
};
use crate::program::{captured_command, run_bounded, BoundedRunError};
use async_trait::async_trait;
use serde::Deserialize;
use std::path::{Path, PathBuf};
use std::time::Duration;
/// How long a `gh` call may take before it is reaped. Every one is a network call.
const GH_DEADLINE: Duration = Duration::from_secs(60);
/// How long `git remote -v` may take. It reads a config file; anything slower is stuck.
const GIT_DEADLINE: Duration = Duration::from_secs(10);
/// What one `gh` run printed, and whether it succeeded.
struct GhRun {
success: bool,
stdout: String,
stderr: String,
}
/// [`GitHub`](super::GitHub) backed by the `gh` command-line tool.
#[derive(Debug, Clone)]
pub struct GhCli {
deadline: Duration,
/// A specific `gh` to run instead of resolving one, for tests
program: Option<PathBuf>,
}
impl Default for GhCli {
fn default() -> Self {
Self { deadline: GH_DEADLINE, program: None }
}
}
impl GhCli {
/// A client that runs `gh` with the default deadline.
pub fn new() -> Self {
Self::default()
}
/// Run `gh` in `cwd` and return its stdout, or the failure classified.
async fn gh(&self, cwd: &Path, args: &[&str]) -> Result<String, GitHubError> {
let ran = self.run(cwd, args).await?;
if ran.success {
Ok(ran.stdout)
} else {
Err(classify_failure(&ran.stderr, &ran.stdout))
}
}
/// Run `gh` in `cwd` and hand back both streams whatever the exit status.
///
/// For the one call whose failure is worth reading closely: a refused post answers with JSON
/// on stdout naming the reasons, and only `HTTP 422` on stderr.
async fn run(&self, cwd: &Path, args: &[&str]) -> Result<GhRun, GitHubError> {
let program = match &self.program {
Some(program) => program.clone(),
None => crate::program::resolve("gh").ok_or(GitHubError::NotInstalled)?,
};
let mut command = captured_command(&program, args, cwd);
// No prompt could be answered from behind the TUI, and an update notice on stderr would
// be read as part of the error
command
.env("GH_PROMPT_DISABLED", "1")
.env("GH_NO_UPDATE_NOTIFIER", "1")
.env("NO_COLOR", "1");
let output = run_bounded(command, self.deadline).await.map_err(|error| match error {
BoundedRunError::Timeout { after } => GitHubError::Timeout { after },
BoundedRunError::Spawn(source) | BoundedRunError::Wait(source) => {
GitHubError::Run { program: "gh", source }
}
})?;
Ok(GhRun {
success: output.status.success(),
stdout: String::from_utf8_lossy(&output.stdout).into_owned(),
stderr: String::from_utf8_lossy(&output.stderr).into_owned(),
})
}
async fn remotes(cwd: &Path) -> Vec<(String, String)> {
local_remotes(cwd).await
}
}
/// `git remote -v` in `cwd`, or an empty list when it cannot be read.
///
/// A checkout whose remotes cannot be listed still has a repository `gh` could name; it just has no
/// remote to fetch it through, which [`Repository::remote`] says with `None`.
pub(super) async fn local_remotes(cwd: &Path) -> Vec<(String, String)> {
let program = crate::program::resolve("git").unwrap_or_else(|| PathBuf::from("git"));
let command = captured_command(program, &["remote", "-v"], cwd);
match run_bounded(command, GIT_DEADLINE).await {
Ok(output) if output.status.success() => {
parse_remotes(&String::from_utf8_lossy(&output.stdout))
}
_ => Vec::new(),
}
}
/// The REST path of a pull request, for `gh api`.
fn pulls_endpoint(repository: &Repository, number: u64) -> String {
format!("repos/{}/{}/pulls/{number}", repository.owner, repository.name)
}
/// Points `gh api` at a GitHub Enterprise host; github.com needs nothing.
fn push_hostname<'a>(args: &mut Vec<&'a str>, repository: &'a Repository) {
if repository.host != "github.com" {
args.extend(["--hostname", repository.host.as_str()]);
}
}
/// A file only its owner can read, removed when dropped.
///
/// `gh api --input` reads a review from a file, and a review is the reader's own words before
/// anyone else has seen them: kept `0600` on unix, and gone however the post ends.
struct PrivateFile {
path: PathBuf,
}
impl PrivateFile {
fn write(contents: &str) -> std::io::Result<Self> {
use std::io::Write;
let path = std::env::temp_dir().join(format!("luxe-review-{}.json", uuid::Uuid::new_v4()));
let mut options = std::fs::OpenOptions::new();
options.write(true).create_new(true);
#[cfg(unix)]
{
use std::os::unix::fs::OpenOptionsExt;
options.mode(0o600);
}
let file = Self { path };
options.open(&file.path)?.write_all(contents.as_bytes())?;
Ok(file)
}
}
impl Drop for PrivateFile {
fn drop(&mut self) {
let _ = std::fs::remove_file(&self.path);
}
}
/// GitHub's reasons for refusing a request, when its answer carries them.
fn rejection(stdout: &str) -> Option<GitHubError> {
#[derive(Deserialize)]
struct Refusal {
errors: Vec<serde_json::Value>,
}
let refusal: Refusal = serde_json::from_str(stdout.trim()).ok()?;
let reasons: Vec<String> = refusal
.errors
.iter()
.map(|error| match error {
serde_json::Value::String(reason) => reason.clone(),
other => other
.get("message")
.and_then(|m| m.as_str())
.map_or_else(|| other.to_string(), str::to_owned),
})
.map(|reason| super::untrusted(&reason, FAILURE_MAX_CHARS))
.collect();
(!reasons.is_empty()).then_some(GitHubError::Rejected { reasons })
}
/// How `gh --repo` names a repository: `owner/name`, prefixed with the host off github.com.
fn repo_arg(repository: &Repository) -> String {
match repository.host.as_str() {
"github.com" => repository.slug(),
host => format!("{host}/{}", repository.slug()),
}
}
/// Turn a failed `gh` call into the variant a caller can act on.
///
/// The one place `gh`'s wording is read. Both streams, because `gh` does not always say why on
/// stderr. Anything unrecognized becomes [`GitHubError::Failed`] with `gh`'s own words, bounded —
/// guessing at an error nobody anticipated is how a tool starts lying about what went wrong.
pub fn classify_failure(stderr: &str, stdout: &str) -> GitHubError {
let reported = match stderr.trim() {
"" => stdout.trim(),
text => text,
};
let lower = reported.to_lowercase();
// First: `gh`'s "no GitHub remote" message ends by suggesting `gh auth login`, and read as a
// sign-in problem it would send the reader to fix an account that is fine
if lower.contains("no git remotes found")
|| lower.contains("none of the git remotes configured for this repository")
|| lower.contains("not a git repository")
{
return GitHubError::NotGitHub;
}
if lower.contains("gh auth login")
|| lower.contains("not logged")
|| lower.contains("authentication token")
|| lower.contains("requires authentication")
|| lower.contains("bad credentials")
{
return GitHubError::NotAuthenticated { host: None };
}
// Before anything else a 403 might be read as: a spent budget is a wait, not a fault
if lower.contains("rate limit exceeded")
|| lower.contains("rate limit already exceeded")
|| lower.contains("secondary rate limit")
|| lower.contains("http 429")
{
return GitHubError::RateLimited;
}
if lower.contains("could not resolve to a") || lower.contains("http 404") {
return GitHubError::NotFound;
}
let message = match reported {
"" => "no output".to_string(),
text => super::untrusted(text, FAILURE_MAX_CHARS),
};
GitHubError::Failed { message }
}
#[derive(Deserialize)]
struct IssueAuthor {
login: String,
}
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct Connection<T> {
#[serde(default)]
total_count: usize,
nodes: Vec<T>,
}
#[derive(Deserialize)]
struct Nodes<T> {
nodes: Vec<T>,
}
#[derive(Deserialize)]
struct Login {
login: String,
}
/// Seconds since the Unix epoch for GitHub's `2026-09-24T19:05:02Z`, or `None` for anything else.
pub fn rfc3339_seconds(stamp: &str) -> Option<u64> {
let (date, time) = stamp.strip_suffix('Z')?.split_once('T')?;
let mut date = date.splitn(3, '-').map(str::parse::<i64>);
let (year, month, day) = (date.next()?.ok()?, date.next()?.ok()?, date.next()?.ok()?);
let mut time = time.splitn(3, ':');
let hour: i64 = time.next()?.parse().ok()?;
let minute: i64 = time.next()?.parse().ok()?;
// Fractional seconds are dropped; a refill time is not that precise
let second: i64 = time.next()?.split('.').next()?.parse().ok()?;
if !(1..=12).contains(&month) || !(1..=31).contains(&day) || hour > 23 || minute > 59 {
return None;
}
// Days from the civil calendar, after Howard Hinnant's `days_from_civil`
let year = if month <= 2 { year - 1 } else { year };
let era = year.div_euclid(400);
let year_of_era = year - era * 400;
let day_of_year = (153 * ((month + 9) % 12) + 2) / 5 + day - 1;
let day_of_era = year_of_era * 365 + year_of_era / 4 - year_of_era / 100 + day_of_year;
let days = era * 146_097 + day_of_era - 719_468;
u64::try_from(days * 86_400 + hour * 3_600 + minute * 60 + second).ok()
}
/// Longest slice of `gh`'s own error text carried in [`GitHubError::Failed`], in characters.
pub(super) const FAILURE_MAX_CHARS: usize = 600;
/// Longest title or summary a status row carries, in characters.
pub(super) const STATUS_TEXT_MAX_CHARS: usize = 200;
/// GitHub's own tally of the head's checks, sorted the way [`roll_up`](pull_requests::roll_up)
/// sorts a list of them.
pub(super) fn count_checks(contexts: &RollupContexts) -> CheckRollup {
let mut rollup = CheckRollup::default();
for StateCount { state, count } in &contexts.check_run_counts_by_state {
let bucket = match state.as_str() {
"SUCCESS" => &mut rollup.passed,
"NEUTRAL" | "SKIPPED" => &mut rollup.skipped,
"FAILURE" | "TIMED_OUT" | "CANCELLED" | "ACTION_REQUIRED" | "STARTUP_FAILURE"
| "STALE" => &mut rollup.failed,
"QUEUED" | "IN_PROGRESS" | "PENDING" | "WAITING" => &mut rollup.pending,
_ => continue,
};
*bucket += count;
}
for StateCount { state, count } in &contexts.status_context_counts_by_state {
let bucket = match state.as_str() {
"SUCCESS" => &mut rollup.passed,
"PENDING" | "EXPECTED" => &mut rollup.pending,
"FAILURE" | "ERROR" => &mut rollup.failed,
_ => continue,
};
*bucket += count;
}
rollup
}
/// A stranger's one-liner, fit for a status row: filtered, on one line, and bounded.
pub(super) fn status_text(text: &str) -> String {
let clean = crate::instructions::sanitize(text).text;
let line = clean.split_whitespace().collect::<Vec<_>>().join(" ");
if line.chars().count() <= STATUS_TEXT_MAX_CHARS {
return line;
}
let kept: String = line.chars().take(STATUS_TEXT_MAX_CHARS - 1).collect();
format!("{}…", kept.trim_end())
}
/// One JSON object per line, the shape `--paginate --jq '.[] | …'` prints across every page.
pub(super) fn parse_lines<T: serde::de::DeserializeOwned>(
body: &str,
) -> Result<Vec<T>, GitHubError> {
body.lines()
.filter(|line| !line.trim().is_empty())
.map(|line| serde_json::from_str(line).map_err(GitHubError::Unreadable))
.collect()
}
#[derive(Deserialize)]
pub(super) struct StateCount {
pub(super) state: String,
pub(super) count: usize,
}
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
pub(super) struct RollupContexts {
#[serde(default)]
pub(super) check_run_counts_by_state: Vec<StateCount>,
#[serde(default)]
pub(super) status_context_counts_by_state: Vec<StateCount>,
}
#[cfg(test)]
mod tests;

View File

@@ -0,0 +1,391 @@
//! Branches — a branch's pull request and stack, where its head lives, and what merged below it.
use super::*;
mod stack;
pub(super) use stack::*;
#[async_trait]
impl Branches for GhCli {
async fn branch_status(
&self,
repository: &Repository,
head: &BranchHead,
) -> Result<BranchStatus, GitHubError> {
let query = format!("query={BRANCH_STATUS_QUERY}");
let (owner, name, branch) = (
format!("owner={}", repository.owner),
format!("name={}", repository.name),
format!("branch={}", head.name),
);
let mut args = vec!["api", "graphql"];
push_hostname(&mut args, repository);
// `-f`, not `-F`, for the branch: `-F` reads `@name` as a file and `123` as a number
args.extend(["-f", &query, "-F", &owner, "-F", &name, "-f", &branch]);
let body = self.gh(&std::env::temp_dir(), &args).await?;
parse_branch_status(&body, &head.name, head.owner.as_deref().unwrap_or(&repository.owner))
}
async fn pull_request_head(
&self,
repository: &Repository,
number: u64,
) -> Result<PullRequestHead, GitHubError> {
let query = format!("query={PULL_REQUEST_HEAD_QUERY}");
let (owner, name, number) = (
format!("owner={}", repository.owner),
format!("name={}", repository.name),
format!("number={number}"),
);
let mut args = vec!["api", "graphql"];
push_hostname(&mut args, repository);
args.extend(["-f", &query, "-F", &owner, "-F", &name, "-F", &number]);
let body = self.gh(&std::env::temp_dir(), &args).await?;
parse_pull_request_head(&body)
}
async fn merged_below(
&self,
repository: &Repository,
number: u64,
base: &str,
) -> Result<Option<crate::restack::MergedBelow>, GitHubError> {
let (owner, name) =
(format!("owner={}", repository.owner), format!("name={}", repository.name));
let query = format!("query={MERGED_BELOW_QUERY}");
let (number, base_arg) = (format!("number={number}"), format!("base={base}"));
let mut args = vec!["api", "graphql"];
push_hostname(&mut args, repository);
args.extend(["-f", &query, "-F", &owner, "-F", &name, "-F", &number, "-f", &base_arg]);
let body = self.gh(&std::env::temp_dir(), &args).await?;
let (merged, previous) = parse_merged_below(&body)?;
if merged.is_some() {
return Ok(merged);
}
let Some(previous) = previous.filter(|previous| previous != base) else {
return Ok(None);
};
let query = format!("query={MERGED_BY_HEAD_QUERY}");
let head = format!("head={previous}");
let mut args = vec!["api", "graphql"];
push_hostname(&mut args, repository);
args.extend(["-f", &query, "-F", &owner, "-F", &name, "-f", &head]);
let body = self.gh(&std::env::temp_dir(), &args).await?;
Ok(parse_merged_below(&body)?.0)
}
}
pub(super) const MERGED_BELOW_QUERY: &str =
"query($owner:String!,$name:String!,$number:Int!,$base:String!){\
repository(owner:$owner,name:$name){pullRequest(number:$number){\
timelineItems(itemTypes:[BASE_REF_CHANGED_EVENT],last:1){nodes{...on BaseRefChangedEvent{\
previousRefName}}}} merged:pullRequests(headRefName:$base,states:MERGED,first:1,\
orderBy:{field:UPDATED_AT,direction:DESC}){nodes{number headRefOid baseRefName}}}}";
pub(super) const MERGED_BY_HEAD_QUERY: &str = "query($owner:String!,$name:String!,$head:String!){\
repository(owner:$owner,name:$name){merged:pullRequests(headRefName:$head,states:MERGED,\
first:1,orderBy:{field:UPDATED_AT,direction:DESC}){nodes{number headRefOid baseRefName}}}}";
pub(super) const PULL_REQUEST_HEAD_QUERY: &str =
"query($owner:String!,$name:String!,$number:Int!){\
repository(owner:$owner,name:$name){viewerPermission defaultBranchRef{name} \
pullRequest(number:$number){headRefName isCrossRepository maintainerCanModify \
headRepositoryOwner{login} headRepository{name viewerPermission}}}}";
/// A branch's pull requests, newest first, with what a status row needs and the budget left. One
/// point: the check counts come from GitHub's own tally rather than a list of every check.
pub(super) const BRANCH_STATUS_QUERY: &str = "query($owner:String!,$name:String!,$branch:String!){\
repository(owner:$owner,name:$name){defaultBranchRef{name} pullRequests(headRefName:$branch,\
first:10,orderBy:{field:UPDATED_AT,direction:DESC},states:[OPEN,MERGED,CLOSED]){nodes{number \
title url state isDraft headRefOid baseRefName headRepositoryOwner{login} reviewDecision \
commits(last:1){nodes{commit{statusCheckRollup{contexts(first:1){checkRunCountsByState{state \
count} statusContextCountsByState{state count}}}}}} reviewThreads(first:100){totalCount \
nodes{isResolved}}}} stack:pullRequests(states:OPEN,first:100,orderBy:{field:UPDATED_AT,\
direction:DESC}){nodes{number title isDraft headRefName baseRefName headRepositoryOwner{login} \
commits(last:1){nodes{commit{statusCheckRollup{state}}}}}}} rateLimit{remaining resetAt}}";
// === Branch status ===
#[derive(Deserialize)]
pub(super) struct StatusAnswer {
data: StatusData,
}
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
pub(super) struct StatusData {
repository: Option<StatusRepository>,
rate_limit: Option<RateLimitNode>,
}
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
pub(super) struct StatusRepository {
#[serde(default)]
default_branch_ref: Option<BranchName>,
pull_requests: Nodes<StatusNode>,
#[serde(default)]
stack: Option<Nodes<StackNode>>,
}
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
pub(super) struct StatusNode {
number: u64,
title: String,
url: String,
state: String,
is_draft: bool,
head_ref_oid: String,
#[serde(default)]
base_ref_name: String,
head_repository_owner: Option<Login>,
review_decision: Option<String>,
commits: Nodes<CommitNode>,
review_threads: Nodes<ResolvedNode>,
}
#[derive(Deserialize)]
pub(super) struct CommitNode {
commit: StatusCommit,
}
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
pub(super) struct StatusCommit {
status_check_rollup: Option<StatusRollup>,
}
#[derive(Deserialize)]
pub(super) struct StatusRollup {
contexts: RollupContexts,
}
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
pub(super) struct ResolvedNode {
is_resolved: bool,
}
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
pub(super) struct RateLimitNode {
remaining: u32,
reset_at: String,
}
/// The merged pull request an answer names, and the base the stack's bottom was moved from.
pub(super) fn parse_merged_below(
body: &str,
) -> Result<(Option<crate::restack::MergedBelow>, Option<String>), GitHubError> {
#[derive(Deserialize)]
struct Answer {
data: Data,
}
#[derive(Deserialize)]
struct Data {
repository: Option<Repo>,
}
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct Repo {
#[serde(default)]
pull_request: Option<Pr>,
merged: Nodes<Merged>,
}
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct Pr {
timeline_items: Nodes<Changed>,
}
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct Changed {
#[serde(default)]
previous_ref_name: Option<String>,
}
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct Merged {
number: u64,
head_ref_oid: String,
base_ref_name: String,
}
let answer: Answer = serde_json::from_str(body).map_err(GitHubError::Unreadable)?;
let repository = answer.data.repository.ok_or(GitHubError::NotFound)?;
let previous = repository
.pull_request
.and_then(|pr| pr.timeline_items.nodes.into_iter().last())
.and_then(|changed| changed.previous_ref_name);
let merged =
repository.merged.nodes.into_iter().next().map(|merged| crate::restack::MergedBelow {
number: merged.number,
head_oid: merged.head_ref_oid,
base_ref: merged.base_ref_name,
});
Ok((merged, previous))
}
#[derive(Deserialize)]
pub(super) struct HeadAnswer {
data: HeadData,
}
#[derive(Deserialize)]
pub(super) struct HeadData {
repository: Option<HeadRepositoryView>,
}
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
pub(super) struct HeadRepositoryView {
viewer_permission: Option<String>,
default_branch_ref: Option<BranchName>,
pull_request: Option<HeadPullRequest>,
}
#[derive(Deserialize)]
pub(super) struct BranchName {
name: String,
}
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
pub(super) struct HeadPullRequest {
head_ref_name: String,
is_cross_repository: bool,
maintainer_can_modify: bool,
head_repository_owner: Option<IssueAuthor>,
head_repository: Option<HeadRepository>,
}
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
pub(super) struct HeadRepository {
name: String,
viewer_permission: Option<String>,
}
/// Whether GitHub's permission name lets its holder push.
pub(super) fn can_write(permission: Option<&str>) -> bool {
matches!(permission, Some("ADMIN" | "MAINTAIN" | "WRITE"))
}
pub(super) fn parse_pull_request_head(body: &str) -> Result<PullRequestHead, GitHubError> {
let answer: HeadAnswer = serde_json::from_str(body).map_err(GitHubError::Unreadable)?;
let repository = answer.data.repository.ok_or(GitHubError::NotFound)?;
let pull_request = repository.pull_request.ok_or(GitHubError::NotFound)?;
let owner = pull_request.head_repository_owner.map(|owner| owner.login).unwrap_or_default();
let maintainer = can_write(repository.viewer_permission.as_deref());
let (name, push) = match &pull_request.head_repository {
None => (String::new(), PushAccess::HeadRepositoryGone),
Some(head) if can_write(head.viewer_permission.as_deref()) => {
(head.name.clone(), PushAccess::Allowed)
}
// A maintainer may push to a fork's branch only when its author allowed it
Some(head) if pull_request.is_cross_repository && maintainer => (
head.name.clone(),
if pull_request.maintainer_can_modify {
PushAccess::Allowed
} else {
PushAccess::MaintainerEditsOff
},
),
Some(head) => (head.name.clone(), PushAccess::NoWriteAccess),
};
let default_branch = repository.default_branch_ref.map(|branch| branch.name);
let head_ref = pull_request.head_ref_name;
let local_branch = if pull_request.is_cross_repository
&& default_branch.as_deref() == Some(head_ref.as_str())
{
format!("{owner}/{head_ref}")
} else {
head_ref.clone()
};
Ok(PullRequestHead {
head_ref,
owner,
name,
cross_repository: pull_request.is_cross_repository,
local_branch,
push,
})
}
/// The branch's pull request among those whose head has its name, and the budget left.
///
/// Only a pull request from `head_owner`'s repository is the branch's: a fork's branch with the
/// same name is someone else's. An open one wins; otherwise the newest, so a branch whose pull
/// request merged says so rather than looking like it never had one.
pub(super) fn parse_branch_status(
body: &str,
head_ref: &str,
head_owner: &str,
) -> Result<BranchStatus, GitHubError> {
let answer: StatusAnswer = serde_json::from_str(body).map_err(GitHubError::Unreadable)?;
let rate_limit = answer.data.rate_limit.and_then(|limit| {
Some(RateLimit { remaining: limit.remaining, reset_at: rfc3339_seconds(&limit.reset_at)? })
});
let repository = answer.data.repository.ok_or(GitHubError::NotFound)?;
let default_branch = repository.default_branch_ref.map(|branch| branch.name);
let open = repository.stack.map(|stack| stack.nodes).unwrap_or_default();
let candidates: Vec<StatusNode> = repository
.pull_requests
.nodes
.into_iter()
.filter(|node| {
node.head_repository_owner
.as_ref()
.is_some_and(|owner| owner.login.eq_ignore_ascii_case(head_owner))
})
.collect();
let chosen = match candidates.iter().position(|node| node.state == "OPEN") {
Some(open) => candidates.into_iter().nth(open),
None => candidates.into_iter().next(),
};
let pull_request = chosen.map(|node| {
let checks = node
.commits
.nodes
.into_iter()
.next()
.and_then(|commit| commit.commit.status_check_rollup)
.map(|rollup| count_checks(&rollup.contexts))
.unwrap_or_default();
PullRequestStatus {
number: node.number,
title: status_text(&node.title),
url: node.url,
state: match node.state.as_str() {
"MERGED" => PullRequestState::Merged,
"CLOSED" => PullRequestState::Closed,
_ => PullRequestState::Open,
},
draft: node.is_draft,
review_decision: match node.review_decision.as_deref() {
Some("APPROVED") => Some(ReviewDecision::Approved),
Some("CHANGES_REQUESTED") => Some(ReviewDecision::ChangesRequested),
Some("REVIEW_REQUIRED") => Some(ReviewDecision::ReviewRequired),
_ => None,
},
checks,
unresolved_threads: node
.review_threads
.nodes
.iter()
.filter(|thread| !thread.is_resolved)
.count(),
stack: stack_of(
node.number,
head_ref,
&node.base_ref_name,
&open,
head_owner,
default_branch.as_deref(),
),
head_oid: node.head_ref_oid,
}
});
Ok(BranchStatus { pull_request, rate_limit })
}

View File

@@ -0,0 +1,88 @@
//! Stack — the chain of pull requests a branch sits in, as GitHub's answer lays it out.
use super::*;
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
pub(in crate::github::gh) struct StackNode {
pub(in crate::github::gh) number: u64,
pub(in crate::github::gh) title: String,
pub(in crate::github::gh) is_draft: bool,
pub(in crate::github::gh) head_ref_name: String,
pub(in crate::github::gh) base_ref_name: String,
pub(in crate::github::gh) head_repository_owner: Option<Login>,
pub(in crate::github::gh) commits: Nodes<StackCommitNode>,
}
#[derive(Deserialize)]
pub(in crate::github::gh) struct StackCommitNode {
commit: StackCommit,
}
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
pub(in crate::github::gh) struct StackCommit {
status_check_rollup: Option<serde_json::Value>,
}
/// Where the pull request from `head` into `base` sits among the repository's `open` ones, or
/// `None` when nothing is stacked below or above it.
///
/// Only pull requests whose branch is in this repository count, since a fork's branch cannot be
/// another pull request's base. Down, each base is followed to the pull request that has it as
/// its branch, until one has none; up, each branch to the pull request based on it — the most
/// recently updated when several are — which a loop in the data cannot turn into an endless walk.
pub(in crate::github::gh) fn stack_of(
number: u64,
head: &str,
base: &str,
open: &[StackNode],
owner: &str,
default_branch: Option<&str>,
) -> Option<Stack> {
let ours: Vec<&StackNode> = open
.iter()
.filter(|node| node.number != number)
.filter(|node| {
node.head_repository_owner
.as_ref()
.is_some_and(|login| login.login.eq_ignore_ascii_case(owner))
})
.collect();
let entry = |node: &StackNode| StackEntry {
number: node.number,
title: status_text(&node.title),
head_ref: node.head_ref_name.clone(),
draft: node.is_draft,
checked: node
.commits
.nodes
.first()
.is_some_and(|commit| commit.commit.status_check_rollup.is_some()),
};
let mut seen = std::collections::HashSet::from([number]);
let mut below = Vec::new();
let mut trunk = base.to_string();
while let Some(node) = ours.iter().find(|node| node.head_ref_name == trunk) {
if !seen.insert(node.number) {
break;
}
below.push(entry(node));
trunk = node.base_ref_name.clone();
}
below.reverse();
let mut above = Vec::new();
let mut branch = head.to_string();
while let Some(node) = ours.iter().find(|node| node.base_ref_name == branch) {
if !seen.insert(node.number) {
break;
}
above.push(entry(node));
branch = node.head_ref_name.clone();
}
if below.is_empty() && above.is_empty() {
return None;
}
let trunk_is_default = default_branch == Some(trunk.as_str());
Some(Stack { trunk, trunk_is_default, below, above })
}

View File

@@ -0,0 +1,225 @@
//! Checks — what is failing on a commit, with the tail of each failing step's log.
use super::*;
#[async_trait]
impl Checks for GhCli {
async fn failing_checks(
&self,
repository: &Repository,
head_oid: &str,
log_tail: usize,
) -> Result<Vec<FailingCheck>, GitHubError> {
let commit = format!("repos/{}/{}/commits/{head_oid}", repository.owner, repository.name);
let runs_endpoint = format!("{commit}/check-runs?per_page=100");
let mut args = vec!["api", "--paginate"];
push_hostname(&mut args, repository);
args.extend([runs_endpoint.as_str(), "--jq", CHECK_RUNS_JQ]);
let runs = self.gh(&std::env::temp_dir(), &args).await?;
let statuses_endpoint = format!("{commit}/status");
let mut args = vec!["api"];
push_hostname(&mut args, repository);
args.extend([statuses_endpoint.as_str(), "--jq", STATUSES_JQ]);
let statuses = self.gh(&std::env::temp_dir(), &args).await?;
let mut failing = parse_failing_checks(&runs, &statuses)?;
let target = repo_arg(repository);
let mut read = 0;
for (check, job) in &mut failing {
let Some(job) = job else { continue };
if read == MAX_LOGS {
check.log = CheckLog::NotRead;
continue;
}
read += 1;
let args = ["run", "view", "--job", job.as_str(), "--log-failed", "--repo", &target];
check.log = match self.gh(&std::env::temp_dir(), &args).await {
Ok(log) => CheckLog::Steps(parse_failed_log(&log, log_tail)),
Err(error) => CheckLog::Unreadable(error.to_string()),
};
}
Ok(failing.into_iter().map(|(check, _)| check).collect())
}
}
/// The check-run fields a [`FailingCheck`] is read from, one JSON object per line.
pub(super) const CHECK_RUNS_JQ: &str =
".check_runs[] | {name, status, conclusion, html_url, details_url, \
app: .app.slug, title: .output.title, summary: .output.summary}";
/// The commit-status fields a [`FailingCheck`] is read from, one JSON object per line.
pub(super) const STATUSES_JQ: &str = ".statuses[] | {context, state, description, target_url}";
/// How many failing Actions jobs have their logs read in one call. Each is its own download.
pub(super) const MAX_LOGS: usize = 4;
// === Failing checks ===
/// One line of the check-runs listing, as [`CHECK_RUNS_JQ`] shapes it.
#[derive(Deserialize)]
pub(super) struct CheckRunLine {
name: String,
status: String,
conclusion: Option<String>,
html_url: String,
details_url: Option<String>,
app: Option<String>,
title: Option<String>,
summary: Option<String>,
}
/// One line of the combined status, as [`STATUSES_JQ`] shapes it.
#[derive(Deserialize)]
pub(super) struct StatusLine {
context: String,
state: String,
description: Option<String>,
target_url: Option<String>,
}
/// The failing checks on a commit, each with the Actions job whose log would explain it.
///
/// Check runs first, in GitHub's order, then commit statuses. A check still running has not
/// failed, whatever else it says.
pub(super) fn parse_failing_checks(
runs: &str,
statuses: &str,
) -> Result<Vec<(FailingCheck, Option<String>)>, GitHubError> {
let mut failing = Vec::new();
for run in parse_lines::<CheckRunLine>(runs)? {
let outcome = run.conclusion.unwrap_or_default();
let failed = matches!(
outcome.as_str(),
"failure" | "timed_out" | "cancelled" | "action_required" | "startup_failure" | "stale"
);
if run.status != "completed" || !failed {
continue;
}
let job = (run.app.as_deref() == Some("github-actions"))
.then(|| run.details_url.as_deref().and_then(actions_job))
.flatten();
// Filtered one at a time, or an empty title would win and hide a real summary
let written = |text: &Option<String>| text.clone().filter(|text| !text.trim().is_empty());
let summary = written(&run.title).or_else(|| written(&run.summary));
failing.push((
FailingCheck {
name: status_text(&run.name),
outcome,
url: run.html_url,
summary: summary.map(|text| status_text(&text)),
log: CheckLog::NotActions,
},
job,
));
}
for status in parse_lines::<StatusLine>(statuses)? {
if !matches!(status.state.as_str(), "failure" | "error") {
continue;
}
failing.push((
FailingCheck {
name: status_text(&status.context),
outcome: status.state,
url: status.target_url.unwrap_or_default(),
summary: status
.description
.filter(|text| !text.trim().is_empty())
.map(|text| status_text(&text)),
log: CheckLog::NotActions,
},
None,
));
}
Ok(failing)
}
/// The job id in an Actions job's address: `…/actions/runs/<run>/job/<job>`.
pub(super) fn actions_job(url: &str) -> Option<String> {
let (_, job) = url.split_once("/actions/runs/")?.1.split_once("/job/")?;
let job = job.split(['/', '?', '#']).next()?;
(!job.is_empty() && job.bytes().all(|byte| byte.is_ascii_digit())).then(|| job.to_string())
}
/// The failing steps in `gh run view --log-failed` output, each cut to its last `tail` lines.
///
/// Every line is `job<TAB>step<TAB>timestamp text`. The timestamp and terminal color codes go,
/// since a reader of the tail needs neither; steps keep the order they first appear in.
pub(super) fn parse_failed_log(log: &str, tail: usize) -> Vec<FailedStep> {
let mut steps: Vec<(String, Vec<String>)> = Vec::new();
for line in log.lines() {
let mut fields = line.splitn(3, '\t');
let (Some(_job), Some(step), Some(text)) = (fields.next(), fields.next(), fields.next())
else {
continue;
};
let text = strip_ansi(without_timestamp(text));
match steps.last_mut() {
Some((name, lines)) if name == step => lines.push(text),
_ => steps.push((step.to_string(), vec![text])),
}
}
steps
.into_iter()
.map(|(name, mut lines)| {
let error_end = lines
.iter()
.rposition(|line| line.starts_with("##[error]"))
.map_or(lines.len(), |last| last + 1);
let after = lines.len() - error_end;
lines.truncate(error_end);
let mut blank = 0;
while lines.last().is_some_and(|line| line.trim().is_empty()) {
lines.pop();
blank += 1;
}
let omitted = lines.len().saturating_sub(tail);
FailedStep { name, tail: lines.split_off(omitted), omitted, after: after + blank }
})
.collect()
}
/// A log line without the `2026-09-23T00:21:48.1862910Z ` Actions puts in front of it.
///
/// A step's first line can carry a byte-order mark ahead of the timestamp, left over from the log
/// file it was cut from.
pub(super) fn without_timestamp(text: &str) -> &str {
let text = text.strip_prefix('\u{feff}').unwrap_or(text);
match text.split_once(' ') {
Some((stamp, rest))
if stamp.ends_with('Z') && stamp.as_bytes().first().is_some_and(u8::is_ascii_digit) =>
{
rest
}
_ => text,
}
}
/// `text` without terminal color sequences (`ESC [ … letter`).
///
/// Actions logs spell the escape in caret notation, as the two characters `^[`, so both forms go.
pub(super) fn strip_ansi(text: &str) -> String {
let mut out = String::with_capacity(text.len());
let mut chars = text.chars().peekable();
while let Some(character) = chars.next() {
let escape = match character {
'\u{1b}' => true,
'^' if chars.peek() == Some(&'[') => {
chars.next();
true
}
_ => false,
};
if escape && chars.peek() == Some(&'[') {
chars.next();
for next in chars.by_ref() {
if next.is_ascii_alphabetic() {
break;
}
}
continue;
}
out.push(character);
}
out
}

View File

@@ -0,0 +1,268 @@
//! Conversation query — everything said about a pull request or an issue, in one request.
//!
//! The description, the comments, each review that said something and its verdict, and every
//! review thread, oldest first. About one point. A minimized comment was hidden by someone with
//! the standing to, and a review submitted with nothing but replies in threads has nothing to say
//! of its own; both are left out here, and the replies are in their threads.
use serde::Deserialize;
use super::threads::{review_thread, ThreadNode};
use super::{rfc3339_seconds, Connection};
use crate::github::overview::{ConversationEntry, Verdict};
use crate::github::{Author, ConversationComment, GitHubError};
pub(super) const PULL_REQUEST_CONVERSATION_QUERY: &str = "query($owner:String!,$name:String!,\
$number:Int!){repository(owner:$owner,name:$name){pullRequest(number:$number){\
author{__typename login} body createdAt viewerDidAuthor \
comments(last:50){nodes{id author{__typename login} body createdAt url isMinimized \
viewerDidAuthor}} reviews(last:50){nodes{id author{__typename login} body state submittedAt \
url viewerDidAuthor comments{totalCount}}} reviewThreads(first:100){totalCount nodes{id \
isResolved isOutdated path line startLine diffSide subjectType viewerCanReply \
viewerCanResolve comments(first:20){totalCount nodes{author{login} body createdAt url \
diffHunk}}}}}} rateLimit{cost remaining}}";
pub(super) const ISSUE_CONVERSATION_QUERY: &str = "query($owner:String!,$name:String!,\
$number:Int!){repository(owner:$owner,name:$name){issue(number:$number){\
author{__typename login} body createdAt viewerDidAuthor \
comments(last:50){nodes{id author{__typename login} body createdAt url isMinimized \
viewerDidAuthor}}}} rateLimit{cost remaining}}";
#[derive(Deserialize)]
struct Answer {
data: Data,
}
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct Data {
repository: Option<RepositoryNode>,
}
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct RepositoryNode {
pull_request: Option<Subject>,
issue: Option<Subject>,
}
/// A pull request or an issue: the same fields, threads and reviews only on a pull request.
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct Subject {
author: Option<Actor>,
#[serde(default)]
body: String,
created_at: String,
comments: Nodes<CommentNode>,
#[serde(default)]
reviews: Option<Nodes<ReviewNode>>,
#[serde(default)]
review_threads: Option<Connection<ThreadNode>>,
}
#[derive(Deserialize)]
struct Nodes<T> {
nodes: Vec<T>,
}
#[derive(Deserialize)]
struct Actor {
#[serde(rename = "__typename", default)]
typename: String,
login: String,
}
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct CommentNode {
id: String,
author: Option<Actor>,
#[serde(default)]
body: String,
created_at: String,
#[serde(default)]
url: String,
#[serde(default)]
is_minimized: bool,
#[serde(default)]
viewer_did_author: bool,
}
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct ReviewNode {
id: String,
author: Option<Actor>,
#[serde(default)]
body: String,
state: String,
submitted_at: Option<String>,
#[serde(default)]
url: String,
#[serde(default)]
viewer_did_author: bool,
comments: Count,
}
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct Count {
total_count: usize,
}
fn comment(
id: String,
author: Option<Actor>,
body: String,
created_at: String,
url: String,
mine: bool,
) -> ConversationComment {
let (author, bot) =
author.map_or((String::new(), false), |actor| (actor.login, actor.typename == "Bot"));
ConversationComment { id, author, bot, mine, body, created_at, url }
}
/// Everything said, oldest first, from the answer to either conversation query.
pub(super) fn parse_conversation(body: &str) -> Result<Vec<ConversationEntry>, GitHubError> {
let answer: Answer = serde_json::from_str(body).map_err(GitHubError::Unreadable)?;
let repository = answer.data.repository.ok_or(GitHubError::NotFound)?;
let subject = repository.pull_request.or(repository.issue).ok_or(GitHubError::NotFound)?;
// Each entry with when it was said, to sort on: RFC 3339 in one zone sorts as text
let mut said: Vec<(String, ConversationEntry)> = Vec::new();
let author = subject.author.map_or_else(
|| Author { login: String::new(), bot: false },
|actor| Author { bot: actor.typename == "Bot", login: actor.login },
);
said.push((
subject.created_at.clone(),
ConversationEntry::Opening {
author,
body: subject.body,
at: rfc3339_seconds(&subject.created_at).unwrap_or_default(),
},
));
for node in subject.comments.nodes.into_iter().filter(|node| !node.is_minimized) {
let at = node.created_at.clone();
let entry = comment(
node.id,
node.author,
node.body,
node.created_at,
node.url,
node.viewer_did_author,
);
said.push((at, ConversationEntry::Comment(entry)));
}
for node in subject.reviews.map(|reviews| reviews.nodes).unwrap_or_default() {
let verdict = match node.state.as_str() {
"APPROVED" => Verdict::Approved,
"CHANGES_REQUESTED" => Verdict::ChangesRequested,
"DISMISSED" => Verdict::Dismissed,
"COMMENTED" => Verdict::Commented,
// A pending review is someone's unsent draft
_ => continue,
};
// A verdict is news even without words; a bare comment-review's words are in its threads
if node.body.trim().is_empty() && verdict == Verdict::Commented {
continue;
}
let at = node.submitted_at.unwrap_or_default();
let entry =
comment(node.id, node.author, node.body, at.clone(), node.url, node.viewer_did_author);
said.push((
at,
ConversationEntry::Review {
comment: entry,
verdict,
line_comments: node.comments.total_count,
},
));
}
let threads = subject.review_threads.map(|threads| threads.nodes).unwrap_or_default();
for node in threads {
let thread = review_thread(node);
let at = thread.comments.first().map(|first| first.created_at.clone()).unwrap_or_default();
said.push((at, ConversationEntry::Thread(thread)));
}
// Stable, so the description stays first when something shares its second
said.sort_by(|a, b| a.0.cmp(&b.0));
Ok(said.into_iter().map(|(_, entry)| entry).collect())
}
#[cfg(test)]
mod tests {
use super::*;
/// `cli/cli#13982`: the description first, then everything in the order it was said — a bot's
/// long review, a reviewer asking for changes, fourteen threads — and the bare comment-reviews
/// that only carried thread replies left out.
#[test]
fn a_pull_request_conversation_reads_in_order() {
let entries =
parse_conversation(include_str!("../fixtures/conversation_pull_request.json"))
.expect("the fixture parses");
assert!(
matches!(&entries[0], ConversationEntry::Opening { author, .. } if author.login == "offbyone")
);
let reviews: Vec<(&str, Verdict)> = entries
.iter()
.filter_map(|entry| match entry {
ConversationEntry::Review { comment, verdict, .. } => {
Some((comment.author.as_str(), *verdict))
}
_ => None,
})
.collect();
assert_eq!(
reviews,
[
("copilot-pull-request-reviewer", Verdict::Commented),
("BagToad", Verdict::ChangesRequested)
]
);
let bot = entries.iter().find_map(|entry| match entry {
ConversationEntry::Review { comment, .. } if comment.bot => Some(comment),
_ => None,
});
assert!(bot.is_some(), "the copilot reviewer is a bot");
let threads = entries.iter().filter(|e| matches!(e, ConversationEntry::Thread(_))).count();
assert_eq!(threads, 14);
let stamps: Vec<u64> = entries
.iter()
.filter_map(|entry| match entry {
ConversationEntry::Comment(c) | ConversationEntry::Review { comment: c, .. } => {
rfc3339_seconds(&c.created_at)
}
_ => None,
})
.collect();
assert!(stamps.windows(2).all(|pair| pair[0] <= pair[1]), "oldest first");
}
/// An issue's conversation: its description, then its comments, a bot's among them.
#[test]
fn an_issue_conversation_is_its_comments() {
let entries = parse_conversation(include_str!("../fixtures/conversation_issue.json"))
.expect("parses");
assert!(matches!(&entries[0], ConversationEntry::Opening { .. }));
let comments: Vec<(&str, bool)> = entries
.iter()
.filter_map(|entry| match entry {
ConversationEntry::Comment(comment) => Some((comment.author.as_str(), comment.bot)),
_ => None,
})
.collect();
assert_eq!(comments.len(), 5);
assert!(comments.contains(&("github-actions", true)), "{comments:?}");
assert!(!entries.iter().any(|entry| matches!(entry, ConversationEntry::Thread(_))));
}
#[test]
fn a_missing_subject_is_not_found() {
let body = r#"{"data":{"repository":{"pullRequest":null}}}"#;
assert!(matches!(parse_conversation(body), Err(GitHubError::NotFound)));
}
}

View File

@@ -0,0 +1,122 @@
//! Discovery — the signed-in account, the repository a checkout belongs to, and search.
use super::*;
#[async_trait]
impl Discovery for GhCli {
async fn account(&self, host: Option<&str>) -> Result<Account, GitHubError> {
let mut args = vec!["auth", "status", "--json", "hosts"];
if let Some(host) = host {
args.extend(["--hostname", host]);
}
// Signed out still exits zero with `--json`, so the answer is read from the body
let cwd = std::env::temp_dir();
let body = self.gh(&cwd, &args).await?;
parse_account(&body, host)
}
async fn repository(&self, cwd: &Path) -> Result<Repository, GitHubError> {
let body =
self.gh(cwd, &["repo", "view", "--json", "nameWithOwner,url,defaultBranchRef"]).await?;
let mut repository = parse_repository(&body)?;
repository.remote = matching_remote(
&Self::remotes(cwd).await,
&repository.host,
&repository.owner,
&repository.name,
);
Ok(repository)
}
async fn search(
&self,
host: &str,
query: &str,
after: Option<&str>,
) -> Result<SearchPage, GitHubError> {
let graphql = format!("query={}", search::SEARCH_QUERY);
let search = format!("q={query}");
let after = after.map(|cursor| format!("after={cursor}"));
let mut args = vec!["api", "graphql"];
if host != "github.com" && !host.is_empty() {
args.extend(["--hostname", host]);
}
args.extend(["-f", graphql.as_str(), "-f", search.as_str()]);
// Left out, `$after` is null, which is the first page
if let Some(after) = after.as_deref() {
args.extend(["-f", after]);
}
let body = self.gh(&std::env::temp_dir(), &args).await?;
parse_search(&body)
}
}
/// The body of `gh auth status --json hosts`.
#[derive(Deserialize)]
pub(super) struct AuthStatus {
hosts: std::collections::BTreeMap<String, Vec<AuthEntry>>,
}
#[derive(Deserialize)]
pub(super) struct AuthEntry {
state: String,
#[serde(default)]
active: bool,
host: String,
#[serde(default)]
login: String,
}
/// The active, working account on `host`, or on any host when `host` is `None`.
pub(super) fn parse_account(body: &str, host: Option<&str>) -> Result<Account, GitHubError> {
let status: AuthStatus = serde_json::from_str(body).map_err(GitHubError::Unreadable)?;
status
.hosts
.values()
.flatten()
.filter(|entry| host.is_none_or(|host| entry.host.eq_ignore_ascii_case(host)))
.find(|entry| entry.active && entry.state == "success" && !entry.login.is_empty())
.map(|entry| Account { host: entry.host.clone(), login: entry.login.clone() })
.ok_or_else(|| GitHubError::NotAuthenticated { host: host.map(str::to_string) })
}
/// The body of `gh repo view --json nameWithOwner,url,defaultBranchRef`.
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
pub(super) struct RepoView {
name_with_owner: String,
url: String,
default_branch_ref: Option<BranchRef>,
}
#[derive(Deserialize)]
pub(super) struct BranchRef {
name: String,
}
/// The repository `gh repo view` described, with no remote chosen yet.
pub(super) fn parse_repository(body: &str) -> Result<Repository, GitHubError> {
let view: RepoView = serde_json::from_str(body).map_err(GitHubError::Unreadable)?;
let (owner, name) =
view.name_with_owner.split_once('/').ok_or_else(|| GitHubError::Failed {
message: format!(
"gh named the repository `{}`, which is not owner/name",
view.name_with_owner
),
})?;
let host =
parse_remote_url(&view.url).map(|url| url.host).ok_or_else(|| GitHubError::Failed {
message: format!("gh gave the repository URL `{}`, which names no host", view.url),
})?;
Ok(Repository {
host,
owner: owner.to_string(),
name: name.to_string(),
// An empty repository has no default branch yet; `main` is what GitHub will create
default_branch: view
.default_branch_ref
.map(|branch| branch.name)
.unwrap_or_else(|| "main".into()),
remote: None,
})
}

View File

@@ -0,0 +1,192 @@
//! Issue overview query — one issue as its detail shows it, in one GraphQL request.
//!
//! Who it is assigned to, the milestone it is in, and the pull requests that would close it —
//! GitHub's Development list, closed attempts included, since a closed one is history worth seeing
//! before starting another. About one point of the hourly budget.
use serde::Deserialize;
use super::{rfc3339_seconds, Login, Nodes};
use crate::github::overview::{IssueOverview, Label, LinkedPullRequest};
use crate::github::{Author, GitHubError, PullRequestState};
pub(super) const ISSUE_OVERVIEW_QUERY: &str = "query($owner:String!,$name:String!,$number:Int!){\
repository(owner:$owner,name:$name){nameWithOwner issue(number:$number){number title body \
url state updatedAt author{__typename login} labels(first:10){nodes{name color}} \
assignees(first:10){nodes{login}} milestone{title} \
closedByPullRequestsReferences(first:10,includeClosedPrs:true){nodes{number title state \
isDraft author{login}}} comments{totalCount}}} rateLimit{cost remaining}}";
#[derive(Deserialize)]
struct Answer {
data: Data,
}
#[derive(Deserialize)]
struct Data {
repository: Option<RepositoryNode>,
}
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct RepositoryNode {
name_with_owner: String,
issue: Option<IssueNode>,
}
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct IssueNode {
number: u64,
title: String,
#[serde(default)]
body: String,
url: String,
state: String,
updated_at: String,
author: Option<Actor>,
labels: Nodes<LabelNode>,
assignees: Nodes<Login>,
milestone: Option<Milestone>,
closed_by_pull_requests_references: Nodes<Linked>,
comments: Count,
}
#[derive(Deserialize)]
struct Actor {
#[serde(rename = "__typename")]
typename: String,
login: String,
}
#[derive(Deserialize)]
struct LabelNode {
name: String,
color: String,
}
#[derive(Deserialize)]
struct Milestone {
title: String,
}
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct Linked {
number: u64,
title: String,
state: String,
is_draft: bool,
author: Option<Login>,
}
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct Count {
total_count: usize,
}
fn state(state: &str) -> PullRequestState {
match state {
"MERGED" => PullRequestState::Merged,
"CLOSED" => PullRequestState::Closed,
_ => PullRequestState::Open,
}
}
/// The overview in `body`, the answer to [`ISSUE_OVERVIEW_QUERY`].
pub(super) fn parse_issue_overview(body: &str) -> Result<IssueOverview, GitHubError> {
let answer: Answer = serde_json::from_str(body).map_err(GitHubError::Unreadable)?;
let repository = answer.data.repository.ok_or(GitHubError::NotFound)?;
let node = repository.issue.ok_or(GitHubError::NotFound)?;
Ok(IssueOverview {
number: node.number,
title: node.title,
body: node.body,
url: node.url,
repository: repository.name_with_owner,
author: node.author.map_or_else(
|| Author { login: String::new(), bot: false },
|actor| Author { bot: actor.typename == "Bot", login: actor.login },
),
state: state(&node.state),
updated_at: rfc3339_seconds(&node.updated_at).unwrap_or_default(),
labels: node
.labels
.nodes
.into_iter()
.map(|label| Label { name: label.name, color: label.color })
.collect(),
assignees: node.assignees.nodes.into_iter().map(|login| login.login).collect(),
milestone: node.milestone.map(|milestone| milestone.title),
linked: node
.closed_by_pull_requests_references
.nodes
.into_iter()
.map(|linked| LinkedPullRequest {
number: linked.number,
title: linked.title,
state: state(&linked.state),
draft: linked.is_draft,
author: linked.author.map(|author| author.login).unwrap_or_default(),
closes: true,
})
.collect(),
// The description, then every comment: what Conversation lists
conversation_count: 1 + node.comments.total_count,
})
}
#[cfg(test)]
mod tests {
use super::*;
fn fixture(name: &str) -> IssueOverview {
let body = match name {
"linked" => include_str!("../fixtures/issue_overview_linked.json"),
"closed" => include_str!("../fixtures/issue_overview_closed_pull_request.json"),
"assigned" => include_str!("../fixtures/issue_overview_assigned.json"),
"milestone" => include_str!("../fixtures/issue_overview_milestone.json"),
other => panic!("no fixture {other}"),
};
parse_issue_overview(body).expect("the fixture parses")
}
/// An open pull request that would close it is named with who opened it: somebody is on it.
#[test]
fn an_issue_names_the_pull_request_that_would_close_it() {
let issue = fixture("linked");
assert_eq!((issue.number, issue.repository.as_str()), (14_015, "cli/cli"));
assert_eq!(issue.linked.len(), 1);
let linked = &issue.linked[0];
assert_eq!((linked.number, linked.state), (14_017, PullRequestState::Open));
assert!(linked.closes && !linked.author.is_empty());
assert!(issue.assignees.is_empty() && issue.milestone.is_none());
assert_eq!(issue.labels.len(), 4);
}
/// A closed attempt is history, kept: the next one should know it was tried.
#[test]
fn a_closed_attempt_is_kept() {
let issue = fixture("closed");
assert!(issue
.linked
.iter()
.any(|linked| linked.number == 13_480 && linked.state == PullRequestState::Closed));
}
#[test]
fn assignees_and_the_milestone_are_read() {
assert_eq!(fixture("assigned").assignees, ["babakks"]);
let issue = fixture("milestone");
assert_eq!(issue.milestone.as_deref(), Some("1.101.0"));
assert_eq!(issue.assignees, ["clarfonthey"]);
assert!(issue.conversation_count >= 1);
}
#[test]
fn a_missing_issue_is_not_found() {
let body = r#"{"data":{"repository":{"nameWithOwner":"a/b","issue":null}}}"#;
assert!(matches!(parse_issue_overview(body), Err(GitHubError::NotFound)));
}
}

View File

@@ -0,0 +1,445 @@
//! Overview query — one pull request as its detail shows it, in one GraphQL request.
//!
//! What GitHub knows about whether it can merge (`mergeStateStatus`), who was asked to review and
//! what each reviewer last said, which checks are failing and whether branch protection requires
//! them, and what the signed-in account may do with it. About one point of the hourly budget.
use serde::Deserialize;
use super::{count_checks, rfc3339_seconds, Connection, Login, Nodes, RollupContexts};
use crate::github::overview::{
FailingCheckName, Label, MergeMethod, MergeSettings, MergeStatus, PullRequestOverview,
Reviewer, ReviewerKind, Verdict, Viewer,
};
use crate::github::{Author, GitHubError, PullRequestState, ReviewDecision};
/// The query. `isRequired` takes the pull request's number because a check is required of a pull
/// request by the rules on its base, not of a commit.
pub(super) const PULL_REQUEST_OVERVIEW_QUERY: &str = "query($owner:String!,$name:String!,\
$number:Int!){repository(owner:$owner,name:$name){nameWithOwner viewerPermission \
mergeCommitAllowed squashMergeAllowed rebaseMergeAllowed viewerDefaultMergeMethod \
deleteBranchOnMerge pullRequest(number:$number){id number viewerCanEnableAutoMerge \
viewerCanDisableAutoMerge autoMergeRequest{mergeMethod} \
title body url state isDraft baseRefName headRefName headRefOid additions deletions \
changedFiles updatedAt mergeStateStatus mergeable reviewDecision viewerDidAuthor isCrossRepository \
maintainerCanModify headRepository{viewerPermission} author{__typename login} \
labels(first:10){nodes{name color}} commitCount:commits{totalCount} \
head:commits(last:1){nodes{commit{statusCheckRollup{contexts(first:100){\
checkRunCountsByState{state count} statusContextCountsByState{state count} \
nodes{__typename ...on CheckRun{name conclusion status isRequired(pullRequestNumber:$number)} \
...on StatusContext{context state isRequired(pullRequestNumber:$number)}}}}}}} \
reviewRequests(first:20){nodes{requestedReviewer{__typename ...on User{login} \
...on Bot{login} ...on Mannequin{login} ...on Team{slug organization{login}}}}} \
latestOpinionatedReviews(first:20){nodes{author{__typename login} state submittedAt}} \
latestReviews(first:20){nodes{author{__typename login} state submittedAt}} \
reviewThreads(first:100){totalCount nodes{isResolved}} comments{totalCount} \
reviews{totalCount}}} rateLimit{cost remaining resetAt}}";
#[derive(Deserialize)]
struct Answer {
data: Data,
}
#[derive(Deserialize)]
struct Data {
repository: Option<RepositoryNode>,
}
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct RepositoryNode {
name_with_owner: String,
viewer_permission: Option<String>,
merge_commit_allowed: bool,
squash_merge_allowed: bool,
rebase_merge_allowed: bool,
viewer_default_merge_method: Option<String>,
#[serde(default)]
delete_branch_on_merge: bool,
pull_request: Option<PullRequestNode>,
}
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct AutoMergeNode {
merge_method: String,
}
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct PullRequestNode {
number: u64,
#[serde(default)]
id: String,
#[serde(default)]
viewer_can_enable_auto_merge: bool,
#[serde(default)]
viewer_can_disable_auto_merge: bool,
auto_merge_request: Option<AutoMergeNode>,
title: String,
#[serde(default)]
body: String,
url: String,
state: String,
is_draft: bool,
base_ref_name: String,
head_ref_name: String,
head_ref_oid: String,
additions: u64,
deletions: u64,
changed_files: u64,
updated_at: String,
merge_state_status: String,
mergeable: String,
review_decision: Option<String>,
viewer_did_author: bool,
is_cross_repository: bool,
maintainer_can_modify: bool,
head_repository: Option<PermissionNode>,
author: Option<Actor>,
labels: Nodes<LabelNode>,
commit_count: Count,
head: Nodes<HeadCommit>,
review_requests: Nodes<RequestNode>,
latest_opinionated_reviews: Nodes<ReviewNode>,
latest_reviews: Nodes<ReviewNode>,
review_threads: Connection<ResolvedThread>,
comments: Count,
reviews: Count,
}
/// A connection asked only how long it is.
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct Count {
total_count: usize,
}
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct PermissionNode {
viewer_permission: Option<String>,
}
/// A user, bot or mannequin; the typename is what tells a bot from a person.
#[derive(Deserialize)]
struct Actor {
#[serde(rename = "__typename")]
typename: String,
login: String,
}
#[derive(Deserialize)]
struct LabelNode {
name: String,
color: String,
}
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct HeadCommit {
commit: HeadRollup,
}
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct HeadRollup {
status_check_rollup: Option<Rollup>,
}
#[derive(Deserialize)]
struct Rollup {
contexts: Contexts,
}
#[derive(Deserialize)]
struct Contexts {
#[serde(flatten)]
counts: RollupContexts,
#[serde(default)]
nodes: Vec<CheckNode>,
}
/// A check run or a commit status; each names itself and says how it ended its own way.
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct CheckNode {
name: Option<String>,
context: Option<String>,
conclusion: Option<String>,
state: Option<String>,
#[serde(default)]
is_required: bool,
}
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct RequestNode {
/// Absent for a team the signed-in account cannot see
requested_reviewer: Option<Requested>,
}
#[derive(Deserialize)]
struct Requested {
#[serde(rename = "__typename")]
typename: String,
login: Option<String>,
slug: Option<String>,
organization: Option<Login>,
}
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct ReviewNode {
author: Option<Actor>,
state: String,
submitted_at: Option<String>,
}
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct ResolvedThread {
is_resolved: bool,
}
fn pull_request_state(state: &str) -> PullRequestState {
match state {
"MERGED" => PullRequestState::Merged,
"CLOSED" => PullRequestState::Closed,
_ => PullRequestState::Open,
}
}
fn review_decision(decision: Option<&str>) -> Option<ReviewDecision> {
match decision {
Some("APPROVED") => Some(ReviewDecision::Approved),
Some("CHANGES_REQUESTED") => Some(ReviewDecision::ChangesRequested),
Some("REVIEW_REQUIRED") => Some(ReviewDecision::ReviewRequired),
_ => None,
}
}
/// What the viewer may do to the pull request: push to its branch, and merge it.
///
/// Args: `(base permission, head repository permission, (cross repository, maintainers may
/// modify, viewer authored it))`.
fn viewer_rights(
base: Option<&str>,
head: Option<&str>,
(cross_repository, maintainer_can_modify, authored): (bool, bool, bool),
) -> Viewer {
let writes =
|permission: Option<&str>| matches!(permission, Some("WRITE" | "MAINTAIN" | "ADMIN"));
let base_writable = writes(base);
let can_push = match cross_repository {
false => base_writable,
true => writes(head) || (maintainer_can_modify && base_writable),
};
Viewer { author: authored, can_push, can_merge: base_writable }
}
/// The merge methods the repository allows, in the order GitHub's own menu lists them.
///
/// Args: `[merge commit, squash, rebase]` allowed.
fn allowed_merge_methods([merge, squash, rebase]: [bool; 3]) -> Vec<MergeMethod> {
[(merge, MergeMethod::Merge), (squash, MergeMethod::Squash), (rebase, MergeMethod::Rebase)]
.into_iter()
.filter_map(|(allowed, method)| allowed.then_some(method))
.collect()
}
/// The overview in `body`, the answer to [`PULL_REQUEST_OVERVIEW_QUERY`].
pub(super) fn parse_pull_request_overview(body: &str) -> Result<PullRequestOverview, GitHubError> {
let answer: Answer = serde_json::from_str(body).map_err(GitHubError::Unreadable)?;
let repository = answer.data.repository.ok_or(GitHubError::NotFound)?;
let node = repository.pull_request.ok_or(GitHubError::NotFound)?;
let rollup =
node.head.nodes.into_iter().next().and_then(|head| head.commit.status_check_rollup);
let (checks, failing) = match rollup {
Some(rollup) => (count_checks(&rollup.contexts.counts), failing(rollup.contexts.nodes)),
None => Default::default(),
};
let viewer = viewer_rights(
repository.viewer_permission.as_deref(),
node.head_repository.as_ref().and_then(|head| head.viewer_permission.as_deref()),
(node.is_cross_repository, node.maintainer_can_modify, node.viewer_did_author),
);
let author = node.author.map_or_else(
|| Author { login: String::new(), bot: false },
|actor| Author { bot: actor.typename == "Bot", login: actor.login },
);
let merge_methods = allowed_merge_methods([
repository.merge_commit_allowed,
repository.squash_merge_allowed,
repository.rebase_merge_allowed,
]);
let threads = node.review_threads.total_count;
Ok(PullRequestOverview {
number: node.number,
node_id: node.id,
title: node.title,
body: node.body,
url: node.url,
repository: repository.name_with_owner,
author,
state: pull_request_state(&node.state),
draft: node.is_draft,
base_ref: node.base_ref_name,
head_ref: node.head_ref_name,
head_oid: node.head_ref_oid,
cross_repository: node.is_cross_repository,
additions: node.additions,
deletions: node.deletions,
changed_files: node.changed_files,
commits: node.commit_count.total_count as u64,
updated_at: rfc3339_seconds(&node.updated_at).unwrap_or_default(),
labels: node
.labels
.nodes
.into_iter()
.map(|label| Label { name: label.name, color: label.color })
.collect(),
merge_status: merge_status(&node.merge_state_status, &node.mergeable),
review_decision: review_decision(node.review_decision.as_deref()),
reviewers: reviewers(
node.latest_opinionated_reviews.nodes,
node.latest_reviews.nodes,
node.review_requests.nodes,
),
checks,
failing,
unresolved_threads: node
.review_threads
.nodes
.iter()
.filter(|thread| !thread.is_resolved)
.count(),
stack: None,
viewer,
merge_methods,
merge_settings: MergeSettings {
last_method: repository.viewer_default_merge_method.as_deref().and_then(merge_method),
deletes_branch: repository.delete_branch_on_merge,
can_auto_merge: node.viewer_can_enable_auto_merge,
can_cancel_auto_merge: node.viewer_can_disable_auto_merge,
auto_merge: node
.auto_merge_request
.and_then(|request| merge_method(&request.merge_method)),
},
// The description, then every comment, review and thread: what Conversation lists
conversation_count: 1 + node.comments.total_count + node.reviews.total_count + threads,
})
}
/// GitHub's `PullRequestMergeMethod`.
fn merge_method(word: &str) -> Option<MergeMethod> {
match word {
"MERGE" => Some(MergeMethod::Merge),
"SQUASH" => Some(MergeMethod::Squash),
"REBASE" => Some(MergeMethod::Rebase),
_ => None,
}
}
/// GitHub's word for whether it can merge. A conflict reported by `mergeable` is a conflict even
/// while `mergeStateStatus` is still catching up.
fn merge_status(state: &str, mergeable: &str) -> MergeStatus {
if mergeable == "CONFLICTING" {
return MergeStatus::Dirty;
}
match state {
"CLEAN" => MergeStatus::Clean,
"HAS_HOOKS" => MergeStatus::HasHooks,
"UNSTABLE" => MergeStatus::Unstable,
"BEHIND" => MergeStatus::Behind,
"BLOCKED" => MergeStatus::Blocked,
"DIRTY" => MergeStatus::Dirty,
"DRAFT" => MergeStatus::Draft,
_ => MergeStatus::Unknown,
}
}
/// The checks that failed, required ones first, each by the name GitHub lists it under.
fn failing(nodes: Vec<CheckNode>) -> Vec<FailingCheckName> {
let mut failed: Vec<FailingCheckName> = nodes
.into_iter()
.filter(|node| {
let run = matches!(
node.conclusion.as_deref(),
Some(
"FAILURE"
| "TIMED_OUT"
| "CANCELLED"
| "ACTION_REQUIRED"
| "STARTUP_FAILURE"
| "STALE"
)
);
let status = matches!(node.state.as_deref(), Some("FAILURE" | "ERROR"));
run || status
})
.filter_map(|node| {
let name = node.name.or(node.context)?;
Some(FailingCheckName { name, required: node.is_required })
})
.collect();
// Stable, so checks keep GitHub's order within each group
failed.sort_by_key(|check| !check.required);
failed
}
/// Everyone with a say: each reviewer's latest verdict, then whoever is asked and has not answered.
///
/// An opinionated review — approval or changes requested — is what counts toward merging, so it
/// wins over a later comment from the same person. A request to someone who already reviewed is a
/// re-request, which GitHub treats as pending again, so it wins over both.
fn reviewers(
opinionated: Vec<ReviewNode>,
latest: Vec<ReviewNode>,
requested: Vec<RequestNode>,
) -> Vec<Reviewer> {
let mut reviewers: Vec<Reviewer> = Vec::new();
for review in opinionated.into_iter().chain(latest) {
let Some(actor) = review.author else { continue };
if reviewers.iter().any(|known| known.login == actor.login) {
continue;
}
let verdict = match review.state.as_str() {
"APPROVED" => Verdict::Approved,
"CHANGES_REQUESTED" => Verdict::ChangesRequested,
"DISMISSED" => Verdict::Dismissed,
"COMMENTED" => Verdict::Commented,
_ => continue,
};
reviewers.push(Reviewer {
kind: if actor.typename == "Bot" { ReviewerKind::Bot } else { ReviewerKind::User },
login: actor.login,
verdict,
at: review.submitted_at.as_deref().and_then(rfc3339_seconds),
});
}
for request in requested {
let Some(requested) = request.requested_reviewer else { continue };
let (login, kind) = match requested.typename.as_str() {
"Team" => {
let organization = requested.organization.map(|org| org.login).unwrap_or_default();
let slug = requested.slug.unwrap_or_default();
(format!("{organization}/{slug}"), ReviewerKind::Team)
}
"Bot" => (requested.login.unwrap_or_default(), ReviewerKind::Bot),
_ => (requested.login.unwrap_or_default(), ReviewerKind::User),
};
if login.is_empty() || login == "/" {
continue;
}
match reviewers.iter_mut().find(|known| known.login == login) {
Some(known) => known.verdict = Verdict::Requested,
None => reviewers.push(Reviewer { login, kind, verdict: Verdict::Requested, at: None }),
}
}
reviewers
}
#[cfg(test)]
mod tests;

View File

@@ -0,0 +1,223 @@
//! The overview query against real answers, and against GitHub itself.
use super::*;
use crate::github::overview::{merge_checks, CheckAction};
fn fixture(name: &str) -> PullRequestOverview {
let body = match name {
"clean_bot" => include_str!("../../fixtures/pr_overview_clean_bot.json"),
"merged" => include_str!("../../fixtures/pr_overview_merged.json"),
"conflicts" => include_str!("../../fixtures/pr_overview_conflicts_changes_requested.json"),
"approved" => include_str!("../../fixtures/pr_overview_blocked_approved.json"),
"failing" => include_str!("../../fixtures/pr_overview_failing_review_required.json"),
"auto_merge_on" => include_str!("../../fixtures/pr_overview_auto_merge_on.json"),
"auto_merge_available" => {
include_str!("../../fixtures/pr_overview_auto_merge_available.json")
}
"auto_merge_enabled" => include_str!("../../fixtures/pr_overview_auto_merge_enabled.json"),
other => panic!("no fixture {other}"),
};
parse_pull_request_overview(body).expect("the fixture parses")
}
/// A dependabot pull request on a repository the account administers: clean, every method
/// allowed, and nothing to act on but the merge.
#[test]
fn a_clean_pull_request_reads_whole() {
let pr = fixture("clean_bot");
assert_eq!((pr.number, pr.repository.as_str()), (197, "nora-quinn/luxe-dev"));
assert_eq!(pr.author, Author { login: "dependabot".into(), bot: true });
assert_eq!((pr.base_ref.as_str(), pr.merge_status), ("master", MergeStatus::Clean));
assert_eq!((pr.additions, pr.deletions, pr.changed_files, pr.commits), (35, 60, 1, 1));
assert_eq!(pr.checks.passed, 5);
assert!(pr.failing.is_empty() && pr.reviewers.is_empty());
assert_eq!(
pr.labels.iter().map(|label| label.name.as_str()).collect::<Vec<_>>(),
["dependencies", "rust"]
);
assert_eq!(pr.merge_options(), [MergeMethod::Merge, MergeMethod::Squash, MergeMethod::Rebase]);
assert_eq!(pr.viewer, Viewer { author: false, can_push: true, can_merge: true });
assert_eq!(pr.updated_at, 1_790_895_769, "2026-10-01T23:02:49Z");
assert_eq!(merge_checks(&pr).last().and_then(|row| row.action), Some(CheckAction::Merge));
// Clean, so there is nothing for auto-merge to wait on, and the repository keeps branches
assert_eq!(
pr.merge_settings,
MergeSettings {
last_method: Some(MergeMethod::Merge),
deletes_branch: false,
can_auto_merge: false,
can_cancel_auto_merge: false,
auto_merge: None,
}
);
assert_eq!(pr.default_merge_method(), MergeMethod::Merge);
}
/// vercel/next.js #98546, with auto-merge on: the method it will use is read and said as a row,
/// and an account that cannot merge there may neither turn it on nor off.
#[test]
fn auto_merge_that_is_on_is_said() {
let pr = fixture("auto_merge_on");
assert_eq!(pr.merge_settings.auto_merge, Some(MergeMethod::Squash));
assert!(!pr.merge_settings.can_auto_merge && !pr.merge_settings.can_cancel_auto_merge);
let row = merge_checks(&pr).into_iter().find(|row| row.label == "Auto-merge").expect("said");
assert_eq!(row.detail, format!("squash and merge into {} when ready", pr.base_ref));
assert_eq!(row.action, None, "not this account's to change");
}
/// On a scratch repository this account administers, with a required check that never reports:
/// blocked, so auto-merge is offered; on, it says how it will merge and offers turning it off.
#[test]
fn auto_merge_is_offered_while_blocked_and_cancellable_once_on() {
let available = fixture("auto_merge_available");
assert_eq!(available.node_id, "PR_kwDOU5qvE88AAAABGZIsWQ");
assert_eq!(available.merge_status, MergeStatus::Blocked);
let row = |pr: &PullRequestOverview| {
merge_checks(pr).into_iter().find(|row| row.label == "Auto-merge").expect("a row")
};
assert_eq!(row(&available).action, Some(CheckAction::EnableAutoMerge));
assert_eq!(row(&available).detail, "off");
let enabled = fixture("auto_merge_enabled");
assert_eq!(enabled.merge_settings.auto_merge, Some(MergeMethod::Squash));
assert_eq!(row(&enabled).action, Some(CheckAction::DisableAutoMerge));
assert_eq!(row(&enabled).detail, "squash and merge into main when ready");
}
/// cli/cli deletes a merged branch by itself, and an account that cannot merge there may not turn
/// auto-merge on either, however blocked the pull request is.
#[test]
fn a_repository_that_deletes_branches_says_so() {
let pr = fixture("approved");
assert!(pr.merge_settings.deletes_branch);
assert!(!pr.merge_settings.can_auto_merge && pr.merge_settings.auto_merge.is_none());
}
#[test]
fn a_merged_pull_request_has_nothing_in_its_way() {
let pr = fixture("merged");
assert_eq!(pr.state, PullRequestState::Merged);
assert!(merge_checks(&pr).is_empty());
}
/// Someone else's repository, read-only: a conflict, a reviewer asking for changes, and a bot's
/// comment that does not count as a verdict. No action is offered on any of it.
#[test]
fn a_conflicted_pull_request_with_changes_requested_offers_nothing_to_a_reader() {
let pr = fixture("conflicts");
assert_eq!(pr.merge_status, MergeStatus::Dirty);
assert_eq!(pr.review_decision, Some(ReviewDecision::ChangesRequested));
let verdicts: Vec<_> =
pr.reviewers.iter().map(|r| (r.login.as_str(), r.kind, r.verdict)).collect();
assert_eq!(
verdicts,
[
("BagToad", ReviewerKind::User, Verdict::ChangesRequested),
("copilot-pull-request-reviewer", ReviewerKind::Bot, Verdict::Commented),
]
);
assert!(pr.reviewers[0].at.is_some());
assert_eq!(pr.viewer, Viewer::default());
assert!(merge_checks(&pr).iter().all(|row| row.action.is_none()));
assert!(merge_checks(&pr).iter().any(|row| row.label == "Conflicts"));
}
/// Approved and still blocked: GitHub says no, so there is no Ready row however green it looks.
#[test]
fn an_approved_pull_request_github_still_blocks_offers_no_merge() {
let pr = fixture("approved");
assert_eq!(
(pr.merge_status, pr.review_decision),
(MergeStatus::Blocked, Some(ReviewDecision::Approved))
);
assert!(merge_checks(&pr).iter().all(|row| row.label != "Ready"));
}
/// A failing check by name, reviewers asked and not yet answering, and a request to a team this
/// account cannot see — which GitHub sends as `null` and is left out rather than failing.
#[test]
fn failing_checks_and_pending_reviewers_are_named() {
let pr = fixture("failing");
assert_eq!(pr.checks.failed, 1);
assert_eq!(pr.failing, [FailingCheckName { name: "govulncheck".into(), required: false }]);
let requested: Vec<&str> = pr
.reviewers
.iter()
.filter(|reviewer| reviewer.verdict == Verdict::Requested)
.map(|reviewer| reviewer.login.as_str())
.collect();
assert_eq!(requested, ["williammartin", "BagToad"]);
let rows = merge_checks(&pr);
assert!(rows.iter().any(|row| row.detail == "1 of 18 failing: govulncheck"), "{rows:#?}");
}
/// The query against GitHub itself, on a merged pull request in a public repository that will
/// not change under it: it parses, and it says what it is.
#[tokio::test]
#[ignore = "needs a signed-in gh and network access"]
async fn a_real_gh_reads_a_public_pull_request() {
use crate::github::{PullRequests, Repository};
let repository = Repository {
host: "github.com".into(),
owner: "cli".into(),
name: "cli".into(),
default_branch: String::new(),
remote: None,
};
let pr = super::super::GhCli::new()
.pull_request_overview(&repository, 8_474)
.await
.expect("a public pull request reads");
assert_eq!((pr.number, pr.repository.as_str()), (8_474, "cli/cli"));
assert_eq!(pr.state, PullRequestState::Merged);
assert!(!pr.viewer.can_merge, "a stranger's repository");
}
#[test]
fn a_missing_pull_request_is_not_found() {
let body = r#"{"data":{"repository":{"nameWithOwner":"a/b","viewerPermission":"READ","mergeCommitAllowed":true,"squashMergeAllowed":true,"rebaseMergeAllowed":true,"pullRequest":null}}}"#;
assert!(matches!(parse_pull_request_overview(body), Err(GitHubError::NotFound)));
}
/// Required checks lead, and a re-request makes a reviewer pending again.
#[test]
fn required_checks_lead_and_a_re_request_is_pending() {
let node = |name: &str, required| CheckNode {
name: Some(name.into()),
context: None,
conclusion: Some("FAILURE".into()),
state: None,
is_required: required,
};
let names: Vec<String> = failing(vec![node("lint", false), node("test", true)])
.into_iter()
.map(|check| check.name)
.collect();
assert_eq!(names, ["test", "lint"]);
let review = ReviewNode {
author: Some(Actor { typename: "User".into(), login: "jon".into() }),
state: "APPROVED".into(),
submitted_at: None,
};
let again = RequestNode {
requested_reviewer: Some(Requested {
typename: "User".into(),
login: Some("jon".into()),
slug: None,
organization: None,
}),
};
let team = RequestNode {
requested_reviewer: Some(Requested {
typename: "Team".into(),
login: None,
slug: Some("core".into()),
organization: Some(Login { login: "acme".into() }),
}),
};
let reviewers = reviewers(vec![review], Vec::new(), vec![again, team]);
let shown: Vec<_> = reviewers.iter().map(|r| (r.login.as_str(), r.verdict)).collect();
assert_eq!(shown, [("jon", Verdict::Requested), ("acme/core", Verdict::Requested)]);
assert_eq!(reviewers[1].kind, ReviewerKind::Team);
}

View File

@@ -0,0 +1,288 @@
//! Pull requests — reading one pull request or issue, and its detail and conversation.
use super::*;
#[async_trait]
impl PullRequests for GhCli {
async fn pull_request(
&self,
repository: &Repository,
number: u64,
) -> Result<PullRequest, GitHubError> {
let number = number.to_string();
let target = repo_arg(repository);
let args = ["pr", "view", &number, "--repo", &target, "--json", PULL_REQUEST_FIELDS];
parse_pull_request(&self.gh(&std::env::temp_dir(), &args).await?)
}
async fn issue(&self, repository: &Repository, number: u64) -> Result<Issue, GitHubError> {
let number = number.to_string();
let target = repo_arg(repository);
let args = [
"issue",
"view",
&number,
"--repo",
&target,
"--json",
"number,title,body,url,author,comments",
];
parse_issue(&self.gh(&std::env::temp_dir(), &args).await?)
}
async fn conversation(
&self,
repository: &Repository,
number: u64,
pull_request: bool,
) -> Result<Vec<crate::github::overview::ConversationEntry>, GitHubError> {
let query = match pull_request {
true => conversation::PULL_REQUEST_CONVERSATION_QUERY,
false => conversation::ISSUE_CONVERSATION_QUERY,
};
let query = format!("query={query}");
let (owner, name, number) = (
format!("owner={}", repository.owner),
format!("name={}", repository.name),
format!("number={number}"),
);
let mut args = vec!["api", "graphql"];
push_hostname(&mut args, repository);
args.extend(["-f", &query, "-F", &owner, "-F", &name, "-F", &number]);
let body = self.gh(&std::env::temp_dir(), &args).await?;
conversation::parse_conversation(&body)
}
async fn issue_overview(
&self,
repository: &Repository,
number: u64,
) -> Result<crate::github::overview::IssueOverview, GitHubError> {
let query = format!("query={}", issue_overview::ISSUE_OVERVIEW_QUERY);
let (owner, name, number) = (
format!("owner={}", repository.owner),
format!("name={}", repository.name),
format!("number={number}"),
);
let mut args = vec!["api", "graphql"];
push_hostname(&mut args, repository);
args.extend(["-f", &query, "-F", &owner, "-F", &name, "-F", &number]);
let body = self.gh(&std::env::temp_dir(), &args).await?;
issue_overview::parse_issue_overview(&body)
}
async fn pull_request_overview(
&self,
repository: &Repository,
number: u64,
) -> Result<crate::github::overview::PullRequestOverview, GitHubError> {
let query = format!("query={}", overview::PULL_REQUEST_OVERVIEW_QUERY);
let (owner, name, number) = (
format!("owner={}", repository.owner),
format!("name={}", repository.name),
format!("number={number}"),
);
let mut args = vec!["api", "graphql"];
push_hostname(&mut args, repository);
args.extend(["-f", &query, "-F", &owner, "-F", &name, "-F", &number]);
let body = self.gh(&std::env::temp_dir(), &args).await?;
overview::parse_pull_request_overview(&body)
}
}
/// The `gh pr view` fields a [`PullRequest`] is read from.
///
/// Not `commits`: it carries every commit's full message and author, which on a large pull request
/// is most of the payload, and the commit messages in range are read from git instead.
pub(super) const PULL_REQUEST_FIELDS: &str = "number,title,body,url,author,isDraft,state,baseRefName,baseRefOid,\
headRefName,headRefOid,isCrossRepository,reviewDecision,statusCheckRollup,closingIssuesReferences";
/// The body of `gh pr view --json` with [`PULL_REQUEST_FIELDS`].
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
pub(super) struct PrView {
number: u64,
title: String,
#[serde(default)]
body: String,
url: String,
author: PrAuthor,
is_draft: bool,
state: String,
base_ref_name: String,
base_ref_oid: String,
head_ref_name: String,
head_ref_oid: String,
#[serde(default)]
is_cross_repository: bool,
#[serde(default)]
review_decision: Option<String>,
#[serde(default)]
status_check_rollup: Vec<CheckEntry>,
#[serde(default)]
closing_issues_references: Vec<ClosingIssue>,
}
#[derive(Deserialize)]
pub(super) struct PrAuthor {
login: String,
#[serde(default)]
is_bot: bool,
}
/// One entry of `statusCheckRollup`: a GitHub Actions or app check run, or a commit status.
#[derive(Deserialize)]
#[serde(tag = "__typename")]
pub(super) enum CheckEntry {
CheckRun {
#[serde(default)]
status: String,
#[serde(default)]
conclusion: String,
},
StatusContext {
#[serde(default)]
state: String,
},
#[serde(other)]
Other,
}
#[derive(Deserialize)]
pub(super) struct ClosingIssue {
number: u64,
repository: ClosingRepository,
}
#[derive(Deserialize)]
pub(super) struct ClosingRepository {
name: String,
owner: ClosingOwner,
}
#[derive(Deserialize)]
pub(super) struct ClosingOwner {
login: String,
}
pub(super) fn parse_pull_request(body: &str) -> Result<PullRequest, GitHubError> {
let view: PrView = serde_json::from_str(body).map_err(GitHubError::Unreadable)?;
let state = match view.state.as_str() {
"MERGED" => PullRequestState::Merged,
"CLOSED" => PullRequestState::Closed,
_ => PullRequestState::Open,
};
// An empty string, not null, is how GitHub says the repository asks for no review
let review_decision = match view.review_decision.as_deref() {
Some("APPROVED") => Some(ReviewDecision::Approved),
Some("CHANGES_REQUESTED") => Some(ReviewDecision::ChangesRequested),
Some("REVIEW_REQUIRED") => Some(ReviewDecision::ReviewRequired),
_ => None,
};
let bot = view.author.is_bot || view.author.login.ends_with("[bot]");
Ok(PullRequest {
number: view.number,
title: view.title,
body: view.body,
url: view.url,
author: Author { login: view.author.login, bot },
draft: view.is_draft,
state,
base_ref: view.base_ref_name,
base_oid: view.base_ref_oid,
head_ref: view.head_ref_name,
head_oid: view.head_ref_oid,
cross_repository: view.is_cross_repository,
review_decision,
checks: roll_up(&view.status_check_rollup),
closing_issues: view
.closing_issues_references
.into_iter()
.map(|issue| IssueRef {
repository: format!("{}/{}", issue.repository.owner.login, issue.repository.name),
number: issue.number,
})
.collect(),
})
}
/// Counts checks by outcome across both kinds GitHub reports.
///
/// A check run that has not completed is pending whatever its conclusion field says; a commit
/// status has only a state. Anything unrecognized is left out of the count rather than guessed at.
pub(super) fn roll_up(entries: &[CheckEntry]) -> CheckRollup {
let mut rollup = CheckRollup::default();
for entry in entries {
let bucket = match entry {
CheckEntry::CheckRun { status, .. } if status != "COMPLETED" => &mut rollup.pending,
CheckEntry::CheckRun { conclusion, .. } => match conclusion.as_str() {
"SUCCESS" => &mut rollup.passed,
"NEUTRAL" | "SKIPPED" => &mut rollup.skipped,
"FAILURE" | "TIMED_OUT" | "CANCELLED" | "ACTION_REQUIRED" | "STARTUP_FAILURE"
| "STALE" => &mut rollup.failed,
_ => continue,
},
CheckEntry::StatusContext { state } => match state.as_str() {
"SUCCESS" => &mut rollup.passed,
"PENDING" | "EXPECTED" => &mut rollup.pending,
"FAILURE" | "ERROR" => &mut rollup.failed,
_ => continue,
},
CheckEntry::Other => continue,
};
*bucket += 1;
}
rollup
}
#[derive(Deserialize)]
pub(super) struct IssueView {
number: u64,
title: String,
#[serde(default)]
body: String,
url: String,
#[serde(default)]
author: Option<IssueAuthor>,
#[serde(default)]
comments: Vec<IssueCommentView>,
}
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
pub(super) struct IssueCommentView {
#[serde(default)]
author: Option<IssueAuthor>,
#[serde(default)]
body: String,
#[serde(default)]
is_minimized: bool,
}
/// How many of an issue's comments are kept: the latest, since that is where a discussion lands.
pub(super) const ISSUE_COMMENTS_KEPT: usize = 5;
pub(super) fn parse_issue(body: &str) -> Result<Issue, GitHubError> {
let view: IssueView = serde_json::from_str(body).map_err(GitHubError::Unreadable)?;
let total_comments = view.comments.len();
// Hidden as spam or abuse by the repository's maintainers: not part of the discussion
let visible: Vec<IssueComment> = view
.comments
.into_iter()
.filter(|comment| !comment.is_minimized)
.map(|comment| IssueComment {
author: comment.author.map(|author| author.login).unwrap_or_default(),
body: comment.body,
})
.collect();
let skip = visible.len().saturating_sub(ISSUE_COMMENTS_KEPT);
Ok(Issue {
number: view.number,
title: view.title,
body: view.body,
url: view.url,
author: view.author.map(|author| author.login).unwrap_or_default(),
comments: visible.into_iter().skip(skip).collect(),
total_comments,
})
}

View File

@@ -0,0 +1,195 @@
//! Reviews — the lines a review may comment on, posting one, and reading those already there.
use super::*;
#[async_trait]
impl Reviews for GhCli {
async fn pull_request_patches(
&self,
repository: &Repository,
number: u64,
) -> Result<Vec<FilePatch>, GitHubError> {
let endpoint = format!("{}/files?per_page=100", pulls_endpoint(repository, number));
let mut args = vec!["api", "--paginate"];
push_hostname(&mut args, repository);
args.extend([
endpoint.as_str(),
"--jq",
".[] | {filename, previous_filename, status, patch}",
]);
parse_patches(&self.gh(&std::env::temp_dir(), &args).await?)
}
async fn submit_review(
&self,
repository: &Repository,
number: u64,
review: &SubmitReview,
) -> Result<PostedReview, GitHubError> {
let input = PrivateFile::write(&review_payload(review).to_string())
.map_err(|source| GitHubError::Run { program: "gh", source })?;
let endpoint = format!("{}/reviews", pulls_endpoint(repository, number));
let path = input.path.to_string_lossy().into_owned();
let mut args = vec!["api", "--method", "POST"];
push_hostname(&mut args, repository);
args.extend([endpoint.as_str(), "--input", path.as_str()]);
let ran = self.run(&std::env::temp_dir(), &args).await?;
if ran.success {
parse_posted_review(&ran.stdout)
} else {
Err(rejection(&ran.stdout)
.unwrap_or_else(|| classify_failure(&ran.stderr, &ran.stdout)))
}
}
async fn reviews(
&self,
repository: &Repository,
number: u64,
) -> Result<Vec<ExistingReview>, GitHubError> {
let endpoint = format!("{}/reviews?per_page=100", pulls_endpoint(repository, number));
let mut args = vec!["api", "--paginate"];
push_hostname(&mut args, repository);
args.extend([
endpoint.as_str(),
"--jq",
".[] | {id, user: .user.login, state, commit_id, body, submitted_at, html_url}",
]);
parse_reviews(&self.gh(&std::env::temp_dir(), &args).await?)
}
}
/// The JSON body GitHub's create-review endpoint takes.
pub(super) fn review_payload(review: &SubmitReview) -> serde_json::Value {
let side = |side: ThreadSide| match side {
ThreadSide::Left => "LEFT",
ThreadSide::Right => "RIGHT",
};
let comments: Vec<serde_json::Value> = review
.comments
.iter()
.map(|comment| {
let mut value = serde_json::json!({
"path": comment.path,
"line": comment.line,
"side": side(comment.side),
"body": comment.body,
});
if let Some(start) = comment.start_line {
value["start_line"] = start.into();
value["start_side"] = side(comment.side).into();
}
value
})
.collect();
serde_json::json!({
"commit_id": review.commit_id,
"event": match review.event {
ReviewEvent::Comment => "COMMENT",
ReviewEvent::Approve => "APPROVE",
ReviewEvent::RequestChanges => "REQUEST_CHANGES",
},
"body": review.body,
"comments": comments,
})
}
/// One line of `gh api --paginate …/files --jq '.[] | {…}'`.
#[derive(Deserialize)]
pub(super) struct FileLine {
filename: String,
#[serde(default)]
previous_filename: Option<String>,
#[serde(default)]
patch: Option<String>,
}
pub(super) fn parse_patches(body: &str) -> Result<Vec<FilePatch>, GitHubError> {
Ok(parse_lines::<FileLine>(body)?
.into_iter()
.map(|file| FilePatch {
commentable: file.patch.as_deref().map(commentable_lines).unwrap_or_default(),
path: file.filename,
previous_path: file.previous_filename,
})
.collect())
}
/// The lines of a unified patch a comment can sit on: every line inside a hunk, on its side.
pub(super) fn commentable_lines(patch: &str) -> CommentableLines {
let mut lines = CommentableLines::default();
let (mut old, mut new) = (0u32, 0u32);
for line in patch.lines() {
if let Some(header) = line.strip_prefix("@@ ") {
let mut ranges = header.split_whitespace();
let start = |range: Option<&str>, sign: char| {
range
.and_then(|range| range.strip_prefix(sign))
.and_then(|range| range.split(',').next())
.and_then(|start| start.parse::<u32>().ok())
.unwrap_or(0)
};
old = start(ranges.next(), '-');
new = start(ranges.next(), '+');
continue;
}
match line.chars().next() {
Some('+') => {
lines.right.insert(new);
new += 1;
}
Some('-') => {
lines.left.insert(old);
old += 1;
}
Some('\\') => {}
_ => {
lines.left.insert(old);
lines.right.insert(new);
old += 1;
new += 1;
}
}
}
lines
}
#[derive(Deserialize)]
pub(super) struct PostedLine {
id: u64,
html_url: String,
}
pub(super) fn parse_posted_review(body: &str) -> Result<PostedReview, GitHubError> {
let posted: PostedLine = serde_json::from_str(body).map_err(GitHubError::Unreadable)?;
Ok(PostedReview { id: posted.id, url: posted.html_url })
}
#[derive(Deserialize)]
pub(super) struct ReviewLine {
id: u64,
#[serde(default)]
user: Option<String>,
#[serde(default)]
commit_id: Option<String>,
#[serde(default)]
body: Option<String>,
#[serde(default)]
submitted_at: Option<String>,
#[serde(default)]
html_url: Option<String>,
}
pub(super) fn parse_reviews(body: &str) -> Result<Vec<ExistingReview>, GitHubError> {
Ok(parse_lines::<ReviewLine>(body)?
.into_iter()
.map(|review| ExistingReview {
id: review.id,
author: review.user.unwrap_or_default(),
commit_id: review.commit_id.unwrap_or_default(),
body: review.body.unwrap_or_default(),
submitted_at: review.submitted_at.unwrap_or_default(),
url: review.html_url.unwrap_or_default(),
})
.collect())
}

View File

@@ -0,0 +1,307 @@
//! Search — what `/github`'s sections list, each row with what its second line says.
//!
//! One GraphQL search per page, thirty rows, one point of the hourly budget: GitHub's own tally of
//! each pull request's checks rather than a list of them, and the first pull request that would
//! close each issue rather than every one that mentions it. The page says how many the search
//! matches in all and where the next page starts, so a section can say `30 of 214` and go on.
use serde::Deserialize;
use super::{count_checks, status_text, Nodes, RollupContexts};
use crate::github::overview::{Label, RowFacts};
use crate::github::{GitHubError, ListItem, PullRequestState, ReviewDecision, SearchPage};
/// The search, with what each row's second line needs.
pub(super) const SEARCH_QUERY: &str = "query($q:String!,$after:String){\
search(query:$q,type:ISSUE,first:30,after:$after){issueCount pageInfo{endCursor hasNextPage} \
nodes{__typename ...on PullRequest{number title url state isDraft updatedAt \
repository{nameWithOwner} author{__typename login} additions deletions reviewDecision \
comments{totalCount} commits(last:1){nodes{commit{statusCheckRollup{contexts(first:1){\
checkRunCountsByState{state count} statusContextCountsByState{state count}}}}}}} \
...on Issue{number title url state updatedAt repository{nameWithOwner} \
author{__typename login} labels(first:5){nodes{name color}} comments{totalCount} \
closedByPullRequestsReferences(first:1,includeClosedPrs:false){nodes{number}}}}}}";
#[derive(Deserialize)]
struct Answer {
data: Data,
}
#[derive(Deserialize)]
struct Data {
search: Search,
}
/// The search's answer. A fixture from before the count and cursor were asked for has neither,
/// and reads as one page holding everything.
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct Search {
nodes: Vec<Option<Node>>,
issue_count: Option<u64>,
page_info: Option<PageInfo>,
}
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct PageInfo {
end_cursor: Option<String>,
has_next_page: bool,
}
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct Node {
#[serde(rename = "__typename")]
typename: String,
number: Option<u64>,
#[serde(default)]
title: String,
#[serde(default)]
url: String,
#[serde(default)]
is_draft: bool,
#[serde(default)]
updated_at: String,
#[serde(default)]
state: String,
repository: Option<NameWithOwner>,
author: Option<Actor>,
additions: Option<u64>,
deletions: Option<u64>,
review_decision: Option<String>,
comments: Option<Count>,
commits: Option<Nodes<CommitNode>>,
labels: Option<Nodes<LabelNode>>,
closed_by_pull_requests_references: Option<Nodes<Numbered>>,
}
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct NameWithOwner {
name_with_owner: String,
}
/// An author; an answer from before the typename was asked for has none, and reads as a person.
#[derive(Deserialize)]
struct Actor {
#[serde(rename = "__typename", default)]
typename: String,
login: String,
}
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct Count {
total_count: usize,
}
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct CommitNode {
commit: CommitRollup,
}
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct CommitRollup {
status_check_rollup: Option<Rollup>,
}
#[derive(Deserialize)]
struct Rollup {
contexts: RollupContexts,
}
#[derive(Deserialize)]
struct LabelNode {
name: String,
color: String,
}
#[derive(Deserialize)]
struct Numbered {
number: u64,
}
/// The page a search found: its rows in the search's order, the count, and the next page's cursor.
pub(super) fn parse_search(body: &str) -> Result<SearchPage, GitHubError> {
let answer: Answer = serde_json::from_str(body).map_err(GitHubError::Unreadable)?;
let search = answer.data.search;
let items: Vec<ListItem> = search
.nodes
.into_iter()
// GitHub types each node nullable; anything but these two has no number to act on
.flatten()
.filter_map(|node| {
let pull_request = match node.typename.as_str() {
"PullRequest" => true,
"Issue" => false,
_ => return None,
};
let facts = facts(&node, pull_request);
Some(ListItem {
pull_request,
number: node.number?,
title: status_text(&node.title),
url: node.url,
repository: node.repository.map(|repo| repo.name_with_owner).unwrap_or_default(),
author: node.author.map(|author| author.login).unwrap_or_default(),
draft: node.is_draft,
updated_at: node.updated_at,
state: match node.state.as_str() {
"MERGED" => PullRequestState::Merged,
"CLOSED" => PullRequestState::Closed,
_ => PullRequestState::Open,
},
facts,
})
})
.collect();
let next = search
.page_info
.filter(|page| page.has_next_page)
.and_then(|page| page.end_cursor)
.filter(|cursor| !cursor.is_empty());
// Never fewer than it brought, whatever the count says
let total = search.issue_count.unwrap_or(0).max(items.len() as u64);
Ok(SearchPage { items, total, next })
}
/// What a row's second line says, or nothing for an answer that carries none of it.
fn facts(node: &Node, pull_request: bool) -> Option<RowFacts> {
let asked = node.comments.is_some();
if !asked {
return None;
}
let checks = node
.commits
.as_ref()
.and_then(|commits| commits.nodes.first())
.and_then(|commit| commit.commit.status_check_rollup.as_ref())
.map(|rollup| count_checks(&rollup.contexts))
.unwrap_or_default();
Some(RowFacts {
author_bot: node.author.as_ref().is_some_and(|author| author.typename == "Bot"),
additions: node.additions.unwrap_or_default(),
deletions: node.deletions.unwrap_or_default(),
checks,
review_decision: match node.review_decision.as_deref() {
Some("APPROVED") => Some(ReviewDecision::Approved),
Some("CHANGES_REQUESTED") => Some(ReviewDecision::ChangesRequested),
Some("REVIEW_REQUIRED") => Some(ReviewDecision::ReviewRequired),
_ => None,
},
comments: node.comments.as_ref().map_or(0, |count| count.total_count),
labels: node
.labels
.as_ref()
.map(|labels| {
labels
.nodes
.iter()
.map(|label| Label {
name: status_text(&label.name),
color: label.color.clone(),
})
.collect()
})
.unwrap_or_default(),
linked_pull_request: match pull_request {
true => None,
false => node
.closed_by_pull_requests_references
.as_ref()
.and_then(|linked| linked.nodes.first())
.map(|linked| linked.number),
},
})
}
#[cfg(test)]
mod tests {
use super::*;
/// Thirty open pull requests on `cli/cli`: each row carries its size, its checks and its
/// review verdict, and a bot is named as one.
#[test]
fn a_pull_request_row_says_how_big_and_how_it_stands() {
let rows = parse_search(include_str!("../fixtures/search_pull_requests_facts.json"))
.expect("the fixture parses")
.items;
assert_eq!(rows.len(), 30);
let first = &rows[0];
assert_eq!((first.number, first.draft), (14_578, true));
let facts = first.facts.as_ref().expect("facts");
assert_eq!((facts.additions, facts.deletions), (1_332, 867));
assert_eq!(facts.review_decision, Some(ReviewDecision::ReviewRequired));
assert!(!facts.author_bot);
assert!(rows.iter().all(|row| row.pull_request && row.facts.is_some()));
assert!(rows.iter().any(|row| row.facts.as_ref().unwrap().checks.total() > 0));
}
/// The first of three pages of `repo:cli/cli is:pr is:open`: GitHub's count of all 76, and
/// the cursor the second page starts after.
#[test]
fn a_page_with_more_says_how_many_and_where_the_next_starts() {
let page = parse_search(include_str!("../fixtures/search_page_first.json"))
.expect("the fixture parses");
assert_eq!(page.items.len(), 30);
assert_eq!(page.total, 76);
assert_eq!(page.next.as_deref(), Some("Y3Vyc29yOjMw"));
assert_eq!(page.items[0].number, 14_620);
// A real page's verdicts, every kind GitHub gives, each read as itself
let verdicts = |wanted| {
page.items
.iter()
.filter(|item| item.facts.as_ref().unwrap().review_decision == Some(wanted))
.count()
};
assert_eq!(verdicts(ReviewDecision::Approved), 3);
assert_eq!(verdicts(ReviewDecision::ChangesRequested), 2);
assert_eq!(verdicts(ReviewDecision::ReviewRequired), 25);
}
/// The last of those pages carries a cursor too, and `hasNextPage: false` is what says it is
/// the end: a section that followed the cursor would ask for an empty fourth page forever.
#[test]
fn the_last_page_has_no_next() {
let page = parse_search(include_str!("../fixtures/search_page_last.json"))
.expect("the fixture parses");
assert_eq!((page.items.len(), page.total), (16, 76));
assert_eq!(page.next, None);
}
/// An answer from before the count and cursor were asked for is one page holding everything,
/// and a count below what arrived never says fewer than are on screen.
#[test]
fn an_answer_without_a_count_is_everything_it_brought() {
let page = parse_search(include_str!("../fixtures/search_issues_facts.json"))
.expect("the fixture parses");
assert_eq!(page.total, page.items.len() as u64);
assert_eq!(page.next, None);
let low = r#"{"data":{"search":{"issueCount":0,"pageInfo":{"endCursor":"","hasNextPage":true},"nodes":[null,{"__typename":"Issue","number":7,"url":"u"}]}}}"#;
let page = parse_search(low).expect("parses");
assert_eq!((page.items.len(), page.total), (1, 1));
assert_eq!(page.next, None, "an empty cursor leads nowhere");
}
/// Issues carry their labels and comment count, and the open pull request that closes one.
#[test]
fn an_issue_row_says_its_labels_and_what_closes_it() {
let rows = parse_search(include_str!("../fixtures/search_issues_facts.json"))
.expect("the fixture parses")
.items;
let first = rows.first().expect("rows");
assert_eq!(first.number, 13_434);
let facts = first.facts.as_ref().expect("facts");
let labels: Vec<&str> = facts.labels.iter().map(|label| label.name.as_str()).collect();
assert_eq!(labels, ["bug", "priority-3", "gh-run", "pitch"]);
assert_eq!(facts.comments, 6);
assert!(rows.iter().all(|row| !row.pull_request));
assert!(
rows.iter().any(|row| row.facts.as_ref().unwrap().linked_pull_request.is_some()),
"an issue with an open pull request that closes it says which"
);
}
}

View File

@@ -0,0 +1,21 @@
use super::*;
use crate::github::ListItem;
// Every fixture below is copied from real `gh` 2.101.0 output, never written by hand: a
// round-trip through our own types would sail straight past a field `gh` renamed.
mod branches;
mod checks;
mod discovery;
mod process;
mod pull_requests;
mod reviews;
mod threads;
mod writes;
use branches::*;
use discovery::*;
use pull_requests::*;
#[cfg(unix)]
use reviews::*;
use threads::*;

View File

@@ -0,0 +1,132 @@
//! Branches — a branch's pull request, its stack and its search results.
use super::*;
pub(super) const STATUS_OPEN: &str = include_str!("../../fixtures/branch_status_open.json");
pub(super) const STATUS_NONE: &str = include_str!("../../fixtures/branch_status_none.json");
pub(super) const STATUS_FAILING: &str = include_str!("../../fixtures/branch_status_failing.json");
pub(super) const STATUS_NO_CHECKS: &str =
include_str!("../../fixtures/branch_status_no_checks.json");
pub(super) const STATUS_FORK: &str = include_str!("../../fixtures/branch_status_fork_threads.json");
pub(super) const STATUS_STACKED: &str = include_str!("../../fixtures/branch_status_stacked.json");
pub(super) const MERGED_SQUASHED: &str = include_str!("../../fixtures/merged_below_squashed.json");
pub(super) const SEARCH_MINE: &str = include_str!("../../fixtures/search_mine.json");
pub(super) const SEARCH_ISSUES: &str = include_str!("../../fixtures/search_issues.json");
/// Real searches: this repository's pull requests by the reader, and cli/cli's bugs, of any
/// state and newest first.
#[test]
fn a_search_lists_pull_requests_and_issues_with_where_they_are() {
let mine = parse_search(SEARCH_MINE).unwrap().items;
assert_eq!(mine.len(), 30);
assert!(mine.iter().all(|item| item.pull_request && item.repository == "nora-quinn/luxe-dev"));
assert_eq!(mine[0].number, 177);
assert!(mine[0].url.ends_with("/pull/177") && mine[0].author == "nora-quinn");
assert!(!mine[0].updated_at.is_empty());
let states: Vec<(u64, PullRequestState, bool)> =
mine[..3].iter().map(|item| (item.number, item.state, item.draft)).collect();
assert_eq!(
states,
[
(177, PullRequestState::Open, false),
(179, PullRequestState::Closed, true),
(178, PullRequestState::Merged, false),
]
);
let issues = parse_search(SEARCH_ISSUES).unwrap().items;
assert!(issues.iter().all(|item| !item.pull_request && item.repository == "cli/cli"));
assert_eq!(issues[0].number, 14495);
assert_eq!(
(issues[0].state, issues[2].state),
(PullRequestState::Closed, PullRequestState::Open)
);
let deleted =
SEARCH_ISSUES.replacen("\"author\":{\"login\":", "\"author\":null,\"x\":{\"login\":", 1);
assert_eq!(parse_search(&deleted).unwrap().items[0].author, "", "a deleted account");
// A frame from a Luxe that sent no state reads as open, not as an error
let older = r#"{"pull_request":true,"number":1,"title":"T","url":"u","repository":"a/b","author":"","draft":false,"updated_at":""}"#;
let item: ListItem = serde_json::from_str(older).unwrap();
assert_eq!(item.state, PullRequestState::Open);
}
pub(super) const MERGED_NONE: &str = include_str!("../../fixtures/merged_below_none.json");
/// Real answers from restacking a scratch stack on luxe-dev: the bottom squash-merged with its
/// branch kept, and a layer with nothing merged below it. A retargeted one names the base it
/// was moved from.
#[test]
fn what_merged_below_a_stack_is_read_with_where_it_went() {
let (merged, previous) = parse_merged_below(MERGED_SQUASHED).unwrap();
let merged = merged.expect("#158 merged");
assert_eq!(merged.number, 158);
assert_eq!(merged.head_oid, "e934880d96cdfd85a9b9771a086c152d84ab142f");
assert_eq!(merged.base_ref, "scratch/stack-trunk");
assert_eq!(previous, None, "never retargeted");
assert_eq!(parse_merged_below(MERGED_NONE).unwrap(), (None, None));
let retargeted = MERGED_NONE.replace(
"\"timelineItems\":{\"nodes\":[]}",
"\"timelineItems\":{\"nodes\":[{\"previousRefName\":\"scratch/stack-1\"}]}",
);
assert_eq!(parse_merged_below(&retargeted).unwrap().1.as_deref(), Some("scratch/stack-1"));
}
pub(super) const STATUS_UNSTACKED: &str =
include_str!("../../fixtures/branch_status_unstacked.json");
/// Luxe's own chain on luxe-dev, read from the middle: seven below down to `master`, two above,
/// and the evidence that checks wait for trunk — the bottom one has them, this one none.
#[test]
fn a_pull_request_in_the_middle_of_a_stack_knows_where_it_sits() {
let status =
parse_branch_status(STATUS_STACKED, "feat/session-worktrees", "nora-quinn").unwrap();
let pr = status.pull_request.unwrap();
assert_eq!(pr.number, 149);
let stack = pr.stack.expect("in a stack");
let numbers = |entries: &[StackEntry]| entries.iter().map(|e| e.number).collect::<Vec<_>>();
assert_eq!(numbers(&stack.below), [138, 139, 140, 143, 145, 147, 148], "bottom first");
assert_eq!(numbers(&stack.above), [153, 156], "nearest first");
assert_eq!((stack.position(), stack.height()), (8, 10));
assert_eq!(stack.trunk, "master");
assert!(stack.trunk_is_default);
assert!(stack.below[0].checked && !stack.below[1].checked);
assert!(stack.checks_wait_for_trunk(&pr.checks), "none here, and #138's ran");
assert!(!stack.checks_wait_for_trunk(&CheckRollup { passed: 1, ..Default::default() }));
}
/// A pull request into trunk with nothing stacked on it is in no stack, and is not listed as
/// part of anyone else's.
#[test]
fn a_pull_request_on_its_own_is_in_no_stack() {
let status =
parse_branch_status(STATUS_UNSTACKED, "polish/composer-text-navigation", "nora-quinn")
.unwrap();
assert_eq!(status.pull_request.unwrap().stack, None);
}
/// The walk follows only this repository's branches, stops at a base with no pull request of
/// its own (which is then not trunk), and a loop in the data ends it rather than hanging it.
#[test]
fn the_stack_walk_stops_at_forks_plain_branches_and_loops() {
let node = |number: u64, head: &str, base: &str, owner: &str| StackNode {
number,
title: format!("#{number}"),
is_draft: false,
head_ref_name: head.into(),
base_ref_name: base.into(),
head_repository_owner: Some(Login { login: owner.into() }),
commits: Nodes { nodes: Vec::new() },
};
let open = [
node(2, "one", "shared-base", "acme"),
node(3, "fork-branch", "two", "mara"),
node(4, "loop-a", "loop-b", "acme"),
node(5, "loop-b", "loop-a", "acme"),
];
let stack = stack_of(9, "two", "one", &open, "acme", Some("main")).unwrap();
assert_eq!(stack.below.iter().map(|e| e.number).collect::<Vec<_>>(), [2]);
assert!(stack.above.is_empty(), "a fork's branch is no base");
assert_eq!(stack.trunk, "shared-base");
assert!(!stack.trunk_is_default && !stack.checks_wait_for_trunk(&CheckRollup::default()));
let looped = stack_of(9, "x", "loop-a", &open, "acme", Some("main")).unwrap();
assert_eq!(looped.below.iter().map(|e| e.number).collect::<Vec<_>>(), [5, 4]);
}

View File

@@ -0,0 +1,293 @@
//! Checks — failing checks, their jobs, and the tail of a failed log.
use super::*;
pub(super) const CHECK_RUNS: &str = include_str!("../../fixtures/check_runs.jsonl");
pub(super) const COMMIT_STATUSES: &str = include_str!("../../fixtures/commit_statuses.jsonl");
pub(super) const LOG_FAILED: &str = include_str!("../../fixtures/log_failed.txt");
#[test]
fn a_branch_with_a_passing_pull_request_reads_its_counts_and_budget() {
let status = parse_branch_status(STATUS_OPEN, "topic", "nora-quinn").unwrap();
let pr = status.pull_request.expect("the branch has a pull request");
assert_eq!(pr.number, 138);
assert_eq!(pr.state, PullRequestState::Open);
assert!(!pr.draft);
assert_eq!(pr.review_decision, None);
assert_eq!(pr.checks, CheckRollup { passed: 5, ..CheckRollup::default() });
assert_eq!(pr.unresolved_threads, 0);
assert_eq!(pr.head_oid, "399286814564627352030020a163bfcbaeafe166");
assert!(pr.url.ends_with("/pull/138"));
let limit = status.rate_limit.expect("the query asks for its budget");
assert!(limit.remaining > 0 && limit.remaining <= 5000);
assert!(limit.reset_at > 1_780_000_000, "{}", limit.reset_at);
}
#[test]
fn a_branch_without_one_has_none_and_still_reports_the_budget() {
let status = parse_branch_status(STATUS_NONE, "topic", "nora-quinn").unwrap();
assert_eq!(status.pull_request, None);
assert!(status.rate_limit.is_some());
}
/// A closed pull request with a failing check is still the branch's, and says both.
#[test]
fn a_closed_pull_request_with_a_failing_check_says_both() {
let pr = parse_branch_status(STATUS_FAILING, "topic", "nora-quinn").unwrap().pull_request;
let pr = pr.expect("the branch had a pull request");
assert_eq!(pr.state, PullRequestState::Closed);
assert_eq!(pr.checks, CheckRollup { passed: 4, failed: 1, ..CheckRollup::default() });
}
#[test]
fn no_checks_at_all_counts_nothing() {
let pr = parse_branch_status(STATUS_NO_CHECKS, "topic", "nora-quinn").unwrap().pull_request;
assert_eq!(pr.expect("pull request").checks.total(), 0);
}
/// A fork's pull request is the fork owner's, whatever the branch is called: seen from the
/// upstream's own owner it does not exist.
#[test]
fn a_forks_pull_request_belongs_to_the_fork_owner() {
let pr = parse_branch_status(STATUS_FORK, "topic", "sebtardif").unwrap().pull_request;
let pr = pr.expect("the fork owner's branch has a pull request");
assert_eq!(pr.number, 13340);
assert_eq!(pr.unresolved_threads, 2);
assert_eq!(pr.review_decision, Some(ReviewDecision::ReviewRequired));
assert_eq!(parse_branch_status(STATUS_FORK, "topic", "cli").unwrap().pull_request, None);
}
#[test]
fn an_open_pull_request_wins_over_a_newer_closed_one() {
let body = r#"{"data":{"repository":{"pullRequests":{"nodes":[
{"number":2,"title":"t","url":"u","state":"CLOSED","isDraft":false,"headRefOid":"b",
"headRepositoryOwner":{"login":"me"},"reviewDecision":null,"commits":{"nodes":[]},
"reviewThreads":{"totalCount":0,"nodes":[]}},
{"number":1,"title":"t","url":"u","state":"OPEN","isDraft":true,"headRefOid":"a",
"headRepositoryOwner":{"login":"me"},"reviewDecision":"CHANGES_REQUESTED",
"commits":{"nodes":[]},"reviewThreads":{"totalCount":0,"nodes":[]}}]}},
"rateLimit":null}}"#;
let pr = parse_branch_status(body, "topic", "me").unwrap().pull_request.unwrap();
assert_eq!((pr.number, pr.draft), (1, true));
assert_eq!(pr.review_decision, Some(ReviewDecision::ChangesRequested));
}
#[test]
fn a_title_is_filtered_flattened_and_bounded() {
assert_eq!(status_text("Fix\n the\tthing<!-- hidden -->"), "Fix the thing");
let long = status_text(&"x".repeat(500));
assert_eq!(long.chars().count(), STATUS_TEXT_MAX_CHARS);
assert!(long.ends_with('…'));
}
#[test]
fn github_timestamps_become_epoch_seconds() {
assert_eq!(rfc3339_seconds("1970-01-01T00:00:00Z"), Some(0));
assert_eq!(rfc3339_seconds("2000-03-01T00:00:00Z"), Some(951_868_800));
assert_eq!(rfc3339_seconds("2026-09-24T19:05:02Z"), Some(1_790_276_702));
assert_eq!(rfc3339_seconds("2024-02-29T23:59:59.5Z"), Some(1_709_251_199));
for bad in [
"",
"2026-09-24",
"2026-13-01T00:00:00Z",
"2026-09-24T24:00:00Z",
"2026-09-24T10:60:00Z",
"2026-09-24T19:05:02+01:00",
] {
assert_eq!(rfc3339_seconds(bad), None, "{bad}");
}
}
#[test]
fn failing_checks_are_the_failed_runs_and_statuses_with_their_jobs() {
let failing = parse_failing_checks(CHECK_RUNS, COMMIT_STATUSES).unwrap();
let names: Vec<_> =
failing.iter().map(|(check, job)| (check.name.as_str(), job.as_deref())).collect();
assert_eq!(
names,
[
("build · clippy · test (macos-latest)", Some("106993218139")),
("build · test · clippy · fmt", Some("106993218126")),
("build · clippy · test (windows-latest)", Some("106993217890")),
("Azure Pipelines CI", None),
]
);
let (azure, _) = &failing[3];
assert_eq!(azure.outcome, "failure");
assert_eq!(azure.summary.as_deref(), Some("#20260924.53 failed"));
assert!(azure.url.starts_with("https://dev.azure.com/"));
assert!(failing.iter().all(|(check, _)| check.log == CheckLog::NotActions));
}
/// An empty title is no summary, and does not hide the one the check wrote.
#[test]
fn a_check_summary_skips_an_empty_title() {
let summary = |title: &str, summary: &str| {
let line = format!(
r#"{{"name":"lint","status":"completed","conclusion":"failure","html_url":"h","details_url":null,"app":"other","title":{title},"summary":{summary}}}"#
);
parse_failing_checks(&line, "").unwrap()[0].0.summary.clone()
};
assert_eq!(summary("\"\"", "\"3 errors\"").as_deref(), Some("3 errors"));
assert_eq!(summary("\"Lint failed\"", "\"3 errors\"").as_deref(), Some("Lint failed"));
assert_eq!(summary("null", "\" \""), None);
}
#[test]
fn check_counts_land_in_the_bucket_their_state_names() {
let count = |state: &str, count: usize| StateCount { state: state.into(), count };
let contexts = RollupContexts {
check_run_counts_by_state: vec![
count("SUCCESS", 3),
count("SKIPPED", 1),
count("NEUTRAL", 1),
count("FAILURE", 2),
count("TIMED_OUT", 1),
count("QUEUED", 1),
count("IN_PROGRESS", 2),
count("COMPLETED", 9),
],
status_context_counts_by_state: vec![
count("SUCCESS", 1),
count("PENDING", 1),
count("EXPECTED", 1),
count("ERROR", 1),
count("FAILURE", 1),
],
};
assert_eq!(
count_checks(&contexts),
CheckRollup { passed: 4, failed: 5, pending: 5, skipped: 2 }
);
}
#[test]
fn a_merged_and_approved_pull_request_says_so() {
let body = r#"{"data":{"repository":{"pullRequests":{"nodes":[
{"number":7,"title":"t","url":"u","state":"MERGED","isDraft":false,"headRefOid":"a",
"headRepositoryOwner":{"login":"me"},"reviewDecision":"APPROVED",
"commits":{"nodes":[]},"reviewThreads":{"totalCount":0,"nodes":[]}}]}},
"rateLimit":null}}"#;
let pr = parse_branch_status(body, "topic", "me").unwrap().pull_request.unwrap();
assert_eq!(pr.state, PullRequestState::Merged);
assert_eq!(pr.review_decision, Some(ReviewDecision::Approved));
}
#[test]
fn a_running_check_has_not_failed() {
let runs = r#"{"name":"ci","status":"in_progress","conclusion":"failure","html_url":"h","details_url":null,"app":"github-actions","title":null,"summary":null}"#;
assert!(parse_failing_checks(runs, "").unwrap().is_empty());
}
#[test]
fn an_actions_job_id_comes_from_its_address() {
let url = "https://github.com/o/r/actions/runs/35801682338/job/106993218126";
assert_eq!(actions_job(url).as_deref(), Some("106993218126"));
assert_eq!(actions_job(&format!("{url}?pr=3")).as_deref(), Some("106993218126"));
assert_eq!(actions_job("https://github.com/o/r/actions/runs/1"), None);
assert_eq!(actions_job("https://github.com/o/r/actions/runs/1/job/x1"), None);
assert_eq!(actions_job("https://ci.example/job/12"), None);
}
/// The log's tail is the error, without the timestamps, color codes or byte-order mark that
/// would otherwise fill the lines around it.
#[test]
fn a_failed_log_is_cut_to_the_tail_of_each_step() {
let steps = parse_failed_log(LOG_FAILED, 12);
assert_eq!(steps.len(), 1);
let step = &steps[0];
assert_eq!(step.name, "Clippy (deny warnings)");
assert_eq!(step.tail.len(), 12);
assert_eq!(step.omitted + step.tail.len(), LOG_FAILED.lines().count());
assert_eq!(step.tail.last().unwrap(), "##[error]Process completed with exit code 101.");
assert!(step.tail.iter().any(|line| line.contains("error[E0425]")), "{:#?}", step.tail);
for line in &step.tail {
assert!(!line.contains('\u{1b}') && !line.contains("2026-09-23T"), "{line}");
assert!(!line.contains("^["), "{line}");
}
let all = parse_failed_log(LOG_FAILED, usize::MAX);
assert_eq!(all[0].omitted, 0);
assert!(all[0].tail[0].starts_with("##[group]Run cargo clippy"), "{}", all[0].tail[0]);
assert_eq!(all[0].tail[1], "cargo clippy --workspace --all-targets --locked -- -D warnings");
}
/// When `gh` could not split the log by step it prints the whole job, cleanup and all; the
/// tail ends at the last error, and what came after is counted, not shown.
#[test]
fn the_tail_ends_at_the_last_error_not_at_the_cleanup() {
let log = "job\tUNKNOWN STEP\t2026-01-01T00:00:00Z compiling\n\
job\tUNKNOWN STEP\t2026-01-01T00:00:00Z error[E0425]: nope\n\
job\tUNKNOWN STEP\t2026-01-01T00:00:00Z ##[error]Process completed with exit code 101.\n\
job\tUNKNOWN STEP\t2026-01-01T00:00:00Z Post job cleanup.\n\
job\tUNKNOWN STEP\t2026-01-01T00:00:00Z Cleaning up orphan processes\n";
let steps = parse_failed_log(log, 2);
assert_eq!(
steps[0].tail,
["error[E0425]: nope", "##[error]Process completed with exit code 101."]
);
assert_eq!((steps[0].omitted, steps[0].after), (1, 2));
let clean = parse_failed_log(LOG_FAILED, 5);
assert_eq!(clean[0].after, 0, "the error was the last line already");
}
#[test]
fn steps_keep_their_order_and_trailing_blank_lines_go() {
let log = "job\ta\t2026-01-01T00:00:00Z one\njob\tb\t2026-01-01T00:00:00Z two\n\
job\tb\t2026-01-01T00:00:00Z \nnot a log line\n";
let steps = parse_failed_log(log, 5);
assert_eq!(steps.len(), 2);
assert_eq!((steps[0].name.as_str(), steps[0].tail.clone()), ("a", vec!["one".to_string()]));
assert_eq!((steps[1].name.as_str(), steps[1].tail.clone()), ("b", vec!["two".to_string()]));
assert_eq!(steps[1].after, 1, "the blank line is counted as left out");
}
#[test]
fn color_codes_go_and_everything_else_stays() {
assert_eq!(strip_ansi("\u{1b}[1m\u{1b}[91merror\u{1b}[0m: x"), "error: x");
assert_eq!(strip_ansi("plain [1m"), "plain [1m");
assert_eq!(strip_ansi("^[[36;1mcargo^[[0m"), "cargo");
assert_eq!(strip_ansi("x ^ [y] ^ok"), "x ^ [y] ^ok");
assert_eq!(without_timestamp("2026-09-23T00:21:48Z text here"), "text here");
assert_eq!(without_timestamp("\u{feff}2026-09-23T00:21:48Z text"), "text");
assert_eq!(without_timestamp("warning: 2026Z"), "warning: 2026Z");
assert_eq!(without_timestamp("2026 was a year"), "2026 was a year");
}
/// Through a fake `gh`: the check listing, the statuses, and a log for each failing Actions
/// job up to the limit, the rest marked as not read.
#[cfg(unix)]
#[tokio::test]
async fn failing_checks_read_logs_for_the_first_few_actions_jobs() {
let dir = tempfile::tempdir().unwrap();
let fixtures = Path::new(env!("CARGO_MANIFEST_DIR")).join("src/github/fixtures");
let script = format!(
"case \"$*\" in\n\
*check-runs*) cat '{runs}' '{runs}' ;;\n\
*commits/*/status*) cat '{statuses}' ;;\n\
*106993217890*) echo 'HTTP 410: logs expired' >&2; exit 1 ;;\n\
*run\\ view*) cat '{log}' ;;\n\
esac",
runs = fixtures.join("check_runs.jsonl").display(),
statuses = fixtures.join("commit_statuses.jsonl").display(),
log = fixtures.join("log_failed.txt").display(),
);
let gh = GhCli { deadline: GH_DEADLINE, program: Some(fake_gh(dir.path(), &script)) };
let repository = Repository {
host: "github.com".into(),
owner: "o".into(),
name: "r".into(),
default_branch: String::new(),
remote: None,
};
let checks = gh.failing_checks(&repository, "1ee6ffe", 5).await.unwrap();
// The listing twice over: six failing Actions jobs, of which the first four are read
assert_eq!(checks.len(), 7);
assert!(matches!(&checks[0].log, CheckLog::Steps(steps) if steps[0].tail.len() == 5));
assert!(matches!(&checks[2].log, CheckLog::Unreadable(reason) if reason.contains("410")));
assert!(matches!(&checks[3].log, CheckLog::Steps(_)));
assert_eq!(checks[4].log, CheckLog::NotRead);
assert_eq!(checks[5].log, CheckLog::NotRead);
assert_eq!(checks[6].log, CheckLog::NotActions);
}

View File

@@ -0,0 +1,115 @@
//! Discovery — who is signed in, which repository this is, and how `gh` failures are told apart.
use super::*;
pub(super) const SIGNED_IN: &str = r#"{"hosts":{"github.com":[{"state":"success","active":true,"host":"github.com","login":"Nora-Quinn","tokenSource":"keyring","scopes":"gist, read:org, repo, workflow","gitProtocol":"https"}]}}"#;
pub(super) const SIGNED_OUT: &str = r#"{"hosts":{}}"#;
pub(super) const BAD_TOKEN: &str = r#"{"hosts":{"github.com":[{"state":"error","error":"non-200 OK status code: 401 Unauthorized body: \"{\\r\\n \\\"message\\\": \\\"Bad credentials\\\",\\r\\n \\\"documentation_url\\\": \\\"https://docs.github.com/rest\\\",\\r\\n \\\"status\\\": \\\"401\\\"\\r\\n}\"","active":true,"host":"github.com","login":"","tokenSource":"GH_TOKEN","gitProtocol":"https"}]}}"#;
pub(super) const REPO_VIEW: &str = r#"{"defaultBranchRef":{"name":"master"},"nameWithOwner":"nora-quinn/luxe-dev","url":"https://github.com/nora-quinn/luxe-dev"}"#;
/// A known login whose token GitHub no longer accepts.
pub(super) const REVOKED: &str = r#"{"hosts":{"github.com":[{"state":"error","error":"HTTP 401: Bad credentials (https://api.github.com/)","active":true,"host":"github.com","login":"someone","tokenSource":"/tmp/tmp.zrxMvye382/hosts.yml","gitProtocol":"https"}]}}"#;
#[test]
fn a_signed_in_account_is_read_from_auth_status() {
let account = parse_account(SIGNED_IN, None).unwrap();
assert_eq!(account, Account { host: "github.com".into(), login: "Nora-Quinn".into() });
assert_eq!(parse_account(SIGNED_IN, Some("GitHub.com")).unwrap().login, "Nora-Quinn");
}
/// Signed out exits zero under `--json`, so the body is the only witness.
#[test]
fn signed_out_and_a_rejected_token_are_both_not_signed_in() {
for body in [SIGNED_OUT, BAD_TOKEN, REVOKED] {
assert!(
matches!(parse_account(body, None), Err(GitHubError::NotAuthenticated { host: None })),
"{body}"
);
}
assert!(matches!(
parse_account(SIGNED_IN, Some("ghe.example.com")),
Err(GitHubError::NotAuthenticated { host: Some(host) }) if host == "ghe.example.com"
));
}
#[test]
fn a_repository_is_read_from_repo_view() {
let repository = parse_repository(REPO_VIEW).unwrap();
assert_eq!(repository.host, "github.com");
assert_eq!(repository.slug(), "nora-quinn/luxe-dev");
assert_eq!(repository.default_branch, "master");
assert_eq!(repository.remote, None, "chosen from the local remotes, not by gh");
}
#[test]
fn output_gh_did_not_promise_is_unreadable_rather_than_a_guess() {
assert!(matches!(parse_repository("not json"), Err(GitHubError::Unreadable(_))));
assert!(matches!(parse_account("{}", None), Err(GitHubError::Unreadable(_))));
}
/// Each failure `gh` really printed lands on the variant a caller branches on.
#[test]
fn real_gh_failures_are_classified() {
let kind = |error: GitHubError| match error {
GitHubError::NotAuthenticated { .. } => "not signed in",
GitHubError::NotGitHub => "not github",
GitHubError::NotFound => "not found",
GitHubError::RateLimited => "rate limited",
other => panic!("unclassified: {other:?}"),
};
// Each sign-in pattern on a line of real output that carries it alone, so dropping any one
// of them fails here rather than on somebody's machine
for (stderr, expected) in [
("You are not logged into any GitHub hosts.", "not signed in"),
("Try authenticating with: gh auth login -h github.com", "not signed in"),
(
"Alternatively, populate the GH_TOKEN environment variable with a GitHub API \
authentication token.",
"not signed in",
),
("HTTP 401: Requires authentication (https://api.github.com/user)", "not signed in"),
("HTTP 401: Bad credentials (https://api.github.com/graphql)", "not signed in"),
("no git remotes found", "not github"),
(
"none of the git remotes configured for this repository point to a known GitHub \
host. To tell gh about a new GitHub host, please use `gh auth login`",
"not github",
),
(
"GraphQL: Could not resolve to a Repository with the name \
'nosuchowner-zz/nosuchrepo-zz'. (repository)",
"not found",
),
// GitHub's documented wording for each way a budget runs out
("GraphQL: API rate limit exceeded for user ID 1234.", "rate limited"),
("HTTP 403: API rate limit already exceeded for user ID 1234.", "rate limited"),
(
"HTTP 403: You have exceeded a secondary rate limit. Please wait a few minutes \
before you try again.",
"rate limited",
),
("HTTP 429: Too Many Requests (https://api.github.com/graphql)", "rate limited"),
] {
assert_eq!(kind(classify_failure(stderr, "")), expected, "{stderr}");
}
}
/// Unrecognized failures keep `gh`'s words, bounded and scrubbed, and an empty one says so.
#[test]
fn an_unrecognized_failure_is_passed_through_not_guessed_at() {
let GitHubError::Failed { message } = classify_failure("", "something nobody anticipated")
else {
panic!("an unknown failure is Failed");
};
assert_eq!(message, "something nobody anticipated", "stdout is read when stderr is empty");
let GitHubError::Failed { message } = classify_failure(&"x".repeat(5_000), "") else {
panic!("an unknown failure is Failed");
};
assert!(message.chars().count() < 700, "bounded: {} chars", message.chars().count());
assert!(matches!(
classify_failure(" ", ""),
GitHubError::Failed { message } if message == "no output"
));
}

View File

@@ -0,0 +1,177 @@
//! Process — `gh` run as a real program: found, failing, fed a private file.
use super::*;
#[cfg(unix)]
pub(super) fn git(dir: &Path, args: &[&str]) {
let status = std::process::Command::new("git").args(args).current_dir(dir).status().unwrap();
assert!(status.success(), "git {args:?}");
}
/// The whole path through a real subprocess: prompts are off, stdout is the answer, and the
/// local remote that points at the repository is found.
#[cfg(unix)]
#[tokio::test]
async fn a_repository_is_resolved_through_gh_and_the_local_remotes() {
let bin = tempfile::tempdir().unwrap();
let script = format!(
"[ \"$GH_PROMPT_DISABLED\" = 1 ] || {{ echo 'prompts are on' >&2; exit 3; }}\n\
case \"$1 $2\" in\n\
'auth status') echo '{SIGNED_IN}' ;;\n\
'repo view') echo '{REPO_VIEW}' ;;\n\
esac"
);
let github = GhCli { program: Some(fake_gh(bin.path(), &script)), ..GhCli::default() };
let checkout = tempfile::tempdir().unwrap();
git(checkout.path(), &["init", "-q"]);
git(checkout.path(), &["remote", "add", "fork", "git@github.com:me/luxe-dev.git"]);
git(
checkout.path(),
&["remote", "add", "origin", "https://github.com/nora-quinn/luxe-dev.git"],
);
assert_eq!(github.account(None).await.unwrap().login, "Nora-Quinn");
let repository = github.repository(checkout.path()).await.unwrap();
assert_eq!(repository.slug(), "nora-quinn/luxe-dev");
assert_eq!(repository.remote.as_deref(), Some("origin"), "the remote that points at it");
}
/// A failing `gh` is classified from what it printed, and a missing checkout has no remote.
#[cfg(unix)]
#[tokio::test]
async fn a_failing_gh_is_classified_from_what_it_printed() {
let bin = tempfile::tempdir().unwrap();
let github = GhCli {
program: Some(fake_gh(bin.path(), "echo 'no git remotes found' >&2; exit 1")),
..GhCli::default()
};
let nowhere = tempfile::tempdir().unwrap();
assert!(matches!(github.repository(nowhere.path()).await, Err(GitHubError::NotGitHub)));
assert!(GhCli::remotes(nowhere.path()).await.is_empty(), "not a repository, no remotes");
}
/// `--repo` and, off github.com, `--hostname` reach `gh` the way it expects them.
#[cfg(unix)]
#[tokio::test]
async fn pull_request_reads_name_the_repository_and_host() {
let bin = tempfile::tempdir().unwrap();
let fixtures = bin.path().join("fixtures");
std::fs::create_dir(&fixtures).unwrap();
std::fs::write(fixtures.join("pr.json"), PR_MERGED).unwrap();
std::fs::write(fixtures.join("threads.json"), THREADS).unwrap();
std::fs::write(fixtures.join("issue.json"), ISSUE).unwrap();
let script = format!(
"case \"$*\" in\n\
'pr view 14429 --repo ghe.example.com/cli/cli --json '*) cat '{dir}/pr.json' ;;\n\
'issue view 14404 --repo ghe.example.com/cli/cli --json number,title,body,url,author,comments') cat '{dir}/issue.json' ;;\n\
'api graphql --hostname ghe.example.com -f '*' -F owner=cli -F name=cli -F number=14475') cat '{dir}/threads.json' ;;\n\
*) echo \"unexpected: $*\" >&2; exit 9 ;;\n\
esac",
dir = fixtures.display()
);
let github = GhCli { program: Some(fake_gh(bin.path(), &script)), ..GhCli::default() };
let repository = Repository {
host: "ghe.example.com".into(),
owner: "cli".into(),
name: "cli".into(),
default_branch: "trunk".into(),
remote: None,
};
assert_eq!(github.pull_request(&repository, 14429).await.unwrap().number, 14429);
assert_eq!(github.issue(&repository, 14404).await.unwrap().number, 14404);
assert_eq!(github.review_threads(&repository, 14475).await.unwrap().threads.len(), 9);
}
/// The review reaches `gh` as a file only its owner can read, which is gone afterwards; a
/// refusal comes back as GitHub's reasons rather than `HTTP 422`.
#[cfg(unix)]
#[tokio::test]
async fn a_review_is_posted_from_a_private_file_that_does_not_outlive_it() {
let bin = tempfile::tempdir().unwrap();
let seen = bin.path().join("seen");
let answer = bin.path().join("answer.json");
std::fs::write(&answer, REVIEW_POSTED).unwrap();
let script = format!(
"for last; do :; done\n\
ls -l \"$last\" | cut -c1-10 > '{seen}.mode'\n\
cat \"$last\" > '{seen}.body'\n\
echo \"$last\" > '{seen}.path'\n\
case \"$*\" in\n\
'api --method POST repos/acme/app/pulls/7/reviews --input '*) cat '{answer}' ;;\n\
*) echo \"unexpected: $*\" >&2; exit 9 ;;\n\
esac",
seen = seen.display(),
answer = answer.display()
);
let github = GhCli { program: Some(fake_gh(bin.path(), &script)), ..GhCli::default() };
let repository = Repository {
host: "github.com".into(),
owner: "acme".into(),
name: "app".into(),
default_branch: "main".into(),
remote: None,
};
let review = SubmitReview {
commit_id: "a".repeat(40),
event: ReviewEvent::Comment,
body: "Looks right to me.".into(),
comments: Vec::new(),
};
let posted = github.submit_review(&repository, 7, &review).await.unwrap();
assert_eq!(posted.id, 5307695620);
let read =
|suffix: &str| std::fs::read_to_string(format!("{}.{suffix}", seen.display())).unwrap();
assert_eq!(read("mode").trim(), "-rw-------", "only the owner can read the reader's words");
assert!(read("body").contains("Looks right to me."));
assert!(!std::path::Path::new(read("path").trim()).exists(), "removed after the post");
let refusing = GhCli {
program: Some(fake_gh(
bin.path(),
&format!("cat '{}'; echo 'gh: Unprocessable Entity (HTTP 422)' >&2; exit 1", {
let refused = bin.path().join("refused.json");
std::fs::write(&refused, REFUSED_OWN_APPROVE).unwrap();
refused.display().to_string()
}),
)),
..GhCli::default()
};
let error = refusing.submit_review(&repository, 7, &review).await.unwrap_err();
assert!(
matches!(&error, GitHubError::Rejected { reasons } if reasons[0].contains("own pull request")),
"{error:?}"
);
}
/// Resolves this very checkout through a real, signed-in `gh`, so the next host can repeat the
/// check the fixtures stand in for.
#[tokio::test]
#[ignore = "needs a signed-in gh and network access"]
async fn a_real_gh_resolves_this_repository() {
let github = GhCli::new();
let account = github.account(None).await.expect("gh is signed in");
assert!(!account.login.is_empty());
let repository =
github.repository(Path::new(env!("CARGO_MANIFEST_DIR"))).await.expect("a GitHub checkout");
assert_eq!(repository.host, "github.com");
assert!(repository.remote.is_some(), "a local remote points at {}", repository.slug());
}
/// A real search, paged: the cursor `gh` is handed brings the rows after the first page's,
/// none of them repeated, under the same count.
#[tokio::test]
#[ignore = "needs a signed-in gh and network access"]
async fn a_real_search_pages_on_from_its_cursor() {
let github = GhCli::new();
let query = "repo:cli/cli is:pr is:merged sort:updated-desc";
let first = github.search("github.com", query, None).await.expect("the first page");
assert_eq!(first.items.len(), 30);
assert!(first.total > 30, "cli/cli has merged more than a page");
let after = first.next.as_deref().expect("a cursor to the second page");
let second = github.search("github.com", query, Some(after)).await.expect("the second");
assert_eq!(second.total, first.total);
assert!(second.items.iter().all(|item| first.items.iter().all(|seen| seen.url != item.url)));
}

View File

@@ -0,0 +1,198 @@
//! Pull requests — what `gh pr view` and `gh issue view` say, read into our types.
use super::*;
// Saved verbatim from `gh` 2.101.0 against public repositories; see `fixtures/`.
pub(super) const PR_MERGED: &str = include_str!("../../fixtures/pr_view.json");
pub(super) const PR_FAILING: &str = include_str!("../../fixtures/pr_view_failing.json");
pub(super) const PR_STATUSES: &str = include_str!("../../fixtures/pr_view_statuses.json");
pub(super) const PR_BOT: &str = include_str!("../../fixtures/pr_view_bot.json");
pub(super) const ISSUE: &str = include_str!("../../fixtures/issue_view.json");
pub(super) const PR_CLOSED: &str = include_str!("../../fixtures/pr_view_closed.json");
pub(super) const THREADS: &str = include_str!("../../fixtures/review_threads.json");
pub(super) const THREADS_LEFT: &str = include_str!("../../fixtures/review_threads_left.json");
/// A merged, approved pull request: every field the brief needs, read off `cli/cli#14429`.
#[test]
fn a_pull_request_is_read_from_pr_view() {
let pr = parse_pull_request(PR_MERGED).unwrap();
assert_eq!(pr.number, 14429);
assert_eq!(pr.title, "Fix remote branch deletion for owner case mismatch");
assert!(pr.body.starts_with("Fixes #14404"), "{}", pr.body);
assert_eq!(pr.author, Author { login: "williammartin".into(), bot: false });
assert_eq!(pr.state, PullRequestState::Merged);
assert_eq!(pr.review_decision, Some(ReviewDecision::Approved));
assert!(!pr.draft && !pr.cross_repository);
assert_eq!(pr.base_ref, "trunk");
assert_eq!(pr.base_oid, "7f0590c2b8050bb04c5af52291062e6825dda9df");
assert_eq!(pr.head_oid, "a9d9d84ee3e848f0e1ea97eaef837126d3a7d983");
assert_eq!(pr.checks, CheckRollup { passed: 11, ..CheckRollup::default() });
assert_eq!(pr.closing_issues, vec![IssueRef { repository: "cli/cli".into(), number: 14404 }]);
}
/// A draft from a fork, waiting on review, with a failing check among skipped and passing ones.
#[test]
fn a_draft_fork_with_mixed_checks_is_read_as_such() {
let pr = parse_pull_request(PR_FAILING).unwrap();
assert_eq!(pr.state, PullRequestState::Open);
assert!(pr.draft && pr.cross_repository);
assert_eq!(pr.review_decision, Some(ReviewDecision::ReviewRequired));
assert_eq!(pr.checks, CheckRollup { passed: 10, failed: 1, pending: 0, skipped: 14 });
assert_eq!(pr.checks.total(), 25);
}
/// Commit statuses count too, and an empty review decision means none is asked for.
#[test]
fn commit_statuses_count_and_an_empty_decision_is_none() {
let pr = parse_pull_request(PR_STATUSES).unwrap();
assert_eq!(pr.checks, CheckRollup { passed: 2, pending: 19, ..CheckRollup::default() });
assert_eq!(pr.checks.total(), 21);
assert_eq!(pr.review_decision, None);
assert!(pr.cross_repository);
}
/// Closed without merging, after a reviewer asked for changes.
#[test]
fn a_closed_pull_request_with_changes_requested_is_read_as_such() {
let pr = parse_pull_request(PR_CLOSED).unwrap();
assert_eq!(pr.state, PullRequestState::Closed);
assert_eq!(pr.review_decision, Some(ReviewDecision::ChangesRequested));
}
/// An app is a bot, however `gh` spells its login.
#[test]
fn an_app_author_is_a_bot() {
let pr = parse_pull_request(PR_BOT).unwrap();
assert_eq!(pr.author, Author { login: "app/dependabot".into(), bot: true });
}
/// Check outcomes GitHub documents but the fixtures above do not happen to contain.
#[test]
fn every_documented_check_outcome_lands_in_a_bucket() {
let run = |status: &str, conclusion: &str| CheckEntry::CheckRun {
status: status.into(),
conclusion: conclusion.into(),
};
let status = |state: &str| CheckEntry::StatusContext { state: state.into() };
let rollup = roll_up(&[
run("IN_PROGRESS", ""),
run("QUEUED", ""),
run("COMPLETED", "NEUTRAL"),
run("COMPLETED", "TIMED_OUT"),
run("COMPLETED", "CANCELLED"),
run("COMPLETED", "ACTION_REQUIRED"),
run("COMPLETED", "STARTUP_FAILURE"),
run("COMPLETED", "STALE"),
run("COMPLETED", "SOMETHING_NEW"),
status("EXPECTED"),
status("ERROR"),
status("FAILURE"),
status("SOMETHING_NEW"),
CheckEntry::Other,
]);
assert_eq!(rollup, CheckRollup { passed: 0, failed: 7, pending: 3, skipped: 1 });
}
#[test]
fn an_issue_is_read_from_issue_view() {
let issue = parse_issue(ISSUE).unwrap();
assert_eq!(issue.number, 14404);
assert!(issue.title.starts_with("`gh pr merge NNN --delete-branch`"), "{}", issue.title);
assert!(issue.url.ends_with("/issues/14404"));
assert_eq!(issue.author, "dweomer");
assert_eq!((issue.comments.len(), issue.total_comments), (4, 4));
assert!(issue.comments.iter().all(|comment| !comment.author.is_empty()));
}
/// Only the latest few comments are kept, and none GitHub hid as spam or abuse.
#[test]
fn an_issue_keeps_its_latest_visible_comments() {
let comment = |n: usize, hidden: bool| {
format!(r#"{{"author":{{"login":"u{n}"}},"body":"c{n}","isMinimized":{hidden}}}"#)
};
let comments: Vec<String> = (1..=8).map(|n| comment(n, n == 7)).collect();
let body = format!(
r#"{{"number":1,"title":"t","body":"b","url":"u","author":null,"comments":[{}]}}"#,
comments.join(",")
);
let issue = parse_issue(&body).unwrap();
let kept: Vec<&str> = issue.comments.iter().map(|comment| comment.body.as_str()).collect();
assert_eq!(kept, ["c3", "c4", "c5", "c6", "c8"]);
assert_eq!(issue.total_comments, 8);
assert_eq!(issue.author, "", "a deleted account");
}
pub(super) const PR_HEAD_OWN: &str = include_str!("../../fixtures/pr_head_own.json");
pub(super) const PR_HEAD_FORK: &str = include_str!("../../fixtures/pr_head_fork.json");
pub(super) const PR_HEAD_FORK_NO_EDITS: &str =
include_str!("../../fixtures/pr_head_fork_no_edits.json");
pub(super) const PR_HEAD_FORK_DEFAULT: &str =
include_str!("../../fixtures/pr_head_fork_default_branch.json");
/// Real answers: your own branch, a fork (renamed) that allows maintainer edits, one that does
/// not, and one from the fork's own default branch.
#[test]
fn a_pull_requests_head_says_where_it_lives_and_who_can_push() {
let own = parse_pull_request_head(PR_HEAD_OWN).unwrap();
assert_eq!(
(own.head_ref.as_str(), own.local_branch.as_str(), own.cross_repository),
("feat/issue-to-pull-request", "feat/issue-to-pull-request", false)
);
assert_eq!(own.push, PushAccess::Allowed, "ADMIN on the repository");
let fork = parse_pull_request_head(PR_HEAD_FORK).unwrap();
assert_eq!((fork.owner.as_str(), fork.name.as_str()), ("jarrensj", "gh-cli"));
assert_eq!(fork.local_branch, "remove-claude-md");
assert_eq!(fork.push, PushAccess::NoWriteAccess, "READ on both sides");
let off = parse_pull_request_head(PR_HEAD_FORK_NO_EDITS).unwrap();
assert_eq!(off.push, PushAccess::NoWriteAccess);
let default = parse_pull_request_head(PR_HEAD_FORK_DEFAULT).unwrap();
assert_eq!(default.head_ref, "trunk");
assert_eq!(default.local_branch, "HIHACK1911/trunk", "not in place of your own trunk");
}
/// Every refusal says why, and names the fork when there is one.
#[test]
fn a_refusal_says_why_a_fix_could_not_reach_the_pull_request() {
let fork = parse_pull_request_head(PR_HEAD_FORK).unwrap();
let said = |push| PullRequestHead { push, ..fork.clone() }.refusal(14474);
assert_eq!(said(PushAccess::Allowed), None);
assert!(said(PushAccess::NoWriteAccess).unwrap().contains("comes from jarrensj/gh-cli"));
assert!(said(PushAccess::MaintainerEditsOff).unwrap().contains("did not allow edits"));
assert!(said(PushAccess::HeadRepositoryGone).unwrap().contains("was deleted"));
let own = PullRequestHead { cross_repository: false, push: PushAccess::NoWriteAccess, ..fork };
assert!(own.refusal(7).unwrap().starts_with("This account cannot push to this repository"));
}
/// The same answers from a maintainer's side: a maintainer pushes to a fork only when its
/// author allowed edits, and a deleted fork has nowhere to push.
#[test]
fn a_maintainer_pushes_to_a_fork_only_when_its_author_allowed_it() {
let as_maintainer = |body: &str| {
body.replacen("\"viewerPermission\":\"READ\"", "\"viewerPermission\":\"MAINTAIN\"", 1)
};
assert_eq!(
parse_pull_request_head(&as_maintainer(PR_HEAD_FORK)).unwrap().push,
PushAccess::Allowed
);
assert_eq!(
parse_pull_request_head(&as_maintainer(PR_HEAD_FORK_NO_EDITS)).unwrap().push,
PushAccess::MaintainerEditsOff
);
let gone = as_maintainer(PR_HEAD_FORK).replace(
"\"headRepository\":{\"name\":\"gh-cli\",\"viewerPermission\":\"READ\"}",
"\"headRepository\":null",
);
assert_eq!(parse_pull_request_head(&gone).unwrap().push, PushAccess::HeadRepositoryGone);
// Your own fork, written to directly
let yours = PR_HEAD_FORK.replace(
"{\"name\":\"gh-cli\",\"viewerPermission\":\"READ\"}",
"{\"name\":\"gh-cli\",\"viewerPermission\":\"ADMIN\"}",
);
assert_eq!(parse_pull_request_head(&yours).unwrap().push, PushAccess::Allowed);
for permission in ["WRITE", "MAINTAIN", "ADMIN"] {
assert!(can_write(Some(permission)), "{permission}");
}
assert!(!can_write(Some("TRIAGE")) && !can_write(Some("READ")) && !can_write(None));
}

View File

@@ -0,0 +1,124 @@
//! Reviews — commentable lines from a patch, a posted review, and the shape GitHub accepted.
use super::*;
pub(super) const REVIEW_POSTED: &str = include_str!("../../fixtures/review_post.json");
pub(super) const REVIEWS: &str = include_str!("../../fixtures/viewer_reviews.jsonl");
pub(super) const REFUSED_OWN_APPROVE: &str =
include_str!("../../fixtures/review_post_422_own_approve.json");
pub(super) const REFUSED_OUTSIDE_PATCH: &str =
include_str!("../../fixtures/review_post_422_outside_patch.json");
pub(super) const REFUSED_FILE_LEVEL: &str =
include_str!("../../fixtures/review_post_422_file_level.json");
/// GitHub's own hunks decide which lines take a comment, on each side.
#[test]
fn commentable_lines_come_from_githubs_patch() {
let patches = parse_patches(PR_FILES).unwrap();
assert_eq!(patches.len(), 2);
let config = patches.iter().find(|file| file.path == "rustfmt.toml").unwrap();
assert_eq!(config.commentable.left, [1, 2, 3, 4].into());
assert_eq!(config.commentable.right, [1, 2, 3, 4].into());
assert!(config.commentable.accepts(ThreadSide::Left, 1), "the removed line");
let added = patches.iter().find(|file| file.path == "scratch-review-fixture.txt").unwrap();
assert_eq!(added.commentable.right, (1..=8).collect());
assert!(added.commentable.left.is_empty(), "a new file has no old side");
assert!(!added.commentable.accepts(ThreadSide::Right, 40), "outside the patch");
}
/// Multiple hunks, a no-newline marker, and a file too large for a patch.
#[test]
fn a_patch_with_several_hunks_counts_each_from_its_header() {
let lines = commentable_lines(
"@@ -1,2 +1,2 @@\n-a\n+b\n c\n@@ -40,2 +40,3 @@ fn tail\n x\n+y\n z\n\\ No newline at end of file",
);
assert_eq!(lines.left, [1, 2, 40, 41].into());
assert_eq!(lines.right, [1, 2, 40, 41, 42].into());
let huge = parse_patches(
r#"{"filename":"big.bin","previous_filename":null,"status":"modified","patch":null}"#,
)
.unwrap();
assert_eq!(huge[0].commentable, CommentableLines::default(), "no patch, no line comments");
}
#[test]
fn a_posted_review_and_the_reviews_on_a_pull_request_are_read() {
let posted = parse_posted_review(REVIEW_POSTED).unwrap();
assert_eq!(posted.id, 5307695620);
assert!(posted.url.ends_with("#pullrequestreview-5307695620"), "{}", posted.url);
let reviews = parse_reviews(REVIEWS).unwrap();
assert_eq!(reviews.len(), 1);
assert_eq!(reviews[0].author, "nora-quinn");
assert_eq!(reviews[0].commit_id, "6277c5f225665e1d99617a5dbe7d0a416e4c3697");
assert!(reviews[0].body.starts_with("Fixture review"));
}
/// Each refusal GitHub really sent comes back as its own reasons.
#[test]
fn a_refused_post_says_what_github_said() {
for (body, reason) in [
(REFUSED_OWN_APPROVE, "Can not approve your own pull request"),
(REFUSED_OUTSIDE_PATCH, "Line could not be resolved"),
(REFUSED_FILE_LEVEL, "subjectType"),
] {
let Some(GitHubError::Rejected { reasons }) = rejection(body) else {
panic!("a refusal: {body}");
};
assert!(reasons.iter().any(|r| r.contains(reason)), "{reasons:?}");
}
assert!(rejection("not json").is_none());
assert!(rejection(REVIEW_POSTED).is_none(), "a success is not a refusal");
}
/// The body GitHub accepted for the scratch review, byte for byte in meaning: the request is a
/// published shape, and a renamed key would be refused rather than ignored.
#[test]
fn the_review_request_is_the_shape_github_accepted() {
let review = SubmitReview {
commit_id: "6277c5f225665e1d99617a5dbe7d0a416e4c3697".into(),
event: ReviewEvent::Comment,
body: "Fixture review: a body and two line comments, one on each side.".into(),
comments: vec![
super::super::super::DraftComment {
path: "scratch-review-fixture.txt".into(),
line: 4,
side: ThreadSide::Right,
start_line: None,
body: "A new-side line comment.".into(),
},
super::super::super::DraftComment {
path: "rustfmt.toml".into(),
line: 1,
side: ThreadSide::Left,
start_line: None,
body: "An old-side line comment.".into(),
},
super::super::super::DraftComment {
path: "scratch-review-fixture.txt".into(),
line: 7,
side: ThreadSide::Right,
start_line: Some(5),
body: "A multi-line comment.".into(),
},
],
};
let accepted: serde_json::Value = serde_json::from_str(
r#"{"commit_id":"6277c5f225665e1d99617a5dbe7d0a416e4c3697","event":"COMMENT","body":"Fixture review: a body and two line comments, one on each side.","comments":[{"path":"scratch-review-fixture.txt","line":4,"side":"RIGHT","body":"A new-side line comment."},{"path":"rustfmt.toml","line":1,"side":"LEFT","body":"An old-side line comment."},{"path":"scratch-review-fixture.txt","start_line":5,"start_side":"RIGHT","line":7,"side":"RIGHT","body":"A multi-line comment."}]}"#,
)
.unwrap();
assert_eq!(review_payload(&review), accepted);
for (event, spelled) in
[(ReviewEvent::Approve, "APPROVE"), (ReviewEvent::RequestChanges, "REQUEST_CHANGES")]
{
assert_eq!(review_payload(&SubmitReview { event, ..review.clone() })["event"], spelled);
}
}
/// Writes an executable stand-in for `gh` that answers from a script.
#[cfg(unix)]
pub(super) fn fake_gh(dir: &Path, body: &str) -> PathBuf {
use std::os::unix::fs::PermissionsExt;
let path = dir.join("gh");
std::fs::write(&path, format!("#!/bin/sh\n{body}\n")).unwrap();
std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o755)).unwrap();
path
}

View File

@@ -0,0 +1,268 @@
//! Threads — review threads and the conversation around them, read and answered.
use super::*;
/// Threads on removed lines count on the left, from `astral-sh/uv#21908`.
#[test]
fn a_thread_on_removed_lines_is_on_the_left() {
let threads = parse_review_threads(THREADS_LEFT).unwrap().threads;
let left: Vec<_> = threads.iter().filter(|thread| thread.side == ThreadSide::Left).collect();
assert_eq!(left.len(), 3);
assert_eq!((left[0].start_line, left[0].line), (Some(1576), Some(1583)));
}
/// A pull request GraphQL cannot see is not found, not an empty list.
#[test]
fn a_missing_pull_request_has_no_threads_rather_than_none() {
let body = r#"{"data":{"repository":{"pullRequest":null},"rateLimit":{"cost":1,"remaining":4990,"resetAt":"2026-09-24T06:55:28Z"}}}"#;
assert!(matches!(parse_review_threads(body), Err(GitHubError::NotFound)));
}
#[test]
fn gh_names_a_repository_off_github_com_by_host() {
let mut repository = parse_repository(REPO_VIEW).unwrap();
assert_eq!(repo_arg(&repository), "nora-quinn/luxe-dev");
repository.host = "ghe.example.com".into();
assert_eq!(repo_arg(&repository), "ghe.example.com/nora-quinn/luxe-dev");
assert!(repository.is("Nora-Quinn/Luxe-Dev"));
assert!(!repository.is("nora-quinn/luxe"));
}
// From the scratch pull request nora-quinn/luxe-dev#141, posted to and closed for this.
pub(super) const PR_FILES: &str = include_str!("../../fixtures/pr_files.jsonl");
pub(super) const THREADS_OWN: &str = include_str!("../../fixtures/review_threads_own.json");
pub(super) const THREAD_REPLY: &str = include_str!("../../fixtures/thread_reply.json");
pub(super) const THREADS_CONVERSATION: &str =
include_str!("../../fixtures/review_threads_conversation.json");
pub(super) const THREADS_BOT: &str = include_str!("../../fixtures/review_threads_bot.json");
pub(super) const PR_COMMENT: &str = include_str!("../../fixtures/pr_comment.json");
pub(super) const THREAD_RESOLVE: &str = include_str!("../../fixtures/thread_resolve.json");
/// A thread carries what answering it needs: its id, whether this account may reply and
/// resolve, and the line it was written on, from its patch.
#[test]
fn threads_carry_their_id_permissions_and_line() {
let threads = parse_review_threads(THREADS_OWN).unwrap().threads;
assert_eq!(threads.len(), 3);
let loop_thread = threads.iter().find(|thread| thread.line == Some(7)).unwrap();
assert!(loop_thread.id.starts_with("PRRT_"), "{}", loop_thread.id);
assert!(loop_thread.can_reply && loop_thread.can_resolve);
assert_eq!(
loop_thread.anchor_text.as_deref(),
Some(" for index in range(1, len(numbers)):")
);
let docstring = threads.iter().find(|thread| thread.line == Some(1)).unwrap();
assert_eq!(
docstring.anchor_text.as_deref(),
Some(r#""""Scratch file for a review round trip. It is deleted with its pull request.""""#)
);
// Someone else's pull request: readable, not resolvable from here
let theirs = parse_review_threads(THREADS).unwrap().threads;
assert!(theirs.iter().all(|thread| !thread.can_resolve));
assert!(theirs.iter().all(|thread| thread.id.starts_with("PRRT_")));
assert!(theirs.iter().filter(|thread| !thread.file_level).all(|t| t.anchor_text.is_some()));
}
#[test]
fn a_patch_gives_the_line_without_its_marker() {
assert_eq!(anchor_text("@@ -1 +1 @@\n-old\n+new").as_deref(), Some("new"));
assert_eq!(anchor_text("@@ -1 +1 @@\n-gone\n").as_deref(), Some("gone"));
assert_eq!(anchor_text("@@ -1,2 +1,2 @@\n kept").as_deref(), Some("kept"));
assert_eq!(anchor_text("@@ -0,0 +1 @@"), None, "a file-level thread has no line");
assert_eq!(anchor_text(""), None);
}
#[test]
fn a_reply_answers_where_it_can_be_read_and_a_resolve_must_stick() {
assert_eq!(
parse_reply(THREAD_REPLY).unwrap(),
"https://github.com/nora-quinn/luxe-dev/pull/146#discussion_r4098691176"
);
assert!(parse_resolved(THREAD_RESOLVE).is_ok());
let still_open = r#"{"data":{"resolveReviewThread":{"thread":{"isResolved":false}}}}"#;
assert!(matches!(parse_resolved(still_open), Err(GitHubError::Rejected { .. })));
let gone = r#"{"data":{"resolveReviewThread":null}}"#;
assert!(matches!(parse_resolved(gone), Err(GitHubError::NotFound)));
assert!(matches!(
parse_reply(r#"{"data":{"addPullRequestReviewThreadReply":null}}"#),
Err(GitHubError::NotFound)
));
// `gh`'s own line for an id GitHub does not know
assert!(matches!(
classify_failure("gh: Could not resolve to a node with the global id of 'PRRT_x'", ""),
GitHubError::NotFound
));
}
/// The conversation comes with the threads, as one list oldest first: a comment and a review's
/// summary alike, a minimized comment left out, and a bot marked as one. An answer from before
/// the query asked for it reads as a conversation with nothing said.
#[test]
fn the_conversation_comes_with_the_threads() {
let read = parse_review_threads(THREADS_CONVERSATION).unwrap();
assert!(read.threads.is_empty());
let said: Vec<(&str, &str)> = read
.conversation
.iter()
.map(|c| (c.id.as_str(), c.body.lines().next().unwrap_or_default()))
.collect();
assert_eq!(
said,
[
(
"IC_kwDOTyoMn88AAAABXB8h6w",
"In `scratch-note.md`, please change \"Hello\" to \"Hello from the other side!\""
),
("PRR_kwDOTyoMn88AAAABPU2kMA", "Also, end the file with a newline."),
(
"IC_kwDOTyoMn88AAAABXCnvuQ",
"> In `scratch-note.md`, please change \"Hello\" to \"Hello from the other side!\""
),
],
"the two minimized ones are gone, and the rest are in the order they were said"
);
assert_eq!(read.conversation[0].author, "nora-quinn");
assert!(read.conversation.iter().all(|comment| !comment.bot && comment.mine));
assert!(read.conversation[1].url.ends_with("#pullrequestreview-5323465776"));
// A review submitted with only line comments has no summary to say
let bot = parse_review_threads(THREADS_BOT).unwrap();
assert_eq!(bot.conversation.len(), 1, "{:?}", bot.conversation);
assert!(bot.conversation[0].bot && bot.conversation[0].author == "github-actions");
assert!(!bot.conversation[0].mine);
let before = parse_review_threads(THREADS_OWN).unwrap();
assert!(before.conversation.is_empty() && !before.threads.is_empty());
}
/// On luxe-dev#169 the reader answered the first comment from Luxe, so it and the answer stay
/// quiet, and the review's summary is what is still asked.
#[test]
fn an_answered_comment_on_a_real_pull_request_asks_nothing() {
let read = parse_review_threads(THREADS_CONVERSATION).unwrap();
let conversation = crate::guided_review::earlier_conversation(&[], read);
let ids: Vec<&str> = conversation.said().iter().map(|entry| entry.id.as_str()).collect();
assert_eq!(ids, ["PRR_kwDOTyoMn88AAAABPU2kMA"]);
}
/// Comments and review summaries interleave by when they were written, not by kind.
#[test]
fn the_conversation_is_in_the_order_it_was_said() {
let node = |id: &str, at: &str| ConversationNode {
id: id.into(),
author: None,
body: "Said.".into(),
created_at: at.into(),
url: String::new(),
is_minimized: false,
viewer_did_author: false,
};
let said = conversation(
vec![node("IC_late", "2026-05-02T12:00:00Z")],
vec![node("PRR_early", "2026-05-02T09:00:00Z")],
);
let ids: Vec<&str> = said.iter().map(|comment| comment.id.as_str()).collect();
assert_eq!(ids, ["PRR_early", "IC_late"]);
assert!(said[0].author.is_empty() && !said[0].bot, "a deleted account is nobody, not a bot");
}
#[test]
fn a_conversation_comment_answers_where_it_can_be_read() {
assert_eq!(
parse_commented(PR_COMMENT).unwrap(),
"https://github.com/nora-quinn/luxe-dev/pull/169#issuecomment-5840873033"
);
assert!(matches!(parse_commented("{}"), Err(GitHubError::Unreadable(_))));
}
/// A comment on the conversation reaches `gh` in a file rather than on the command line.
#[cfg(unix)]
#[tokio::test]
async fn a_conversation_comment_travels_in_a_file() {
let dir = tempfile::tempdir().unwrap();
let argv = dir.path().join("argv");
let seen = dir.path().join("seen");
let script = format!(
"printf '%s\\n' \"$@\" > '{argv}'\n\
prev=; for arg in \"$@\"; do [ \"$prev\" = --input ] && cat \"$arg\" > '{seen}'; prev=$arg; done\n\
cat '{reply}'",
argv = argv.display(),
seen = seen.display(),
reply = Path::new(env!("CARGO_MANIFEST_DIR")).join("src/github/fixtures/pr_comment.json").display(),
);
let gh = GhCli { deadline: GH_DEADLINE, program: Some(fake_gh(dir.path(), &script)) };
let repository = Repository {
host: "github.com".into(),
owner: "o".into(),
name: "r".into(),
default_branch: String::new(),
remote: None,
};
let url = gh.comment_on_pull_request(&repository, 7, "Added it.").await.unwrap();
assert!(url.ends_with("#issuecomment-5840873033"), "{url}");
let argv = std::fs::read_to_string(&argv).unwrap();
assert!(!argv.contains("Added it."), "{argv}");
assert!(argv.contains("repos/o/r/issues/7/comments"), "{argv}");
let seen: serde_json::Value =
serde_json::from_str(&std::fs::read_to_string(&seen).unwrap()).unwrap();
assert_eq!(seen, serde_json::json!({ "body": "Added it." }));
}
/// The reply's words reach `gh` through a file named with `@`, never as an argument another
/// user could read in a process listing.
#[cfg(unix)]
#[tokio::test]
async fn a_reply_travels_in_a_file_not_on_the_command_line() {
let dir = tempfile::tempdir().unwrap();
let argv = dir.path().join("argv");
let seen = dir.path().join("seen");
let script = format!(
"printf '%s\\n' \"$@\" > '{argv}'\n\
for arg in \"$@\"; do case \"$arg\" in body=@*) cat \"${{arg#body=@}}\" > '{seen}' ;; esac; done\n\
cat '{reply}'",
argv = argv.display(),
seen = seen.display(),
reply = Path::new(env!("CARGO_MANIFEST_DIR")).join("src/github/fixtures/thread_reply.json").display(),
);
let gh = GhCli { deadline: GH_DEADLINE, program: Some(fake_gh(dir.path(), &script)) };
let repository = Repository {
host: "github.com".into(),
owner: "o".into(),
name: "r".into(),
default_branch: String::new(),
remote: None,
};
let url = gh.reply_to_thread(&repository, "PRRT_1", "Fixed in the next push.").await.unwrap();
assert!(url.contains("#discussion_r"));
let argv = std::fs::read_to_string(&argv).unwrap();
assert!(!argv.contains("Fixed in the next push."), "{argv}");
assert!(argv.contains("thread=PRRT_1"), "{argv}");
assert_eq!(std::fs::read_to_string(&seen).unwrap(), "Fixed in the next push.");
}
/// A resolve names the thread, and an answer that leaves it open is a failure, not a success.
#[cfg(unix)]
#[tokio::test]
async fn a_resolve_names_its_thread_and_must_come_back_resolved() {
let dir = tempfile::tempdir().unwrap();
let repository = Repository {
host: "github.com".into(),
owner: "o".into(),
name: "r".into(),
default_branch: String::new(),
remote: None,
};
let open = r#"{"data":{"resolveReviewThread":{"thread":{"isResolved":false}}}}"#;
let script = format!(
"case \"$*\" in *thread=PRRT_1*) cat '{resolved}' ;; *) echo '{open}' ;; esac",
resolved = Path::new(env!("CARGO_MANIFEST_DIR"))
.join("src/github/fixtures/thread_resolve.json")
.display(),
);
let gh = GhCli { deadline: GH_DEADLINE, program: Some(fake_gh(dir.path(), &script)) };
assert!(gh.resolve_thread(&repository, "PRRT_1").await.is_ok());
assert!(matches!(
gh.resolve_thread(&repository, "PRRT_2").await,
Err(GitHubError::Rejected { .. })
));
}

View File

@@ -0,0 +1,100 @@
//! Writes — opening a pull request, and what a refusal says.
use super::*;
pub(super) const PR_OPEN: &str = include_str!("../../fixtures/pr_open.json");
pub(super) const PR_OPEN_NO_COMMITS: &str =
include_str!("../../fixtures/pr_open_422_no_commits.json");
pub(super) const PR_OPEN_EXISTS: &str = include_str!("../../fixtures/pr_open_422_exists.json");
#[test]
fn opening_a_pull_request_answers_its_number_and_refusals_say_why() {
let opened = parse_opened(PR_OPEN).unwrap();
assert_eq!(opened.number, 150);
assert!(opened.url.ends_with("/pull/150"));
for (body, reason) in [
(PR_OPEN_NO_COMMITS, "No commits between master and master"),
(PR_OPEN_EXISTS, "A pull request already exists for"),
] {
let Some(GitHubError::Rejected { reasons }) = rejection(body) else {
panic!("{body}");
};
assert!(reasons[0].starts_with(reason), "{reasons:?}");
}
}
/// The body travels in a private file named with `--input`, never on the command line, and a
/// refusal comes back as GitHub's reason.
#[cfg(unix)]
#[tokio::test]
async fn opening_sends_the_request_in_a_file_and_reads_a_refusal() {
let dir = tempfile::tempdir().unwrap();
let fixtures = Path::new(env!("CARGO_MANIFEST_DIR")).join("src/github/fixtures");
let argv = dir.path().join("argv");
let sent = dir.path().join("sent");
let script = format!(
"printf '%s\\n' \"$@\" > '{argv}'\n\
while [ \"$1\" != \"--input\" ]; do shift; done; cat \"$2\" > '{sent}'\n\
if grep -q exists '{sent}'; then cat '{exists}'; exit 1; fi\n\
cat '{opened}'",
argv = argv.display(),
sent = sent.display(),
exists = fixtures.join("pr_open_422_exists.json").display(),
opened = fixtures.join("pr_open.json").display(),
);
let gh = GhCli { deadline: GH_DEADLINE, program: Some(fake_gh(dir.path(), &script)) };
let repository = Repository {
host: "github.com".into(),
owner: "o".into(),
name: "r".into(),
default_branch: String::new(),
remote: None,
};
let request = NewPullRequest {
head: "me:topic".into(),
base: "main".into(),
title: "Fix the loop".into(),
body: "Closes #7 — the body stays private.".into(),
draft: false,
};
let opened = gh.open_pull_request(&repository, &request).await.unwrap();
assert_eq!(opened.number, 150);
let argv = std::fs::read_to_string(&argv).unwrap();
assert!(argv.contains("repos/o/r/pulls") && !argv.contains("the body stays private"), "{argv}");
let sent: serde_json::Value =
serde_json::from_str(&std::fs::read_to_string(&sent).unwrap()).unwrap();
assert_eq!(sent["head"], "me:topic");
assert_eq!(sent["draft"], false);
assert_eq!(sent["body"], "Closes #7 — the body stays private.");
let refused = NewPullRequest { title: "exists".into(), ..request };
assert!(matches!(
gh.open_pull_request(&repository, &refused).await,
Err(GitHubError::Rejected { reasons }) if reasons[0].contains("already exists")
));
}
/// Nine threads on `cli/cli#14475`: multi-line, single-line, outdated, resolved and not.
#[test]
fn review_threads_are_read_from_graphql() {
let read = parse_review_threads(THREADS).unwrap();
assert_eq!(read.total, 9);
let threads = read.threads;
assert_eq!(threads.len(), 9);
assert_eq!(threads.iter().filter(|thread| thread.resolved).count(), 5);
let first = &threads[0];
assert_eq!(first.path, ".github/skills/cli-exercise/scripts/terminal.mjs");
assert_eq!((first.start_line, first.line), (Some(16), Some(25)), "a multi-line anchor");
assert_eq!(first.side, ThreadSide::Right);
assert_eq!(first.comments.len(), 2);
assert_eq!(first.total_comments, 2);
assert!(!first.comments[0].author.is_empty());
let outdated = threads.iter().find(|thread| thread.outdated).expect("one is outdated");
assert_eq!(outdated.line, None, "an outdated thread has no line at the current head");
let single = threads.iter().find(|thread| thread.line == Some(169)).expect("line 169");
assert_eq!(single.start_line, None, "a one-line anchor has no separate start");
assert!(threads.iter().all(|thread| !thread.file_level));
}

View File

@@ -0,0 +1,357 @@
//! Threads — a pull request's review threads: reading, replying, commenting and resolving.
use super::*;
#[async_trait]
impl Threads for GhCli {
async fn review_threads(
&self,
repository: &Repository,
number: u64,
) -> Result<ReviewThreads, GitHubError> {
let query = format!("query={REVIEW_THREADS_QUERY}");
let (owner, name, number) = (
format!("owner={}", repository.owner),
format!("name={}", repository.name),
format!("number={number}"),
);
let mut args = vec!["api", "graphql"];
push_hostname(&mut args, repository);
args.extend(["-f", &query, "-F", &owner, "-F", &name, "-F", &number]);
parse_review_threads(&self.gh(&std::env::temp_dir(), &args).await?)
}
async fn reply_to_thread(
&self,
repository: &Repository,
thread_id: &str,
body: &str,
) -> Result<String, GitHubError> {
let input = PrivateFile::write(body)
.map_err(|source| GitHubError::Run { program: "gh", source })?;
let query = format!("query={REPLY_MUTATION}");
let thread = format!("thread={thread_id}");
let body = format!("body=@{}", input.path.to_string_lossy());
let mut args = vec!["api", "graphql"];
push_hostname(&mut args, repository);
// `-F body=@file` reads the value from the file, which is the point of writing one
args.extend(["-f", &query, "-f", &thread, "-F", &body]);
parse_reply(&self.gh(&std::env::temp_dir(), &args).await?)
}
async fn comment_on_pull_request(
&self,
repository: &Repository,
number: u64,
body: &str,
) -> Result<String, GitHubError> {
let payload = serde_json::json!({ "body": body });
let input = PrivateFile::write(&payload.to_string())
.map_err(|source| GitHubError::Run { program: "gh", source })?;
let endpoint =
format!("repos/{}/{}/issues/{number}/comments", repository.owner, repository.name);
let path = input.path.to_string_lossy().into_owned();
let mut args = vec!["api", "--method", "POST"];
push_hostname(&mut args, repository);
args.extend([endpoint.as_str(), "--input", path.as_str(), "--jq", "{html_url}"]);
parse_commented(&self.gh(&std::env::temp_dir(), &args).await?)
}
async fn resolve_thread(
&self,
repository: &Repository,
thread_id: &str,
) -> Result<(), GitHubError> {
let query = format!("query={RESOLVE_MUTATION}");
let thread = format!("thread={thread_id}");
let mut args = vec!["api", "graphql"];
push_hostname(&mut args, repository);
args.extend(["-f", &query, "-f", &thread]);
parse_resolved(&self.gh(&std::env::temp_dir(), &args).await?)
}
}
/// The review threads on a pull request, oldest comment first, and the latest of what was said
/// about it as a whole. One point of the GraphQL budget.
pub(super) const REVIEW_THREADS_QUERY: &str = "query($owner:String!,$name:String!,$number:Int!){\
repository(owner:$owner,name:$name){pullRequest(number:$number){\
reviewThreads(first:100){totalCount nodes{id isResolved isOutdated path line originalLine \
startLine diffSide startDiffSide subjectType viewerCanReply viewerCanResolve \
comments(first:20){totalCount nodes{author{login} body createdAt url diffHunk}}}} \
comments(last:20){nodes{id author{__typename login} body createdAt url isMinimized \
viewerDidAuthor}} \
reviews(last:20){nodes{id author{__typename login} body createdAt url viewerDidAuthor}}}} \
rateLimit{cost remaining resetAt}}";
/// Replies to a thread; the body is read from a private file, never the command line.
pub(super) const REPLY_MUTATION: &str = "mutation($thread:ID!,$body:String!){\
addPullRequestReviewThreadReply(input:{pullRequestReviewThreadId:$thread,body:$body}){\
comment{url}}}";
/// Resolves a thread.
pub(super) const RESOLVE_MUTATION: &str =
"mutation($thread:ID!){resolveReviewThread(input:{threadId:$thread}){\
thread{isResolved}}}";
/// The body of the [`REVIEW_THREADS_QUERY`] answer, down to the threads.
#[derive(Deserialize)]
pub(super) struct ThreadsAnswer {
data: ThreadsData,
}
#[derive(Deserialize)]
pub(super) struct ThreadsData {
repository: Option<ThreadsRepository>,
}
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
pub(super) struct ThreadsRepository {
pull_request: Option<ThreadsPullRequest>,
}
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
pub(super) struct ThreadsPullRequest {
review_threads: Connection<ThreadNode>,
// Absent from an answer to the query before it asked for them
#[serde(default)]
comments: Option<Nodes<ConversationNode>>,
#[serde(default)]
reviews: Option<Nodes<ConversationNode>>,
}
/// A conversation comment or a review, which carry what is said about the pull request as a whole
/// in the same fields.
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
pub(super) struct ConversationNode {
pub(super) id: String,
pub(super) author: Option<ConversationAuthor>,
#[serde(default)]
pub(super) body: String,
#[serde(default)]
pub(super) created_at: String,
#[serde(default)]
pub(super) url: String,
// Reviews are not minimizable, so theirs never comes
#[serde(default)]
pub(super) is_minimized: bool,
#[serde(default)]
pub(super) viewer_did_author: bool,
}
#[derive(Deserialize)]
pub(super) struct ConversationAuthor {
#[serde(rename = "__typename", default)]
typename: String,
login: String,
}
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
pub(super) struct ThreadNode {
#[serde(default)]
id: String,
#[serde(default)]
viewer_can_reply: bool,
#[serde(default)]
viewer_can_resolve: bool,
is_resolved: bool,
is_outdated: bool,
path: String,
line: Option<u32>,
start_line: Option<u32>,
diff_side: Option<String>,
subject_type: Option<String>,
comments: Connection<CommentNode>,
}
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
pub(super) struct CommentNode {
author: Option<CommentAuthor>,
#[serde(default)]
body: String,
#[serde(default)]
created_at: String,
#[serde(default)]
url: String,
#[serde(default)]
diff_hunk: Option<String>,
}
#[derive(Deserialize)]
pub(super) struct CommentAuthor {
login: String,
}
pub(super) fn parse_review_threads(body: &str) -> Result<ReviewThreads, GitHubError> {
let answer: ThreadsAnswer = serde_json::from_str(body).map_err(GitHubError::Unreadable)?;
let pull_request = answer
.data
.repository
.and_then(|repository| repository.pull_request)
.ok_or(GitHubError::NotFound)?;
let conversation = conversation(
pull_request.comments.map(|nodes| nodes.nodes).unwrap_or_default(),
pull_request.reviews.map(|nodes| nodes.nodes).unwrap_or_default(),
);
let connection = pull_request.review_threads;
let total = connection.total_count.max(connection.nodes.len());
let threads = connection.nodes.into_iter().map(review_thread).collect();
Ok(ReviewThreads { threads, total, conversation })
}
/// A review thread as GitHub's answer describes it, its first comment's patch read for the line it
/// was written on.
pub(super) fn review_thread(node: ThreadNode) -> ReviewThread {
ReviewThread {
id: node.id,
can_reply: node.viewer_can_reply,
can_resolve: node.viewer_can_resolve,
anchor_text: node
.comments
.nodes
.first()
.and_then(|comment| comment.diff_hunk.as_deref())
.and_then(anchor_text),
path: node.path,
line: node.line,
start_line: node.start_line.filter(|start| Some(*start) != node.line),
side: match node.diff_side.as_deref() {
Some("LEFT") => ThreadSide::Left,
_ => ThreadSide::Right,
},
outdated: node.is_outdated,
resolved: node.is_resolved,
file_level: node.subject_type.as_deref() == Some("FILE"),
total_comments: node.comments.total_count.max(node.comments.nodes.len()),
comments: node
.comments
.nodes
.into_iter()
.map(|comment| ThreadComment {
// A deleted account comes back as a null author
author: comment.author.map(|author| author.login).unwrap_or_default(),
body: comment.body,
created_at: comment.created_at,
url: comment.url,
})
.collect(),
}
}
/// The conversation comments and review summaries as one list, oldest first. A minimized comment
/// was hidden by someone with the standing to, and a review submitted with nothing but line
/// comments has no summary: neither says anything here.
pub(super) fn conversation(
comments: Vec<ConversationNode>,
reviews: Vec<ConversationNode>,
) -> Vec<ConversationComment> {
let mut said: Vec<ConversationComment> = comments
.into_iter()
.chain(reviews)
.filter(|node| !node.is_minimized && !node.body.trim().is_empty())
.map(|node| {
let (author, bot) = node
.author
.map_or((String::new(), false), |author| (author.login, author.typename == "Bot"));
ConversationComment {
id: node.id,
author,
bot,
mine: node.viewer_did_author,
body: node.body,
created_at: node.created_at,
url: node.url,
}
})
.collect();
// RFC 3339 in one zone sorts as text
said.sort_by(|a, b| a.created_at.cmp(&b.created_at));
said
}
/// The line a thread was written on: the last line of its first comment's patch, without the
/// patch's marker. `None` for a hunk header alone, which is what a file-level thread carries.
pub(super) fn anchor_text(diff_hunk: &str) -> Option<String> {
let last = diff_hunk.lines().rev().find(|line| !line.is_empty())?;
if last.starts_with("@@") {
return None;
}
let text = last.strip_prefix(['+', '-', ' ']).unwrap_or(last);
Some(text.to_string())
}
#[derive(Deserialize)]
pub(super) struct ReplyAnswer {
data: ReplyData,
}
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
pub(super) struct ReplyData {
add_pull_request_review_thread_reply: Option<ReplyPayload>,
}
#[derive(Deserialize)]
pub(super) struct ReplyPayload {
comment: ReplyComment,
}
#[derive(Deserialize)]
pub(super) struct ReplyComment {
url: String,
}
pub(super) fn parse_reply(body: &str) -> Result<String, GitHubError> {
let answer: ReplyAnswer = serde_json::from_str(body).map_err(GitHubError::Unreadable)?;
answer
.data
.add_pull_request_review_thread_reply
.map(|payload| payload.comment.url)
.ok_or(GitHubError::NotFound)
}
/// Where a new conversation comment can be read.
pub(super) fn parse_commented(body: &str) -> Result<String, GitHubError> {
#[derive(Deserialize)]
struct Commented {
html_url: String,
}
let commented: Commented = serde_json::from_str(body).map_err(GitHubError::Unreadable)?;
Ok(commented.html_url)
}
#[derive(Deserialize)]
pub(super) struct ResolveAnswer {
data: ResolveData,
}
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
pub(super) struct ResolveData {
resolve_review_thread: Option<ResolvePayload>,
}
#[derive(Deserialize)]
pub(super) struct ResolvePayload {
thread: ResolvedThread,
}
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
pub(super) struct ResolvedThread {
is_resolved: bool,
}
/// A resolve that came back unresolved is refused, not quietly counted as done.
pub(super) fn parse_resolved(body: &str) -> Result<(), GitHubError> {
let answer: ResolveAnswer = serde_json::from_str(body).map_err(GitHubError::Unreadable)?;
match answer.data.resolve_review_thread {
Some(payload) if payload.thread.is_resolved => Ok(()),
Some(_) => Err(GitHubError::Rejected { reasons: vec!["the thread is still open".into()] }),
None => Err(GitHubError::NotFound),
}
}

View File

@@ -0,0 +1,335 @@
//! Writes — the changes a status row makes: update the branch, mark it ready, merge it.
//!
//! Each is one REST call, or `gh pr ready`, run so that a refusal is read from GitHub's own answer:
//! `gh api` prints the JSON body even when the call fails, and its `message` is what GitHub said,
//! where `gh`'s own wording on stderr is not ours to parse.
use super::*;
use crate::github::overview::Merged;
#[async_trait]
impl Writes for GhCli {
async fn update_branch(
&self,
repository: &Repository,
number: u64,
expected_head: &str,
) -> Result<(), GitHubError> {
let endpoint =
format!("repos/{}/{}/pulls/{number}/update-branch", repository.owner, repository.name);
let sha = format!("expected_head_sha={expected_head}");
let mut args = vec!["api", "--method", "PUT"];
push_hostname(&mut args, repository);
args.extend([endpoint.as_str(), "-f", sha.as_str()]);
let run = self.run(&std::env::temp_dir(), &args).await?;
if run.success {
Ok(())
} else {
Err(refusal(&run))
}
}
async fn set_auto_merge(
&self,
repository: &Repository,
node_id: &str,
enable: Option<(crate::github::overview::MergeMethod, &str)>,
) -> Result<(), GitHubError> {
use crate::github::overview::MergeMethod;
let id = format!("id={node_id}");
let mut args = vec!["api", "graphql"];
push_hostname(&mut args, repository);
let (query, field, extra) = match enable {
Some((method, head)) => {
let method = match method {
MergeMethod::Merge => "method=MERGE",
MergeMethod::Squash => "method=SQUASH",
MergeMethod::Rebase => "method=REBASE",
};
(
ENABLE_AUTO_MERGE,
"enablePullRequestAutoMerge",
vec![
"-F".to_string(),
method.to_string(),
"-F".to_string(),
format!("head={head}"),
],
)
}
None => (DISABLE_AUTO_MERGE, "disablePullRequestAutoMerge", Vec::new()),
};
let query = format!("query={query}");
args.extend(["-f", query.as_str(), "-F", id.as_str()]);
args.extend(extra.iter().map(String::as_str));
let run = self.run(&std::env::temp_dir(), &args).await?;
parse_auto_merge(&run, field)
}
async fn mark_ready(&self, repository: &Repository, number: u64) -> Result<(), GitHubError> {
let number = number.to_string();
let target = repo_arg(repository);
// Already ready answers success too, which is what the reader wanted
self.gh(&std::env::temp_dir(), &["pr", "ready", &number, "--repo", &target]).await?;
Ok(())
}
async fn merge_pull_request(
&self,
repository: &Repository,
number: u64,
request: &crate::github::overview::MergeRequest,
) -> Result<crate::github::overview::Merged, GitHubError> {
use crate::github::overview::MergeMethod;
let endpoint =
format!("repos/{}/{}/pulls/{number}/merge", repository.owner, repository.name);
let method = format!(
"merge_method={}",
match request.method {
MergeMethod::Merge => "merge",
MergeMethod::Squash => "squash",
MergeMethod::Rebase => "rebase",
}
);
let sha = format!("sha={}", request.head_oid);
let mut args = vec!["api", "--method", "PUT"];
push_hostname(&mut args, repository);
args.extend([endpoint.as_str(), "-f", method.as_str(), "-f", sha.as_str()]);
let run = self.run(&std::env::temp_dir(), &args).await?;
if !run.success {
return Err(refusal(&run));
}
let commit = parse_merged(&run.stdout)?;
let Some(branch) = &request.delete_branch else {
return Ok(merged(commit, false));
};
// A repository that deletes branches on merge may have done it already: ask before deleting
// rather than reading the refusal a second delete would draw
let reference =
format!("repos/{}/{}/git/ref/heads/{branch}", repository.owner, repository.name);
let mut look = vec!["api"];
push_hostname(&mut look, repository);
look.push(reference.as_str());
match self.gh(&std::env::temp_dir(), &look).await {
Err(GitHubError::NotFound) => return Ok(merged(commit, true)),
Err(error) => {
tracing::warn!(%error, branch, "could not tell whether the merged branch remains");
return Ok(merged(commit, false));
}
Ok(_) => {}
}
let reference =
format!("repos/{}/{}/git/refs/heads/{branch}", repository.owner, repository.name);
let mut delete = vec!["api", "--method", "DELETE"];
push_hostname(&mut delete, repository);
delete.push(reference.as_str());
let deleted = self.gh(&std::env::temp_dir(), &delete).await;
if let Err(error) = &deleted {
tracing::warn!(%error, branch, "the merged branch could not be deleted");
}
Ok(merged(commit, deleted.is_ok()))
}
async fn retarget_pull_request(
&self,
repository: &Repository,
number: u64,
base: &str,
) -> Result<(), GitHubError> {
let endpoint = format!("repos/{}/{}/pulls/{number}", repository.owner, repository.name);
let field = format!("base={base}");
let mut args = vec!["api", "--method", "PATCH"];
push_hostname(&mut args, repository);
args.extend([endpoint.as_str(), "-f", field.as_str(), "--silent"]);
let ran = self.run(&std::env::temp_dir(), &args).await?;
if ran.success {
Ok(())
} else {
Err(rejection(&ran.stdout)
.unwrap_or_else(|| classify_failure(&ran.stderr, &ran.stdout)))
}
}
async fn open_pull_request(
&self,
repository: &Repository,
pull_request: &NewPullRequest,
) -> Result<OpenedPullRequest, GitHubError> {
let payload = serde_json::json!({
"title": pull_request.title,
"head": pull_request.head,
"base": pull_request.base,
"body": pull_request.body,
"draft": pull_request.draft,
});
let input = PrivateFile::write(&payload.to_string())
.map_err(|source| GitHubError::Run { program: "gh", source })?;
let endpoint = format!("repos/{}/{}/pulls", repository.owner, repository.name);
let path = input.path.to_string_lossy().into_owned();
let mut args = vec!["api", "--method", "POST"];
push_hostname(&mut args, repository);
args.extend([endpoint.as_str(), "--input", path.as_str(), "--jq", "{number, html_url}"]);
let ran = self.run(&std::env::temp_dir(), &args).await?;
if ran.success {
parse_opened(&ran.stdout)
} else {
Err(rejection(&ran.stdout)
.unwrap_or_else(|| classify_failure(&ran.stderr, &ran.stdout)))
}
}
}
/// Turns on auto-merge, naming the head the reader saw so a push in between is refused.
pub(super) const ENABLE_AUTO_MERGE: &str = "mutation($id:ID!,$method:PullRequestMergeMethod!,\
$head:GitObjectID!){enablePullRequestAutoMerge(input:{pullRequestId:$id,mergeMethod:$method,\
expectedHeadOid:$head}){pullRequest{autoMergeRequest{mergeMethod}}}}";
/// Turns auto-merge off.
pub(super) const DISABLE_AUTO_MERGE: &str = "mutation($id:ID!){disablePullRequestAutoMerge(\
input:{pullRequestId:$id}){pullRequest{autoMergeRequest{mergeMethod}}}}";
/// Why a write did not land: GitHub's own message when its answer carries one.
pub(super) fn refusal(run: &GhRun) -> GitHubError {
#[derive(Deserialize)]
struct Refused {
message: String,
}
match serde_json::from_str::<Refused>(run.stdout.trim()) {
Ok(refused) if !refused.message.trim().is_empty() => {
GitHubError::Rejected { reasons: vec![crate::github::untrusted(&refused.message, 300)] }
}
_ => classify_failure(&run.stderr, &run.stdout),
}
}
/// Whether an auto-merge mutation landed. GitHub answers a refusal with its own sentence in
/// `errors`, and a mutation that did nothing with a null in place of what it changed.
pub(super) fn parse_auto_merge(run: &GhRun, field: &str) -> Result<(), GitHubError> {
#[derive(Deserialize)]
struct Said {
message: String,
}
#[derive(Deserialize)]
struct Answer {
data: Option<serde_json::Map<String, serde_json::Value>>,
#[serde(default)]
errors: Vec<Said>,
}
let answer: Answer = match serde_json::from_str(run.stdout.trim()) {
Ok(answer) => answer,
Err(_) if !run.success => return Err(classify_failure(&run.stderr, &run.stdout)),
Err(error) => return Err(GitHubError::Unreadable(error)),
};
if let Some(said) = answer.errors.first().filter(|said| !said.message.trim().is_empty()) {
return Err(GitHubError::Rejected {
reasons: vec![crate::github::untrusted(&said.message, 300)],
});
}
match answer.data.as_ref().and_then(|data| data.get(field)) {
Some(changed) if !changed.is_null() => Ok(()),
_ => {
Err(GitHubError::Rejected { reasons: vec!["GitHub did not change auto-merge.".into()] })
}
}
}
/// The merge commit in a merge's answer.
pub(super) fn parse_merged(body: &str) -> Result<String, GitHubError> {
#[derive(Deserialize)]
struct Answer {
sha: String,
merged: bool,
}
let answer: Answer = serde_json::from_str(body).map_err(GitHubError::Unreadable)?;
match answer.merged {
true => Ok(answer.sha),
false => Err(GitHubError::Rejected { reasons: vec!["GitHub did not merge it.".into()] }),
}
}
/// A merge that landed, and whether its branch is gone.
pub(super) fn merged(sha: String, branch_deleted: bool) -> Merged {
Merged { sha, branch_deleted }
}
#[derive(Deserialize)]
struct OpenedView {
number: u64,
html_url: String,
}
pub(super) fn parse_opened(body: &str) -> Result<OpenedPullRequest, GitHubError> {
let view: OpenedView = serde_json::from_str(body).map_err(GitHubError::Unreadable)?;
Ok(OpenedPullRequest { number: view.number, url: view.html_url })
}
#[cfg(test)]
mod tests {
use super::*;
fn failed(stdout: &str, stderr: &str) -> GhRun {
GhRun { success: false, stdout: stdout.into(), stderr: stderr.into() }
}
fn ran(stdout: &str, success: bool) -> GhRun {
GhRun { success, stdout: stdout.into(), stderr: String::new() }
}
/// Auto-merge on and off land; a moved head and a missing permission read as GitHub said
/// them; a mutation answered with a bare null is a refusal, not a success.
#[test]
fn auto_merge_answers_are_read_as_github_gave_them() {
let (enable, disable) = ("enablePullRequestAutoMerge", "disablePullRequestAutoMerge");
let enabled = include_str!("../fixtures/pr_auto_merge_enabled.json");
assert!(parse_auto_merge(&ran(enabled, true), enable).is_ok());
let disabled = include_str!("../fixtures/pr_auto_merge_disabled.json");
assert!(parse_auto_merge(&ran(disabled, true), disable).is_ok());
let reason = |stdout: &str, field: &str| match parse_auto_merge(&ran(stdout, false), field)
{
Err(GitHubError::Rejected { reasons }) => reasons.join(" "),
other => panic!("refused, got {other:?}"),
};
let moved = include_str!("../fixtures/pr_auto_merge_moved.json");
assert!(reason(moved, enable).contains("expected head oid does not match"));
let forbidden = include_str!("../fixtures/pr_auto_merge_forbidden.json");
assert!(reason(forbidden, disable).contains("does not have the correct permissions"));
assert!(parse_auto_merge(&ran(r#"{"data":null}"#, true), enable).is_err());
}
/// Each refusal reads as what GitHub said: a head that moved under a merge or an update.
#[test]
fn a_refusal_is_what_github_said() {
let moved = failed(
include_str!("../fixtures/pr_merge_409_moved.json"),
"gh: Head branch was modified. Review and try the merge again. (HTTP 409)",
);
assert!(matches!(
refusal(&moved),
GitHubError::Rejected { reasons } if reasons == ["Head branch was modified. Review and try the merge again."]
));
let stale = failed(
include_str!("../fixtures/pr_update_branch_422_stale.json"),
"gh: expected head sha didn’t match current head ref. (HTTP 422)",
);
assert!(matches!(
refusal(&stale),
GitHubError::Rejected { reasons } if reasons[0].starts_with("expected head sha")
));
// Without a body to read, `gh`'s failure is classified as any other
let signed_out = failed("", "To get started with GitHub CLI, please run: gh auth login");
assert!(matches!(refusal(&signed_out), GitHubError::NotAuthenticated { .. }));
}
/// A merge answers its commit — the same one when asked twice, so a retry after a lost answer
/// does no harm.
#[test]
fn a_merge_answers_its_commit_and_a_second_ask_the_same() {
let first = parse_merged(include_str!("../fixtures/pr_merge.json")).expect("merged");
let again = parse_merged(include_str!("../fixtures/pr_merge_again.json")).expect("merged");
assert_eq!(first, "abce6b1396d97556c3a8f0beafbb681b5963d714");
assert_eq!(first, again);
assert!(include_str!("../fixtures/pr_update_branch.json")
.contains("Updating pull request branch."));
}
}

View File

@@ -0,0 +1,64 @@
//! Listing — what a search finds, and the sections a list of it is drawn in.
use super::*;
/// A pull request or an issue as a list shows it.
///
/// The title is a stranger's words; it has been through [`untrusted`], is shown, and reaches the
/// model only quoted as the title, when the reader references the row.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ListItem {
/// Whether it is a pull request, rather than an issue
pub pull_request: bool,
/// Number within its repository
pub number: u64,
/// Title, filtered and bounded
pub title: String,
/// Web address
pub url: String,
/// `owner/name`
pub repository: String,
/// Who opened it; empty for a deleted account
pub author: String,
/// Whether it is a draft pull request
pub draft: bool,
/// When it last changed, RFC 3339
pub updated_at: String,
/// Open, closed or merged; an issue is never merged. Open when a frame from before this
/// field was sent says nothing
#[serde(default = "PullRequestState::open")]
pub state: PullRequestState,
/// What its second line says in `/github`: size, checks and verdict, or labels and what closes
/// it. Absent from a frame sent before rows carried it
#[serde(default, skip_serializing_if = "Option::is_none")]
pub facts: Option<overview::RowFacts>,
}
/// One page of a GitHub search.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct SearchPage {
/// Its rows, in the search's order
pub items: Vec<ListItem>,
/// How many the search matches in all, as GitHub counts them
pub total: u64,
/// The cursor the next page starts after, when there is one
pub next: Option<String>,
}
/// One section of `/github`: its rows, or why it has none.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ListedSection {
/// What its tab says
pub name: String,
/// What its search found
pub items: Vec<ListItem>,
/// Why the search failed, as a sentence
pub error: Option<String>,
/// How many the search matches in all, which can be more than it brought. Absent from a
/// frame sent before sections carried it
#[serde(default, skip_serializing_if = "Option::is_none")]
pub total: Option<u64>,
/// The cursor the next page starts after, when the search has more than it brought
#[serde(default, skip_serializing_if = "Option::is_none")]
pub next: Option<String>,
}

View File

@@ -0,0 +1,424 @@
//! Overview — what stands between a pull request and merged, and who is already on an issue.
//!
//! The detail `/github` and `/pr` show. [`super::GitHub`] reads the facts; [`merge_checks`] turns them into
//! rows a person can act on, here rather than in a front-end, because what blocks a merge is a fact
//! every front-end needs and none should recompute.
//!
//! Every check is something GitHub reported. Branch protection details need admin access on many
//! repositories and rulesets live elsewhere, so nothing here reads the rules: `mergeStateStatus` is
//! GitHub's own answer to "can this merge", and the rest refines it.
mod readiness;
pub use readiness::{blocking, merge_checks, CheckAction, CheckMark, MergeCheck};
use serde::{Deserialize, Serialize};
use super::{Author, CheckRollup, ConversationComment, PullRequestState, ReviewDecision, Stack};
use super::{ReviewThread, ThreadComment};
/// A label on a pull request or an issue.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Label {
/// What it says
pub name: String,
/// The repository's color for it, `rrggbb`
pub color: String,
}
/// Whether a reviewer is a person, a team, or a bot.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ReviewerKind {
User,
Team,
Bot,
}
/// A reviewer's latest word on a pull request.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Verdict {
Approved,
ChangesRequested,
Commented,
Dismissed,
/// Asked to review and has not yet
Requested,
}
/// One reviewer and where they stand.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Reviewer {
/// Login, or `org/team` for a team
pub login: String,
/// Person, team or bot
pub kind: ReviewerKind,
/// Their latest verdict
pub verdict: Verdict,
/// When they gave it, or were asked, in seconds since the Unix epoch
pub at: Option<u64>,
}
/// GitHub's own answer to whether a pull request can merge.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum MergeStatus {
/// Mergeable, checks passing
Clean,
/// Mergeable, with pre-receive hooks
HasHooks,
/// Mergeable, with checks that are not passing but not required either
Unstable,
/// The head is out of date with its base
Behind,
/// Something required has not happened yet
Blocked,
/// The merge commit cannot be made cleanly
Dirty,
/// A draft cannot merge
Draft,
/// GitHub is still working it out
Unknown,
}
impl MergeStatus {
/// Whether GitHub would take the merge now.
pub const fn mergeable(self) -> bool {
matches!(self, Self::Clean | Self::HasHooks | Self::Unstable)
}
}
/// How a pull request can be merged, declared in the order GitHub offers them: a merge commit,
/// then squash, then rebase. The order is the type's, so every surface lists them the same way.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum MergeMethod {
Merge,
Squash,
Rebase,
}
impl MergeMethod {
/// How GitHub's button says it.
pub const fn label(self) -> &'static str {
match self {
Self::Merge => "Create a merge commit",
Self::Squash => "Squash and merge",
Self::Rebase => "Rebase and merge",
}
}
/// The same, as a phrase inside a sentence: `squash and merge`.
pub const fn phrase(self) -> &'static str {
match self {
Self::Merge => "merge commit",
Self::Squash => "squash and merge",
Self::Rebase => "rebase and merge",
}
}
}
/// A merge, exactly as the reader confirmed it.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct MergeRequest {
/// How it merges
pub method: MergeMethod,
/// The head the reader saw; GitHub refuses the merge if it has moved since
pub head_oid: String,
/// The head branch to delete once merged, when the reader asked and it is this repository's
pub delete_branch: Option<String>,
}
/// A merge that landed.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Merged {
/// The commit the merge made on the base
pub sha: String,
/// Whether the head branch is gone, deleted now or already
pub branch_deleted: bool,
}
/// A failing check, by name.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct FailingCheckName {
/// Its name, as GitHub lists it
pub name: String,
/// Whether branch protection requires it
pub required: bool,
}
/// What the signed-in account may do with a pull request.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct Viewer {
/// Whether it opened the pull request
pub author: bool,
/// Whether a push from here lands on its head
pub can_push: bool,
/// Whether it may merge into the base
pub can_merge: bool,
}
/// A pull request as its detail shows it.
///
/// Text fields are raw: a stranger's words, sanitized where they are drawn and quoted as data
/// wherever they head for a prompt.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct PullRequestOverview {
/// Number within its repository
pub number: u64,
/// GitHub's id for it, which its mutations name
#[serde(default)]
pub node_id: String,
/// Title, raw
pub title: String,
/// Description, raw
pub body: String,
/// Web address
pub url: String,
/// `owner/name`
pub repository: String,
/// Who opened it
pub author: Author,
/// Open, closed or merged
pub state: PullRequestState,
/// Whether it is still a draft
pub draft: bool,
/// Branch it targets
pub base_ref: String,
/// Branch it comes from
pub head_ref: String,
/// Tip of the pull request when this was read, which a merge or an update names so that it
/// refuses rather than acting on a commit the reader never saw
pub head_oid: String,
/// Whether the head branch lives in a fork
pub cross_repository: bool,
/// Lines added
pub additions: u64,
/// Lines removed
pub deletions: u64,
/// Files changed
pub changed_files: u64,
/// Commits on it
pub commits: u64,
/// When it last changed, in seconds since the Unix epoch
pub updated_at: u64,
/// Its labels
pub labels: Vec<Label>,
/// GitHub's answer to whether it can merge
pub merge_status: MergeStatus,
/// The review verdict so far, when the repository asks for one
pub review_decision: Option<ReviewDecision>,
/// Everyone asked to review, and everyone who did
pub reviewers: Vec<Reviewer>,
/// What the checks on its head say
pub checks: CheckRollup,
/// The checks failing on its head, required ones first
pub failing: Vec<FailingCheckName>,
/// Review threads nobody has resolved
pub unresolved_threads: usize,
/// Where it sits in a stack, when it is in one
pub stack: Option<Stack>,
/// What the signed-in account may do with it
pub viewer: Viewer,
/// The merge methods the repository allows, in any order; [`Self::merge_options`] puts them
/// in GitHub's
pub merge_methods: Vec<MergeMethod>,
/// What else the repository and the signed-in account bring to a merge
#[serde(default)]
pub merge_settings: MergeSettings,
/// How many entries its conversation has
pub conversation_count: usize,
}
/// What the repository and the signed-in account bring to a merge, beyond the methods allowed.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct MergeSettings {
/// The method this account last merged with in the repository, which GitHub's own button
/// opens on
pub last_method: Option<MergeMethod>,
/// Whether the repository deletes a merged head branch by itself
pub deletes_branch: bool,
/// Whether this account may turn on auto-merge now: the repository allows it, and something
/// still stands between the pull request and a merge
pub can_auto_merge: bool,
/// Whether it may turn auto-merge off
pub can_cancel_auto_merge: bool,
/// The method auto-merge will use, while it is on
pub auto_merge: Option<MergeMethod>,
}
impl PullRequestOverview {
/// The method a merge starts on: the one this account used last in the repository, as
/// GitHub's button does, when the repository still allows it; otherwise the first allowed.
pub fn default_merge_method(&self) -> MergeMethod {
let options = self.merge_options();
self.merge_settings
.last_method
.filter(|method| options.contains(method))
.unwrap_or(options[0])
}
/// The methods a merge can use, in GitHub's order — merge commit, squash, rebase — the first
/// of them the default. A repository that reported none is offered a merge commit, which is
/// what GitHub does when nothing has been turned off.
pub fn merge_options(&self) -> Vec<MergeMethod> {
let mut methods = self.merge_methods.clone();
methods.sort();
methods.dedup();
if methods.is_empty() {
methods.push(MergeMethod::Merge);
}
methods
}
}
/// A pull request that closes an issue, or mentions it.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct LinkedPullRequest {
/// Number within its repository
pub number: u64,
/// Title, raw
pub title: String,
/// Open, closed or merged
pub state: PullRequestState,
/// Whether it is a draft
pub draft: bool,
/// Who opened it
pub author: String,
/// Whether it closes the issue when it merges, rather than only mentioning it
pub closes: bool,
}
/// An issue as its detail shows it.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct IssueOverview {
/// Number within its repository
pub number: u64,
/// Title, raw
pub title: String,
/// Description, raw
pub body: String,
/// Web address
pub url: String,
/// `owner/name`
pub repository: String,
/// Who opened it
pub author: Author,
/// Open or closed; an issue is never merged
pub state: PullRequestState,
/// When it last changed, in seconds since the Unix epoch
pub updated_at: u64,
/// Its labels
pub labels: Vec<Label>,
/// Logins it is assigned to
pub assignees: Vec<String>,
/// The milestone it is in
pub milestone: Option<String>,
/// Pull requests that close it or mention it
pub linked: Vec<LinkedPullRequest>,
/// How many entries its conversation has
pub conversation_count: usize,
}
/// A session of yours that took an issue up, which only Luxe knows about.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct LocalSession {
/// The session's id, which resuming it names
pub session: String,
/// The worktree branch it works on, when it has one
pub branch: Option<String>,
/// When it was last written to, in seconds since the Unix epoch
pub last_used: u64,
}
/// One pull request's or issue's overview: what `/github`'s detail and `/pr` draw.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "kind", content = "overview", rename_all = "snake_case")]
pub enum Overview {
PullRequest(Box<PullRequestOverview>),
Issue(Box<IssueOverview>),
}
impl Overview {
/// Its number within its repository.
pub fn number(&self) -> u64 {
match self {
Self::PullRequest(pr) => pr.number,
Self::Issue(issue) => issue.number,
}
}
/// Its web address.
pub fn url(&self) -> &str {
match self {
Self::PullRequest(pr) => &pr.url,
Self::Issue(issue) => &issue.url,
}
}
}
/// What a `/github` row says under its title.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct RowFacts {
/// Whether the author is a bot
pub author_bot: bool,
/// Lines added, for a pull request
pub additions: u64,
/// Lines removed, for a pull request
pub deletions: u64,
/// What the checks on its head say, for a pull request
pub checks: CheckRollup,
/// The review verdict so far, for a pull request
pub review_decision: Option<ReviewDecision>,
/// How many comments it has
pub comments: usize,
/// Its labels
pub labels: Vec<Label>,
/// The open pull request that closes it, for an issue
pub linked_pull_request: Option<u64>,
}
/// One entry in a pull request's or an issue's conversation, oldest first.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum ConversationEntry {
/// The description, as its author opened with it
Opening {
/// Who wrote it
author: Author,
/// What they wrote, raw
body: String,
/// When, in seconds since the Unix epoch
at: u64,
},
/// A comment on the whole pull request or issue
Comment(ConversationComment),
/// A review's summary and verdict
Review {
/// The summary, as a comment
comment: ConversationComment,
/// The verdict it was submitted with
verdict: Verdict,
/// Line comments submitted with it
line_comments: usize,
},
/// A review thread on a line or a file
Thread(ReviewThread),
}
impl ConversationEntry {
/// Whether whoever started this entry is a bot.
pub fn by_bot(&self) -> bool {
match self {
Self::Opening { author, .. } => author.bot,
Self::Comment(comment) | Self::Review { comment, .. } => comment.bot,
Self::Thread(thread) => thread.comments.first().is_some_and(by_bot_login),
}
}
}
/// Whether a thread comment's author looks like a bot: GitHub Apps post as `name[bot]`.
pub fn by_bot_login(comment: &ThreadComment) -> bool {
comment.author.ends_with("[bot]")
}

View File

@@ -0,0 +1,244 @@
//! Readiness — the rows between a pull request and merged, each with what can be done about it.
use super::{MergeStatus, PullRequestOverview, Verdict};
use crate::github::{PullRequestState, ReviewDecision};
/// How a merge check reads at a glance.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CheckMark {
/// Nothing in the way
Pass,
/// In the way until someone acts
Fail,
/// In the way until something finishes, or someone else acts
Wait,
/// Worth knowing, not in the way
Note,
}
/// What a merge check offers to do about itself.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CheckAction {
/// Hand the failing steps to the agent
FixChecks,
/// Work through the unresolved review threads in Guided Review: fix, reply, resolve
ResolveThreads,
/// Bring the head up to date with its base
UpdateBranch,
/// Resolve the conflicts in a worktree session
ResolveConflicts,
/// Take it out of draft
MarkReady,
/// Open the pull request below it in its stack
OpenBelow(u64),
/// Merge it
Merge,
/// Have GitHub merge it by itself once nothing stands in the way
EnableAutoMerge,
DisableAutoMerge,
}
/// One row of "Before it can merge".
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct MergeCheck {
/// How it reads at a glance
pub mark: CheckMark,
/// What is being checked, a word or two
pub label: &'static str,
/// The evidence, as a phrase
pub detail: String,
/// What can be done about it from here
pub action: Option<CheckAction>,
}
/// The rows between a pull request and merged, blockers first and the merge itself last.
///
/// Empty for a pull request that is already merged or closed: there is nothing left to stand in
/// its way. An action is offered only where it would work for this account — `f` on someone
/// else's pull request means nothing when a push from here would be refused.
pub fn merge_checks(pr: &PullRequestOverview) -> Vec<MergeCheck> {
if pr.state != PullRequestState::Open {
return Vec::new();
}
let mut checks = Vec::new();
let check = |mark, label, detail: String, action| MergeCheck { mark, label, detail, action };
if pr.draft {
let action = (pr.viewer.author || pr.viewer.can_push).then_some(CheckAction::MarkReady);
checks.push(check(CheckMark::Fail, "Draft", "still a draft".into(), action));
}
if let Some(below) = pr.stack.as_ref().and_then(|stack| stack.below.last()) {
checks.push(check(
CheckMark::Wait,
"Stack",
format!("waits on #{} below it", below.number),
Some(CheckAction::OpenBelow(below.number)),
));
}
checks.push(checks_row(pr));
if let Some(review) = review_row(pr) {
checks.push(review);
}
if let Some(waiting) = waiting_row(pr) {
checks.push(waiting);
}
match pr.merge_status {
MergeStatus::Dirty => checks.push(check(
CheckMark::Fail,
"Conflicts",
format!("conflicts with {}", pr.base_ref),
pr.viewer.can_push.then_some(CheckAction::ResolveConflicts),
)),
MergeStatus::Behind => checks.push(check(
CheckMark::Fail,
"Up to date",
format!("behind {}", pr.base_ref),
pr.viewer.can_push.then_some(CheckAction::UpdateBranch),
)),
MergeStatus::Unknown => {
checks.push(check(CheckMark::Wait, "Conflicts", "checking".into(), None))
}
_ => checks.push(check(
CheckMark::Pass,
"Conflicts",
format!("none with {}", pr.base_ref),
None,
)),
}
let clear = checks.iter().all(|row| matches!(row.mark, CheckMark::Pass | CheckMark::Note));
// Said whenever it is on, since it merges by itself the moment the rows above clear, and
// offered whenever GitHub says this account may: it starts no run of its own, only waits
let settings = &pr.merge_settings;
if let Some(method) = settings.auto_merge {
checks.push(check(
CheckMark::Note,
"Auto-merge",
format!("{} into {} when ready", method.phrase(), pr.base_ref),
settings.can_cancel_auto_merge.then_some(CheckAction::DisableAutoMerge),
));
} else if settings.can_auto_merge {
checks.push(check(
CheckMark::Note,
"Auto-merge",
"off".into(),
Some(CheckAction::EnableAutoMerge),
));
}
if clear && pr.merge_status.mergeable() {
// Say how it will merge before anyone asks it to: merging is not easy to take back. The
// method is the one the confirmation opens on
let method = pr.default_merge_method();
checks.push(check(
CheckMark::Pass,
"Ready",
format!("{} into {}", method.phrase(), pr.base_ref),
pr.viewer.can_merge.then_some(CheckAction::Merge),
));
}
checks
}
/// How many rows are in the way.
pub fn blocking(checks: &[MergeCheck]) -> usize {
checks.iter().filter(|row| matches!(row.mark, CheckMark::Fail | CheckMark::Wait)).count()
}
fn checks_row(pr: &PullRequestOverview) -> MergeCheck {
let rollup = &pr.checks;
let total = rollup.total();
let (mark, detail, action) = if rollup.failed > 0 {
let mut names: Vec<&str> = pr.failing.iter().take(2).map(|f| f.name.as_str()).collect();
let more = rollup.failed.saturating_sub(names.len());
let mut said = format!("{} of {total} failing", rollup.failed);
if !names.is_empty() {
if more > 0 {
names.push("…");
}
said.push_str(&format!(": {}", names.join(", ")));
}
let action = pr.viewer.can_push.then_some(CheckAction::FixChecks);
(CheckMark::Fail, said, action)
} else if rollup.pending > 0 {
(CheckMark::Wait, format!("{} of {total} running", rollup.pending), None)
} else if total == 0 {
let waiting = pr.stack.as_ref().filter(|stack| stack.checks_wait_for_trunk(rollup));
match waiting {
Some(stack) => {
(CheckMark::Wait, format!("none until it targets {}", stack.trunk), None)
}
None => (CheckMark::Note, "none reported".into(), None),
}
} else {
(CheckMark::Pass, format!("{} passed", rollup.passed), None)
};
MergeCheck { mark, label: "Checks", detail, action }
}
fn review_row(pr: &PullRequestOverview) -> Option<MergeCheck> {
let resolve = pr.viewer.author.then_some(CheckAction::ResolveThreads);
let threads = match pr.unresolved_threads {
0 => None,
1 => Some("1 thread open".to_string()),
count => Some(format!("{count} threads open")),
};
let named = |verdict| -> Vec<&str> {
pr.reviewers
.iter()
.filter(|reviewer| reviewer.verdict == verdict)
.map(|reviewer| reviewer.login.as_str())
.collect()
};
let row = |mark, detail: String, action| MergeCheck { mark, label: "Review", detail, action };
let with_threads = |said: String| match &threads {
Some(threads) => format!("{said} · {threads}"),
None => said,
};
match pr.review_decision {
Some(ReviewDecision::ChangesRequested) => {
let who = named(Verdict::ChangesRequested);
let said = match who.as_slice() {
[] => "changes requested".to_string(),
[one] => format!("changes requested by {one}"),
[first, rest @ ..] => {
format!("changes requested by {first} and {} more", rest.len())
}
};
Some(row(CheckMark::Fail, with_threads(said), resolve))
}
Some(ReviewDecision::Approved) => {
let who = named(Verdict::Approved);
let said = match who.as_slice() {
[] => "approved".to_string(),
[one] => format!("approved by {one}"),
[first, rest @ ..] => format!("approved by {first} and {} more", rest.len()),
};
match threads {
Some(_) => Some(row(CheckMark::Wait, with_threads(said), resolve)),
None => Some(row(CheckMark::Pass, said, None)),
}
}
Some(ReviewDecision::ReviewRequired) => {
Some(row(CheckMark::Wait, with_threads("approval required".into()), None))
}
None => threads.map(|threads| row(CheckMark::Wait, threads, resolve)),
}
}
fn waiting_row(pr: &PullRequestOverview) -> Option<MergeCheck> {
let waiting: Vec<&str> = pr
.reviewers
.iter()
.filter(|reviewer| reviewer.verdict == Verdict::Requested)
.map(|reviewer| reviewer.login.as_str())
.collect();
let detail = match waiting.as_slice() {
[] => return None,
[one] => format!("awaiting {one}"),
[first, second] => format!("awaiting {first} and {second}"),
[first, rest @ ..] => format!("awaiting {first} and {} more", rest.len()),
};
Some(MergeCheck { mark: CheckMark::Wait, label: "Reviewers", detail, action: None })
}
#[cfg(test)]
mod tests;

View File

@@ -0,0 +1,219 @@
use super::super::{FailingCheckName, MergeMethod, Reviewer, ReviewerKind, Viewer};
use super::*;
use crate::github::{Author, CheckRollup, Stack, StackEntry};
fn pr() -> PullRequestOverview {
PullRequestOverview {
node_id: String::new(),
number: 142,
title: "Route digests by category".into(),
body: String::new(),
url: "https://github.com/acme/notify/pull/142".into(),
repository: "acme/notify".into(),
author: Author { login: "nora".into(), bot: false },
state: PullRequestState::Open,
draft: false,
base_ref: "main".into(),
head_ref: "digest-routing".into(),
head_oid: "4c1e2a0f9b".into(),
cross_repository: false,
additions: 10,
deletions: 2,
changed_files: 1,
commits: 1,
updated_at: 0,
labels: Vec::new(),
merge_status: MergeStatus::Clean,
review_decision: None,
reviewers: Vec::new(),
checks: CheckRollup { passed: 4, ..CheckRollup::default() },
failing: Vec::new(),
unresolved_threads: 0,
stack: None,
viewer: Viewer { author: true, can_push: true, can_merge: true },
merge_methods: vec![MergeMethod::Squash],
merge_settings: Default::default(),
conversation_count: 0,
}
}
fn reviewer(login: &str, verdict: Verdict) -> Reviewer {
Reviewer { login: login.into(), kind: ReviewerKind::User, verdict, at: None }
}
fn labels(checks: &[MergeCheck]) -> Vec<(&'static str, CheckMark)> {
checks.iter().map(|row| (row.label, row.mark)).collect()
}
/// Nothing in the way: the conflicts row reassures, and the last row offers the merge to
/// someone who may merge, and only to them.
#[test]
fn a_clear_pull_request_ends_on_the_merge() {
let checks = merge_checks(&pr());
assert_eq!(
labels(&checks),
[("Checks", CheckMark::Pass), ("Conflicts", CheckMark::Pass), ("Ready", CheckMark::Pass)]
);
assert_eq!(checks[0].detail, "4 passed");
assert_eq!(checks[1].detail, "none with main");
assert_eq!(checks[2].action, Some(CheckAction::Merge));
assert_eq!(checks[2].detail, "squash and merge into main");
assert_eq!(blocking(&checks), 0);
let rebase = PullRequestOverview { merge_methods: vec![MergeMethod::Rebase], ..pr() };
assert_eq!(merge_checks(&rebase)[2].detail, "rebase and merge into main");
// GitHub's order, whatever order the repository's settings arrive in
let every = PullRequestOverview {
merge_methods: vec![MergeMethod::Rebase, MergeMethod::Squash, MergeMethod::Merge],
..pr()
};
assert_eq!(
every.merge_options(),
[MergeMethod::Merge, MergeMethod::Squash, MergeMethod::Rebase]
);
assert_eq!(merge_checks(&every)[2].detail, "merge commit into main");
// The method this account used last, as the confirmation opens on it
let remembered = PullRequestOverview {
merge_settings: super::super::MergeSettings {
last_method: Some(MergeMethod::Rebase),
..Default::default()
},
..every.clone()
};
assert_eq!(merge_checks(&remembered)[2].detail, "rebase and merge into main");
let none = PullRequestOverview { merge_methods: Vec::new(), ..pr() };
assert_eq!(none.merge_options(), [MergeMethod::Merge]);
let reader = PullRequestOverview { viewer: Viewer::default(), ..pr() };
assert_eq!(merge_checks(&reader).last().unwrap().action, None);
// Mergeable by GitHub's word, but a required check never reported: no merge row
let blocked = PullRequestOverview { merge_status: MergeStatus::Blocked, ..pr() };
assert!(merge_checks(&blocked).iter().all(|row| row.label != "Ready"));
}
/// Each blocker names its evidence and carries the action that deals with it, for an account
/// that can act; a reader of someone else's pull request gets the facts and no keys.
#[test]
fn each_blocker_carries_its_own_action() {
let busy = PullRequestOverview {
draft: true,
merge_status: MergeStatus::Dirty,
review_decision: Some(ReviewDecision::ChangesRequested),
reviewers: vec![
reviewer("jon", Verdict::ChangesRequested),
reviewer("mara", Verdict::Approved),
reviewer("sam", Verdict::Requested),
],
checks: CheckRollup { passed: 11, failed: 3, ..CheckRollup::default() },
failing: vec![
FailingCheckName { name: "test (ubuntu)".into(), required: true },
FailingCheckName { name: "lint".into(), required: false },
],
unresolved_threads: 2,
..pr()
};
let checks = merge_checks(&busy);
assert_eq!(
labels(&checks),
[
("Draft", CheckMark::Fail),
("Checks", CheckMark::Fail),
("Review", CheckMark::Fail),
("Reviewers", CheckMark::Wait),
("Conflicts", CheckMark::Fail),
]
);
assert_eq!(checks[1].detail, "3 of 14 failing: test (ubuntu), lint, …");
assert_eq!(checks[2].detail, "changes requested by jon · 2 threads open");
assert_eq!(checks[3].detail, "awaiting sam");
assert_eq!(checks[4].detail, "conflicts with main");
let actions: Vec<_> = checks.iter().map(|row| row.action).collect();
assert_eq!(
actions,
[
Some(CheckAction::MarkReady),
Some(CheckAction::FixChecks),
Some(CheckAction::ResolveThreads),
None,
Some(CheckAction::ResolveConflicts),
]
);
assert_eq!(blocking(&checks), 5);
let theirs = PullRequestOverview { viewer: Viewer::default(), ..busy };
assert!(merge_checks(&theirs).iter().all(|row| row.action.is_none()));
}
#[test]
fn running_checks_and_a_stale_head_are_in_the_way() {
let running = PullRequestOverview {
checks: CheckRollup { passed: 9, pending: 3, ..CheckRollup::default() },
merge_status: MergeStatus::Behind,
..pr()
};
let checks = merge_checks(&running);
assert_eq!(checks[0].detail, "3 of 12 running");
assert_eq!(checks[0].mark, CheckMark::Wait);
assert_eq!(
(checks[1].label, checks[1].detail.as_str(), checks[1].action),
("Up to date", "behind main", Some(CheckAction::UpdateBranch))
);
assert!(checks.iter().all(|row| row.label != "Ready"));
let unknown = PullRequestOverview { merge_status: MergeStatus::Unknown, ..pr() };
let checks = merge_checks(&unknown);
assert_eq!(checks[1].detail, "checking");
assert!(checks.iter().all(|row| row.label != "Ready"), "no merge on a guess");
}
/// An approval with threads still open waits on its author; review required waits on someone
/// else, so it offers nothing.
#[test]
fn the_review_row_says_who_and_what_is_left() {
let approved = PullRequestOverview {
review_decision: Some(ReviewDecision::Approved),
reviewers: vec![reviewer("mara", Verdict::Approved), reviewer("li", Verdict::Approved)],
..pr()
};
let row = review_row(&approved).unwrap();
assert_eq!((row.mark, row.detail.as_str()), (CheckMark::Pass, "approved by mara and 1 more"));
let open = PullRequestOverview { unresolved_threads: 1, ..approved };
let row = review_row(&open).unwrap();
assert_eq!(row.detail, "approved by mara and 1 more · 1 thread open");
assert_eq!((row.mark, row.action), (CheckMark::Wait, Some(CheckAction::ResolveThreads)));
let required =
PullRequestOverview { review_decision: Some(ReviewDecision::ReviewRequired), ..pr() };
let row = review_row(&required).unwrap();
assert_eq!((row.detail.as_str(), row.action), ("approval required", None));
assert!(review_row(&pr()).is_none(), "no review asked for, no threads: no row");
}
#[test]
fn a_stacked_pull_request_waits_on_the_one_below() {
let entry = |number| StackEntry {
number,
title: String::new(),
head_ref: format!("b{number}"),
draft: false,
checked: true,
};
let stacked = PullRequestOverview {
checks: CheckRollup::default(),
stack: Some(Stack {
trunk: "main".into(),
trunk_is_default: true,
below: vec![entry(140), entry(141)],
above: Vec::new(),
}),
..pr()
};
let checks = merge_checks(&stacked);
assert_eq!(checks[0].action, Some(CheckAction::OpenBelow(141)), "the one directly below");
assert_eq!(checks[1].detail, "none until it targets main");
assert_eq!(checks[1].mark, CheckMark::Wait);
}
#[test]
fn a_finished_pull_request_has_nothing_in_its_way() {
for state in [PullRequestState::Merged, PullRequestState::Closed] {
assert!(merge_checks(&PullRequestOverview { state, ..pr() }).is_empty());
}
}

View File

@@ -0,0 +1,183 @@
//! Pull request — a pull request or an issue as GitHub describes it, and what opening one takes.
use super::*;
/// A pull request, as GitHub describes it.
///
/// Text fields are raw: they are a stranger's words and go through [`untrusted`] wherever they head
/// for a prompt or a review.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PullRequest {
/// Number within its repository
pub number: u64,
/// Title, raw
pub title: String,
/// Description, raw; empty when the author wrote none
pub body: String,
/// Web address
pub url: String,
/// Who opened it
pub author: Author,
/// Whether it is still a draft
pub draft: bool,
/// Open, closed or merged
pub state: PullRequestState,
/// Branch it targets
pub base_ref: String,
/// Tip of the target branch when this was read
pub base_oid: String,
/// Branch it comes from
pub head_ref: String,
/// Tip of the pull request when this was read
pub head_oid: String,
/// Whether the head branch lives in a fork
pub cross_repository: bool,
/// The review verdict so far, when the repository asks for one
pub review_decision: Option<ReviewDecision>,
/// What the checks on the head commit say
pub checks: CheckRollup,
/// Issues this pull request closes when it merges
pub closing_issues: Vec<IssueRef>,
}
/// Who opened a pull request or wrote a comment.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Author {
/// Account login
pub login: String,
/// Whether GitHub marks the account as a bot
pub bot: bool,
}
/// Where a pull request stands.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum PullRequestState {
Open,
Closed,
Merged,
}
impl PullRequestState {
/// Open, for a serde default.
pub fn open() -> Self {
Self::Open
}
/// How a person says it: `open`, `closed`, `merged`.
pub fn word(self) -> &'static str {
match self {
Self::Open => "open",
Self::Closed => "closed",
Self::Merged => "merged",
}
}
}
/// The review verdict GitHub reports for a pull request.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ReviewDecision {
Approved,
ChangesRequested,
ReviewRequired,
}
/// Checks on a pull request's head commit, counted by outcome.
///
/// A rollup is a fact about the pull request. It cannot say which hunk a check exercised, so it is
/// never evidence about one.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct CheckRollup {
/// Finished and succeeded
pub passed: usize,
/// Finished and failed, errored, timed out or was cancelled
pub failed: usize,
/// Queued, running, or expected and not yet reported
pub pending: usize,
/// Skipped or neutral
pub skipped: usize,
}
impl CheckRollup {
/// How many checks there are in all.
pub const fn total(&self) -> usize {
self.passed + self.failed + self.pending + self.skipped
}
}
/// An issue named by a pull request, possibly in another repository.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct IssueRef {
/// `owner/name` of the repository the issue lives in
pub repository: String,
/// Number within that repository
pub number: u64,
}
/// An issue, as GitHub describes it.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Issue {
/// Number within its repository
pub number: u64,
/// Title, raw
pub title: String,
/// Description, raw
pub body: String,
/// Web address
pub url: String,
/// Who opened it; empty for a deleted account
pub author: String,
/// The latest comments, oldest first, leaving out ones GitHub hid as spam or abuse
pub comments: Vec<IssueComment>,
/// How many comments it has in all
pub total_comments: usize,
}
/// One comment on an issue, raw.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct IssueComment {
/// Who wrote it; empty for a deleted account
pub author: String,
/// What they wrote, raw
pub body: String,
}
/// A pull request to open, exactly as the reader confirmed it.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct NewPullRequest {
/// The branch it comes from, as `owner:branch` when that is a fork
pub head: String,
/// The branch it targets
pub base: String,
/// Title
pub title: String,
/// Description, in the reader's words
pub body: String,
/// Whether it opens as a draft
pub draft: bool,
}
/// Whether a branch is on its remote, which decides whether opening its pull request pushes first.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "state", rename_all = "snake_case")]
pub enum Publication {
/// Never pushed, or pushed nowhere git knows about
Unpublished,
/// Pushed, with this many commits since
Ahead {
/// Commits not on the remote yet
commits: usize,
},
/// On the remote, every commit
Pushed,
}
/// A pull request just opened.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct OpenedPullRequest {
/// Its number
pub number: u64,
/// Where it can be read
pub url: String,
}

View File

@@ -0,0 +1,275 @@
//! Search queries — `/github`'s tabs read and rewritten as the words a reader types.
//!
//! A tab is a GitHub search with `{repo}` standing for the checkout's repository. A tab that names
//! `repo:{repo}` is *scoped*: the reader never sees that term and can never type their way out of
//! it, because GitHub ORs several `repo:` terms together, so one typed beside the scope would widen
//! it rather than narrow it. A configured tab without it searches wherever it says and is run as
//! typed. The state a tab lists (open, closed, merged, all) is a word in the query like any other,
//! rewritten here so every front-end cycles it the same way.
/// The scope term a tab names to stay in the checkout's repository.
pub const SCOPE: &str = "repo:{repo}";
/// What a search lists by state.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum State {
Open,
/// Closed without merging, for pull requests; closed, for issues
Closed,
Merged,
/// No state term at all
All,
}
impl State {
/// The word a header says it with.
pub fn word(self) -> &'static str {
match self {
Self::Open => "open",
Self::Closed => "closed",
Self::Merged => "merged",
Self::All => "all",
}
}
}
/// What a search lists by kind, which decides what its states mean.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Kind {
PullRequests,
Issues,
Both,
}
/// Whether `query` keeps to the checkout's repository.
pub fn is_scoped(query: &str) -> bool {
terms(query).iter().any(|term| term.eq_ignore_ascii_case(SCOPE))
}
/// What the reader sees and edits of `query`: everything but the scope a scoped tab carries
/// without saying.
pub fn shown(query: &str) -> String {
join(terms(query).into_iter().filter(|term| !term.eq_ignore_ascii_case(SCOPE)))
}
/// `typed` as a tab first searching `original` runs it: kept in the checkout's repository when the
/// tab was, with any repository, organization or user typed beside it dropped, and as typed when
/// it was not.
pub fn edited(original: &str, typed: &str) -> String {
if !is_scoped(original) {
return join(terms(typed));
}
let kept = terms(typed).into_iter().filter(|term| !names_a_place(term));
join(kept.chain(std::iter::once(SCOPE)))
}
/// What `query` lists by kind.
pub fn kind(query: &str) -> Kind {
let terms = terms(query);
let has =
|words: &[&str]| terms.iter().any(|t| words.iter().any(|w| t.eq_ignore_ascii_case(w)));
match (has(&["is:pr", "type:pr"]), has(&["is:issue", "type:issue"])) {
(true, false) => Kind::PullRequests,
(false, true) => Kind::Issues,
_ => Kind::Both,
}
}
/// What `query` lists by state.
pub fn state(query: &str) -> State {
let terms = terms(query);
let has =
|words: &[&str]| terms.iter().any(|t| words.iter().any(|w| t.eq_ignore_ascii_case(w)));
if has(&["is:merged"]) {
State::Merged
} else if has(&["is:closed", "state:closed"]) {
State::Closed
} else if has(&["is:open", "state:open"]) {
State::Open
} else {
State::All
}
}
/// The state after `query`'s, in the order a reader cycles them: open, closed, merged, all. An
/// issue is never merged, so a search for issues alone skips it.
pub fn next_state(query: &str) -> State {
match (state(query), kind(query)) {
(State::Open, _) => State::Closed,
(State::Closed, Kind::Issues) => State::All,
(State::Closed, _) => State::Merged,
(State::Merged, _) => State::All,
(State::All, _) => State::Open,
}
}
/// `query` listing `state` instead: every state term dropped and the new one put first, where a
/// reader looks for it.
pub fn with_state(query: &str, state: State) -> String {
let words: &[&str] = match (state, kind(query)) {
(State::Open, _) => &["is:open"],
// Closed alone would bring the merged ones too, which have a state of their own
(State::Closed, Kind::PullRequests) => &["is:closed", "is:unmerged"],
(State::Closed, _) => &["is:closed"],
(State::Merged, _) => &["is:merged"],
(State::All, _) => &[],
};
let rest = terms(query).into_iter().filter(|term| !is_state(term));
join(words.iter().copied().chain(rest))
}
/// Whether `term` says where to search: a repository, an organization or a user, or not one.
fn names_a_place(term: &str) -> bool {
let bare = term.strip_prefix('-').unwrap_or(term).to_ascii_lowercase();
["repo:", "org:", "user:"].iter().any(|qualifier| bare.starts_with(qualifier))
}
/// Whether `term` says which states to list, or which not to.
fn is_state(term: &str) -> bool {
let bare = term.strip_prefix('-').unwrap_or(term).to_ascii_lowercase();
["is:open", "is:closed", "is:merged", "is:unmerged", "state:open", "state:closed"]
.contains(&bare.as_str())
}
/// `query`'s terms, split on whitespace outside double quotes, so `label:"good first issue"` is one.
fn terms(query: &str) -> Vec<&str> {
let mut terms = Vec::new();
let mut start = None;
let mut quoted = false;
for (index, character) in query.char_indices() {
match character {
'"' => {
quoted = !quoted;
start.get_or_insert(index);
}
c if c.is_whitespace() && !quoted => {
if let Some(from) = start.take() {
terms.push(&query[from..index]);
}
}
_ => {
start.get_or_insert(index);
}
}
}
if let Some(from) = start {
terms.push(&query[from..]);
}
terms
}
fn join<'a>(terms: impl IntoIterator<Item = &'a str>) -> String {
terms.into_iter().collect::<Vec<_>>().join(" ")
}
#[cfg(test)]
mod tests {
use super::*;
const PULLS: &str = "is:open is:pr sort:updated-desc repo:{repo}";
const ISSUES: &str = "is:open is:issue sort:updated-desc repo:{repo}";
#[test]
fn a_scoped_query_shows_without_its_scope() {
assert!(is_scoped(PULLS));
assert_eq!(shown(PULLS), "is:open is:pr sort:updated-desc");
assert!(!is_scoped("is:open is:pr review-requested:@me"));
assert_eq!(shown("is:pr author:@me"), "is:pr author:@me", "spacing is tidied");
}
/// Typing a repository beside the scope would widen it, since GitHub ORs `repo:` terms, so a
/// scoped tab drops every place the reader names and keeps its own.
#[test]
fn a_scoped_tab_stays_in_its_repository_whatever_is_typed() {
assert_eq!(
edited(PULLS, "is:merged repo:other/lib -org:acme user:mara label:bug"),
"is:merged label:bug repo:{repo}"
);
assert_eq!(edited(PULLS, "REPO:Other/Lib"), "repo:{repo}", "qualifiers ignore case");
assert_eq!(edited(PULLS, ""), "repo:{repo}");
assert_eq!(edited(PULLS, "reporter"), "reporter repo:{repo}", "a word is not a qualifier");
}
#[test]
fn an_unscoped_tab_runs_as_typed() {
let everywhere = "is:open is:pr review-requested:@me archived:false";
assert_eq!(edited(everywhere, "is:pr repo:cli/cli"), "is:pr repo:cli/cli");
}
/// A phrase is one term, so a qualifier inside one is a word of it: split on every space, the
/// `is:open` in `"fix is:open bug"` would be rewritten and the phrase torn open.
#[test]
fn a_quoted_phrase_is_one_term() {
let typed = r#"label:"good first issue" "see repo:x here" repo:x/y"#;
assert_eq!(
edited(PULLS, typed),
r#"label:"good first issue" "see repo:x here" repo:{repo}"#
);
assert_eq!(
with_state(r#"is:pr "fix is:open bug""#, State::Merged),
r#"is:merged is:pr "fix is:open bug""#
);
assert_eq!(state(r#"is:pr "a is:closed b""#), State::All);
assert_eq!(kind(r#""about is:issue" is:pr"#), Kind::PullRequests);
}
#[test]
fn a_query_says_its_kind_and_state() {
assert_eq!((kind(PULLS), state(PULLS)), (Kind::PullRequests, State::Open));
assert_eq!((kind(ISSUES), state("is:issue")), (Kind::Issues, State::All));
assert_eq!(kind("type:PR is:issue"), Kind::Both);
assert_eq!(state("is:pr is:closed is:unmerged"), State::Closed);
assert_eq!(state("is:pr state:closed"), State::Closed);
assert_eq!(state("is:pr is:merged"), State::Merged);
assert_eq!(state("is:pr STATE:open"), State::Open);
}
#[test]
fn pull_requests_cycle_through_every_state() {
let mut query = PULLS.to_string();
let mut seen = Vec::new();
for _ in 0..4 {
query = with_state(&query, next_state(&query));
seen.push(query.clone());
}
assert_eq!(
seen,
[
"is:closed is:unmerged is:pr sort:updated-desc repo:{repo}",
"is:merged is:pr sort:updated-desc repo:{repo}",
"is:pr sort:updated-desc repo:{repo}",
"is:open is:pr sort:updated-desc repo:{repo}",
]
);
}
/// An issue is never merged, so its tab goes from closed straight to all.
#[test]
fn issues_skip_merged() {
let closed = with_state(ISSUES, next_state(ISSUES));
assert_eq!(closed, "is:closed is:issue sort:updated-desc repo:{repo}");
assert_eq!(next_state(&closed), State::All);
}
/// A search for both kinds closes without `is:unmerged`, which no issue matches.
#[test]
fn both_kinds_close_without_unmerged() {
assert_eq!(with_state("label:bug", State::Closed), "is:closed label:bug");
assert_eq!(next_state("is:closed label:bug"), State::Merged);
}
#[test]
fn every_state_term_is_replaced_including_negations() {
assert_eq!(
with_state("is:pr state:open -is:merged is:unmerged is:draft", State::Merged),
"is:merged is:pr is:draft"
);
}
#[test]
fn a_state_has_a_word() {
let words: Vec<&str> =
[State::Open, State::Closed, State::Merged, State::All].map(State::word).to_vec();
assert_eq!(words, ["open", "closed", "merged", "all"]);
}
}

View File

@@ -0,0 +1,215 @@
//! Refresh — when to ask GitHub about the branch's pull request again.
//!
//! GitHub has no push channel a local program can subscribe to, so the status row is kept current
//! two ways: right away after anything Luxe saw happen, and on an interval otherwise. This module
//! is the interval, and only the arithmetic of it — the workspace runtime tells it what happened
//! and asks when to look next, so every rule here is testable without a clock or a network.
//!
//! # The rules
//!
//! - Every 15 seconds while something is in flight: checks pending, or a push or a new pull
//! request in the last 10 minutes.
//! - Every `github.refresh_secs` (60 by default) once settled, and never slower than that while
//! in flight: a setting of 10 means every 10 seconds, not every 15.
//! - Every 5 minutes once the terminal has been out of focus for 2, or when the pull request is
//! closed or merged and so has nothing left to report.
//! - The settled rate while under a fifth of the hourly budget, which every tool on the same
//! sign-in shares; after a refusal for rate, nothing until the budget refills.
//! - Nothing at all after an answer that retrying cannot change (no `gh`, signed out, not GitHub),
//! or with `github.refresh_secs` at `0`. Refreshes that follow something the reader did still
//! happen; they are the caller's, not this schedule's.
use crate::permission::wildcard::matches_command;
use std::time::{Duration, Instant};
/// How often to look while checks are running or a push is fresh.
pub const ACTIVE: Duration = Duration::from_secs(15);
/// The settled interval when `github.refresh_secs` is not set.
pub const DEFAULT_REFRESH_SECS: u64 = 60;
/// How often to look while nobody is watching, or when nothing is left to change.
pub const IDLE: Duration = Duration::from_secs(300);
/// How long out of focus before the terminal counts as unwatched.
pub const AWAY_AFTER: Duration = Duration::from_secs(120);
/// How long after a push or a new pull request the checks are presumed to be starting.
pub const FRESH_FOR: Duration = Duration::from_secs(600);
/// Points left below which the schedule stops hurrying: a fifth of GitHub's 5,000 an hour.
pub const LOW_BUDGET: u32 = 1_000;
/// What the last refresh found.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Standing {
/// Not asked yet
Unknown,
/// No `gh`, signed out, or not a GitHub repository: asking again changes nothing
Unavailable,
/// The question did not get an answer this time: a timeout, a network error
Failed,
/// The branch has no pull request
NoPullRequest,
/// The branch's pull request is closed or merged
Finished,
/// The branch's pull request is open
Open {
/// Whether any check on its head is still queued or running
checks_pending: bool,
},
}
/// When the next background refresh is due, from what the runtime has told it.
#[derive(Debug, Clone)]
pub struct Schedule {
/// The settled interval, or `None` with background refresh off
settled: Option<Duration>,
last_refresh: Option<Instant>,
standing: Standing,
remaining: Option<u32>,
limited_until: Option<Instant>,
last_activity: Option<Instant>,
unfocused_since: Option<Instant>,
}
impl Schedule {
/// A schedule settling at `refresh_secs`; `0` turns background refresh off.
pub fn new(refresh_secs: u64) -> Self {
Self {
settled: (refresh_secs > 0).then(|| Duration::from_secs(refresh_secs)),
last_refresh: None,
standing: Standing::Unknown,
remaining: None,
limited_until: None,
last_activity: None,
unfocused_since: None,
}
}
/// A refresh finished at `at`, finding `standing`, with `remaining` points left when known.
pub fn refreshed(&mut self, at: Instant, standing: Standing, remaining: Option<u32>) {
self.last_refresh = Some(at);
self.standing = standing;
if remaining.is_some() {
self.remaining = remaining;
}
}
/// GitHub refused for rate at `at`, or answered with nothing left; nothing may ask again
/// before `until`.
pub fn rate_limited(&mut self, at: Instant, until: Instant) {
self.last_refresh = Some(at);
self.limited_until = Some(until.max(at));
}
/// Something that starts checks happened at `at`: a push, or a new pull request.
pub fn activity(&mut self, at: Instant) {
self.last_activity = Some(at);
}
/// The terminal gained or lost focus at `at`.
pub fn focus(&mut self, at: Instant, focused: bool) {
match (focused, self.unfocused_since) {
(true, _) => self.unfocused_since = None,
(false, None) => self.unfocused_since = Some(at),
(false, Some(_)) => {}
}
}
/// Whether asking at `now` is allowed at all. Only a rate refusal forbids it, and it forbids
/// event refreshes too, since a refused request still counts against the budget.
pub fn may_ask(&self, now: Instant) -> bool {
self.limited_until.is_none_or(|until| now >= until)
}
/// When the next background refresh is due, or `None` when there is none to schedule.
pub fn next(&self, now: Instant) -> Option<Instant> {
let settled = self.settled?;
if let Some(until) = self.limited_until.filter(|until| *until > now) {
return Some(until);
}
if self.standing == Standing::Unavailable {
return None;
}
let Some(last) = self.last_refresh else {
return Some(now);
};
Some(last + self.interval(settled, now))
}
fn interval(&self, settled: Duration, now: Instant) -> Duration {
let idle = IDLE.max(settled);
let away = self
.unfocused_since
.is_some_and(|since| now.saturating_duration_since(since) >= AWAY_AFTER);
if away {
return idle;
}
if self.remaining.is_some_and(|left| left < LOW_BUDGET) {
return settled;
}
let fresh =
self.last_activity.is_some_and(|at| now.saturating_duration_since(at) < FRESH_FOR);
let pending = self.standing == Standing::Open { checks_pending: true };
if fresh || pending {
return ACTIVE.min(settled);
}
if self.standing == Standing::Finished {
return idle;
}
settled
}
}
/// What a tool call means for the branch's pull request, once it has finished.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Touch {
/// Nothing GitHub would know about
None,
/// It read or changed the pull request, so what the row shows may be stale
Changed,
/// It started checks: a push, a new pull request, a re-run
Started,
}
/// What `tool` called with `arguments` did to the branch's pull request.
///
/// `bash` commands are matched segment by segment with the permission engine's own splitter, so
/// `cargo fmt && git push` counts the same as `git push`.
pub fn touch(tool: &str, arguments: &serde_json::Value) -> Touch {
match tool {
"git" if arguments.get("action").and_then(|action| action.as_str()) == Some("pr") => {
let first = arguments
.get("args")
.and_then(|args| args.as_array())
.and_then(|args| args.first())
.and_then(|arg| arg.as_str());
if first == Some("create") {
Touch::Started
} else {
Touch::Changed
}
}
"bash" => {
let Some(command) = arguments.get("command").and_then(|command| command.as_str())
else {
return Touch::None;
};
let any = |patterns: &[&str]| {
patterns.iter().any(|pattern| matches_command(command, pattern))
};
if any(&["git push *", "gh pr create *", "gh run rerun *", "gh workflow run *"]) {
Touch::Started
} else if any(&["gh pr *", "gh issue *", "gh run *"]) {
Touch::Changed
} else {
Touch::None
}
}
_ => Touch::None,
}
}
#[cfg(test)]
mod tests;

View File

@@ -0,0 +1,191 @@
use super::*;
use serde_json::json;
#[test]
fn pushes_and_new_pull_requests_start_checks() {
for (tool, arguments) in [
("bash", json!({"command": "git push"})),
("bash", json!({"command": "cargo fmt && git push -u origin topic"})),
("bash", json!({"command": "gh pr create --fill"})),
("bash", json!({"command": "gh run rerun 123 --failed"})),
("bash", json!({"command": "gh workflow run ci.yml"})),
("git", json!({"action": "pr", "args": ["create", "--title", "t"]})),
] {
assert_eq!(touch(tool, &arguments), Touch::Started, "{tool} {arguments}");
}
}
#[test]
fn reading_or_changing_a_pull_request_makes_the_row_stale() {
for (tool, arguments) in [
("bash", json!({"command": "gh pr view"})),
("bash", json!({"command": "gh pr merge 12 --squash"})),
("bash", json!({"command": "gh issue close 3"})),
("bash", json!({"command": "gh run view 9 --log-failed | tail"})),
("git", json!({"action": "pr", "args": ["view"]})),
("git", json!({"action": "pr"})),
] {
assert_eq!(touch(tool, &arguments), Touch::Changed, "{tool} {arguments}");
}
}
#[test]
fn everything_else_is_nothing_github_knows_about() {
for (tool, arguments) in [
("bash", json!({"command": "git status"})),
("bash", json!({"command": "echo gh pr view"})),
("bash", json!({})),
("git", json!({"action": "commit", "message": "gh pr create"})),
("read", json!({"path": "git push"})),
] {
assert_eq!(touch(tool, &arguments), Touch::None, "{tool} {arguments}");
}
}
const SETTLED: Duration = Duration::from_secs(DEFAULT_REFRESH_SECS);
fn secs(n: u64) -> Duration {
Duration::from_secs(n)
}
/// A schedule that last refreshed at `t0`, finding `standing` with plenty of budget.
fn after(t0: Instant, standing: Standing) -> Schedule {
let mut schedule = Schedule::new(DEFAULT_REFRESH_SECS);
schedule.refreshed(t0, standing, Some(4_000));
schedule
}
/// The numbers the module doc and the guide promise.
#[test]
fn the_documented_rates_are_the_ones_used() {
assert_eq!(
[ACTIVE, SETTLED, IDLE, AWAY_AFTER, FRESH_FOR],
[secs(15), secs(60), secs(300), secs(120), secs(600)]
);
assert_eq!(LOW_BUDGET, 5_000 / 5);
}
#[test]
fn the_first_refresh_is_due_at_once_and_zero_turns_it_off() {
let now = Instant::now();
assert_eq!(Schedule::new(60).next(now), Some(now));
assert_eq!(Schedule::new(0).next(now), None);
}
#[test]
fn a_settled_open_pull_request_is_checked_at_the_settled_rate() {
let t0 = Instant::now();
let schedule = after(t0, Standing::Open { checks_pending: false });
assert_eq!(schedule.next(t0), Some(t0 + SETTLED));
assert_eq!(after(t0, Standing::NoPullRequest).next(t0), Some(t0 + SETTLED));
assert_eq!(after(t0, Standing::Failed).next(t0), Some(t0 + SETTLED));
}
#[test]
fn pending_checks_are_watched_closely() {
let t0 = Instant::now();
let schedule = after(t0, Standing::Open { checks_pending: true });
assert_eq!(schedule.next(t0), Some(t0 + ACTIVE));
}
/// A push starts checks GitHub may not report for a while, and a pull request opened in the
/// browser after it should turn up quickly, so for ten minutes the branch is watched closely
/// whatever the last answer was.
#[test]
fn a_fresh_push_is_watched_closely_for_ten_minutes() {
let t0 = Instant::now();
let mut schedule = after(t0, Standing::NoPullRequest);
schedule.activity(t0);
assert_eq!(schedule.next(t0), Some(t0 + ACTIVE));
let later = t0 + FRESH_FOR - secs(1);
schedule.refreshed(later, Standing::NoPullRequest, None);
assert_eq!(schedule.next(later), Some(later + ACTIVE));
let stale = t0 + FRESH_FOR;
schedule.refreshed(stale, Standing::NoPullRequest, None);
assert_eq!(schedule.next(stale), Some(stale + SETTLED));
}
#[test]
fn a_finished_pull_request_has_nothing_left_to_report() {
let t0 = Instant::now();
assert_eq!(after(t0, Standing::Finished).next(t0), Some(t0 + IDLE));
// unless a push says something is starting again
let mut schedule = after(t0, Standing::Finished);
schedule.activity(t0);
assert_eq!(schedule.next(t0), Some(t0 + ACTIVE));
}
#[test]
fn nobody_watching_for_two_minutes_slows_everything_down() {
let t0 = Instant::now();
let mut schedule = after(t0, Standing::Open { checks_pending: true });
schedule.focus(t0, false);
let soon = t0 + AWAY_AFTER - secs(1);
assert_eq!(schedule.next(soon), Some(t0 + ACTIVE), "not away yet");
let away = t0 + AWAY_AFTER;
assert_eq!(schedule.next(away), Some(t0 + IDLE));
// a second focus-out does not restart the clock, and coming back resets it
schedule.focus(away, false);
assert_eq!(schedule.next(away), Some(t0 + IDLE));
schedule.focus(away, true);
assert_eq!(schedule.next(away), Some(t0 + ACTIVE));
}
#[test]
fn a_low_budget_stops_the_hurry_but_not_the_settled_rate() {
let t0 = Instant::now();
let mut schedule = Schedule::new(DEFAULT_REFRESH_SECS);
schedule.refreshed(t0, Standing::Open { checks_pending: true }, Some(LOW_BUDGET - 1));
assert_eq!(schedule.next(t0), Some(t0 + SETTLED));
schedule.refreshed(t0, Standing::Open { checks_pending: true }, Some(LOW_BUDGET));
assert_eq!(schedule.next(t0), Some(t0 + ACTIVE));
// an answer that did not report the budget keeps the last one known
schedule.refreshed(t0, Standing::Open { checks_pending: true }, Some(10));
schedule.refreshed(t0, Standing::Open { checks_pending: true }, None);
assert_eq!(schedule.next(t0), Some(t0 + SETTLED));
}
/// A refusal for rate stops everything, event refreshes included, until the refill.
#[test]
fn a_rate_refusal_waits_for_the_refill() {
let t0 = Instant::now();
let refill = t0 + secs(900);
let mut schedule = after(t0, Standing::Open { checks_pending: true });
schedule.rate_limited(t0, refill);
assert!(!schedule.may_ask(t0));
assert!(!schedule.may_ask(refill - secs(1)));
assert!(schedule.may_ask(refill));
assert_eq!(schedule.next(t0), Some(refill));
assert_eq!(schedule.next(refill), Some(t0 + ACTIVE), "due as soon as it may ask");
assert!(Schedule::new(60).may_ask(t0));
}
#[test]
fn a_refill_already_past_does_not_hold_anything_up() {
let t0 = Instant::now() + secs(1_000);
let mut schedule = after(t0, Standing::NoPullRequest);
schedule.rate_limited(t0, t0 - secs(10));
assert!(schedule.may_ask(t0));
}
#[test]
fn an_answer_retrying_cannot_change_stops_the_interval() {
let t0 = Instant::now();
assert_eq!(after(t0, Standing::Unavailable).next(t0), None);
}
/// The setting is the settled rate, and the ceiling on every other: at 10 seconds it never
/// waits 15, and at ten minutes being away is no faster than being here.
#[test]
fn the_setting_bounds_the_active_and_idle_rates() {
let t0 = Instant::now();
let mut fast = Schedule::new(10);
fast.refreshed(t0, Standing::Open { checks_pending: true }, Some(4_000));
assert_eq!(fast.next(t0), Some(t0 + secs(10)));
let mut slow = Schedule::new(600);
slow.refreshed(t0, Standing::Finished, Some(4_000));
assert_eq!(slow.next(t0), Some(t0 + secs(600)));
slow.refreshed(t0, Standing::Open { checks_pending: true }, Some(4_000));
assert_eq!(slow.next(t0), Some(t0 + ACTIVE));
}

Some files were not shown because too many files have changed in this diff Show More