From 1f7e7027e8db025829aa14e51ef24fb509c055d8 Mon Sep 17 00:00:00 2001 From: "pi-agent-action[bot]" <339978130+pi-agent-action[bot]@users.noreply.github.com> Date: Sat, 7 Nov 2026 17:19:20 +0000 Subject: [PATCH] Add PR merge confirmation and remote branch deletion Co-authored-by: Valian <92361802+lw396@users.noreply.github.com> --- mods/github/main.js | 131 ++++++++++++++++++++++++++++++++- src/github/core/merge.ts | 50 +++++++++++++ src/github/core/pull-detail.ts | 1 + src/github/io/changes.ts | 1 + src/github/io/pulls.ts | 36 +++++++++ src/github/views/panel.ts | 4 +- src/github/views/pull.ts | 87 +++++++++++++++++++++- test/core/merge.test.ts | 24 ++++++ test/io/merge.test.ts | 30 ++++++++ test/io/pull-detail.test.ts | 3 + 10 files changed, 363 insertions(+), 4 deletions(-) create mode 100644 src/github/core/merge.ts create mode 100644 test/core/merge.test.ts create mode 100644 test/io/merge.test.ts diff --git a/mods/github/main.js b/mods/github/main.js index 2089035..6ee3721 100644 --- a/mods/github/main.js +++ b/mods/github/main.js @@ -10283,6 +10283,27 @@ async function localBranches(remote2, { cwd, on }) { return { branches, head: pickRemote(origin) ?? pickRemote(other) ?? remote2 }; } +// src/github/core/merge.ts +function mergeInfo(p, r) { + const methods = ["merge", "squash", "rebase"].filter((m) => r[`allow_${m}_merge`] === true); + const reasons = { + dirty: "This branch has conflicts that must be resolved", + blocked: "Merging is blocked by branch protection rules (required checks or reviews)", + behind: "This branch is out-of-date with the base branch", + unknown: "Checking mergeability\u2026", + unstable: "Checks have not passed" + }; + const reason = p.merged ? "Pull request successfully merged" : p.state !== "open" ? "Pull request is closed" : p.draft ? "This pull request is still a draft" : p.mergeable !== true ? reasons[p.mergeable_state ?? "unknown"] ?? "Checking mergeability\u2026" : p.mergeable_state !== "clean" && p.mergeable_state !== "has_hooks" ? reasons[p.mergeable_state ?? "unknown"] ?? `Merging is blocked: ${p.mergeable_state}` : methods.length === 0 ? "No merge methods are enabled" : null; + return { + methods, + reason, + sha: p.head.sha, + headRepo: p.head.repo?.full_name ?? null, + headRef: p.head.ref, + deletable: Boolean(p.merged && p.head.repo && p.head.ref !== p.head.repo.default_branch) + }; +} + // src/github/core/pull-detail.ts function reviewers(pull, reviews) { const byName = /* @__PURE__ */ new Map(); @@ -10413,6 +10434,10 @@ async function readPull(repo, number, on) { api(`repos/${repo}/pulls/${number}/reviews?per_page=100`, { on, paginate: true }) ]); const detail = parsePullDetail(pull, issue, comments, reviews); + detail.merge = mergeInfo( + pull, + await api(`repos/${repo}`, { on }) + ); const sha = pull.head.sha; const [events, inline, checks, statuses] = await Promise.all([ api(`repos/${repo}/issues/${number}/timeline?per_page=100`, { on, paginate: true }), @@ -10428,8 +10453,31 @@ async function readPull(repo, number, on) { detail.url ); detail.checks = parseChecks(Array.isArray(checks) ? checks : [checks], statuses); + if (detail.merge?.reason?.startsWith("Merging is blocked by")) { + const reasons = []; + if (detail.reviewers.some((r) => r.state === "changes_requested")) reasons.push("Changes requested"); + if (detail.reviewers.some((r) => r.state === "requested")) reasons.push("Review required"); + if (detail.checks.some((c) => /fail|pending|queued|progress|error/i.test(c.status))) + reasons.push("Checks have not passed"); + if (reasons.length) detail.merge.reason += ": " + reasons.join("; "); + } return detail; } +async function mergePull(repo, number, method, sha, on) { + const result = await api(`repos/${repo}/pulls/${number}/merge`, { + on, + method: "PUT", + rawFields: { merge_method: method, sha } + }); + if (!result.merged) throw new Error(result.message); +} +async function deletePullBranch(info, on) { + if (!info.deletable || !info.headRepo) throw new Error("This branch cannot be deleted"); + await api(`repos/${info.headRepo}/git/refs/heads/${info.headRef.split("/").map(encodeURIComponent).join("/")}`, { + on, + method: "DELETE" + }); +} async function localPulls(remote2, { branches, head }, on) { if (branches.length === 0) return []; return parseLocalPulls(await graphql(localPullsQuery(remote2, branches), on), head); @@ -10905,7 +10953,9 @@ var Panel = class { * then the shown expanded groups ask GitHub again (the change made them stale). */ receive(cx) { - const changes2 = this.notices.take().flatMap((n) => n.state ? [n.state] : []); + const notices = this.notices.take(); + if (notices.some((n) => n.pull)) this.pulls.load(cx, true); + const changes2 = notices.flatMap((n) => n.state ? [n.state] : []); if (changes2.length === 0) return; changes2.forEach(issueChanged); this.issues.show(); @@ -11458,6 +11508,10 @@ var REVIEWS = { dismissed: { label: "Review dismissed", icon: "\u2212", color: "dim" } }; var Pull = class { + method = null; + confirming = false; + writing = false; + writeFailure = ""; ref = null; entry = null; host; @@ -11465,6 +11519,9 @@ var Pull = class { this.host = host; } show(cx, ref) { + this.method = null; + this.confirming = false; + this.writeFailure = ""; this.ref = ref; this.entry = null; this.load(cx); @@ -11532,6 +11589,7 @@ var Pull = class { ], [ postCard("pull-body", pull, "opened this pull request", onLink), + this.mergeArea(pull), ...(pull.timeline ?? []).map( (item, index2) => v_flex5().gap(8).child(postCard(`pull-event-${index2}`, item, item.verb, onLink)).children( item.discussion.map( @@ -11554,6 +11612,77 @@ var Pull = class { ] ); } + mergeArea(pull) { + const info = pull.merge; + const area = v_flex5().gap(10).child(div9().font_semibold().child("Merge")); + if (!info) return area; + area.child(quiet(info.reason ?? "This branch has no conflicts with the base branch")); + if (this.writeFailure) area.child(quiet(this.writeFailure)); + const act = (cx, remove) => { + const ref = this.ref, place = detailLocation(this.host.reader); + if (!ref || !place || this.writing) return; + this.writing = true; + cx.spawn(async (cx2) => { + try { + if (remove) { + await deletePullBranch(info, place.on); + info.deletable = false; + } else await mergePull(ref.repo, ref.number, this.method ?? info.methods[0], info.sha, place.on); + announce({ repo: ref.repo, number: ref.number, pull: true }); + if (this.ref === ref) { + this.confirming = false; + this.writeFailure = ""; + if (!remove) this.load(cx2); + } + } catch (e) { + if (this.ref === ref) this.writeFailure = failureOf(e).message; + } finally { + this.writing = false; + cx2.notify(); + } + }); + }; + if (this.writing) return area.child(quiet("Updating pull request\u2026")); + if (info.deletable) + area.child(button("delete-branch", "Delete branch", "Delete remote branch", (_e, cx) => act(cx, true))); + if (!info.reason) { + for (const method of info.methods) + area.child( + button( + `method-${method}`, + `${(this.method ?? info.methods[0]) === method ? "\u25CF" : "\u25CB"} ${method === "merge" ? "Create a merge commit" : method === "squash" ? "Squash and merge" : "Rebase and merge"}`, + "Merge method", + (_e, cx) => { + this.method = method; + this.confirming = false; + cx.notify(); + } + ) + ); + area.child( + button( + "merge-confirm", + this.confirming ? "Confirm Merge" : "Merge Pull Request", + "Merge pull request", + (_e, cx) => { + if (this.confirming) act(cx, false); + else { + this.confirming = true; + cx.notify(); + } + } + ) + ); + if (this.confirming) + area.child( + button("merge-cancel", "Cancel", "Cancel merge", (_e, cx) => { + this.confirming = false; + cx.notify(); + }) + ); + } + return area; + } reviewers(pull) { const t = colors(); if (pull.reviewers.length === 0) return quiet("None yet"); diff --git a/src/github/core/merge.ts b/src/github/core/merge.ts new file mode 100644 index 0000000..aa86154 --- /dev/null +++ b/src/github/core/merge.ts @@ -0,0 +1,50 @@ +export type MergeMethod = "merge" | "squash" | "rebase"; +export interface MergeInfo { + methods: MergeMethod[]; + reason: string | null; + sha: string; + headRepo: string | null; + headRef: string; + deletable: boolean; +} +export function mergeInfo( + p: { + mergeable?: boolean | null; + mergeable_state?: string; + draft?: boolean; + state: string; + merged?: boolean; + head: { sha: string; ref: string; repo: { full_name: string; default_branch: string } | null }; + }, + r: Record, +): MergeInfo { + const methods = (["merge", "squash", "rebase"] as MergeMethod[]).filter((m) => r[`allow_${m}_merge`] === true); + const reasons: Record = { + dirty: "This branch has conflicts that must be resolved", + blocked: "Merging is blocked by branch protection rules (required checks or reviews)", + behind: "This branch is out-of-date with the base branch", + unknown: "Checking mergeability…", + unstable: "Checks have not passed", + }; + const reason = p.merged + ? "Pull request successfully merged" + : p.state !== "open" + ? "Pull request is closed" + : p.draft + ? "This pull request is still a draft" + : p.mergeable !== true + ? (reasons[p.mergeable_state ?? "unknown"] ?? "Checking mergeability…") + : p.mergeable_state !== "clean" && p.mergeable_state !== "has_hooks" + ? (reasons[p.mergeable_state ?? "unknown"] ?? `Merging is blocked: ${p.mergeable_state}`) + : methods.length === 0 + ? "No merge methods are enabled" + : null; + return { + methods, + reason, + sha: p.head.sha, + headRepo: p.head.repo?.full_name ?? null, + headRef: p.head.ref, + deletable: Boolean(p.merged && p.head.repo && p.head.ref !== p.head.repo.default_branch), + }; +} diff --git a/src/github/core/pull-detail.ts b/src/github/core/pull-detail.ts index ceb7cbb..506e6e6 100644 --- a/src/github/core/pull-detail.ts +++ b/src/github/core/pull-detail.ts @@ -13,6 +13,7 @@ export interface Reviewer { } export interface PullDetail { + merge?: import("./merge.ts").MergeInfo; number: number; title: string; state: PullState; diff --git a/src/github/io/changes.ts b/src/github/io/changes.ts index 5faf4d5..79d7161 100644 --- a/src/github/io/changes.ts +++ b/src/github/io/changes.ts @@ -6,6 +6,7 @@ import type { IssueChange } from "../core/issues.ts"; /** One write to an issue: a new comment, or its new state. */ export interface Notice { + pull?: boolean; repo: string; number: number; comment?: Comment; diff --git a/src/github/io/pulls.ts b/src/github/io/pulls.ts index dc8d386..b9ed2e9 100644 --- a/src/github/io/pulls.ts +++ b/src/github/io/pulls.ts @@ -1,4 +1,6 @@ // Pull requests from GitHub, through gh on the folder's or reader tab's machine (ADR 0003). + +import { type MergeInfo, type MergeMethod, mergeInfo } from "../core/merge.ts"; import { type PullDetail, parsePullDetail } from "../core/pull-detail.ts"; import { parseChecks, pullTimeline } from "../core/pull-timeline.ts"; import { @@ -35,6 +37,10 @@ export async function readPull(repo: string, number: number, on: string | null): api(`repos/${repo}/pulls/${number}/reviews?per_page=100`, { on, paginate: true }), ]); const detail = parsePullDetail(pull, issue, comments, reviews); + detail.merge = mergeInfo( + pull as Parameters[0], + (await api(`repos/${repo}`, { on })) as Record, + ); const sha = (pull as { head: { sha: string } }).head.sha; const [events, inline, checks, statuses] = await Promise.all([ api(`repos/${repo}/issues/${number}/timeline?per_page=100`, { on, paginate: true }), @@ -50,9 +56,39 @@ export async function readPull(repo: string, number: number, on: string | null): detail.url, ); detail.checks = parseChecks(Array.isArray(checks) ? checks : [checks], statuses as unknown[]); + if (detail.merge?.reason?.startsWith("Merging is blocked by")) { + const reasons: string[] = []; + if (detail.reviewers.some((r) => r.state === "changes_requested")) reasons.push("Changes requested"); + if (detail.reviewers.some((r) => r.state === "requested")) reasons.push("Review required"); + if (detail.checks.some((c) => /fail|pending|queued|progress|error/i.test(c.status))) + reasons.push("Checks have not passed"); + if (reasons.length) detail.merge.reason += ": " + reasons.join("; "); + } return detail; } +export async function mergePull( + repo: string, + number: number, + method: MergeMethod, + sha: string, + on: string | null, +): Promise { + const result = (await api(`repos/${repo}/pulls/${number}/merge`, { + on, + method: "PUT", + rawFields: { merge_method: method, sha }, + })) as { merged: boolean; message: string }; + if (!result.merged) throw new Error(result.message); +} +export async function deletePullBranch(info: MergeInfo, on: string | null): Promise { + if (!info.deletable || !info.headRepo) throw new Error("This branch cannot be deleted"); + await api(`repos/${info.headRepo}/git/refs/heads/${info.headRef.split("/").map(encodeURIComponent).join("/")}`, { + on, + method: "DELETE", + }); +} + /** The local branches' latest PRs, in one batch. */ export async function localPulls( remote: RemoteRepo, diff --git a/src/github/views/panel.ts b/src/github/views/panel.ts index 17d3735..22075c0 100644 --- a/src/github/views/panel.ts +++ b/src/github/views/panel.ts @@ -165,7 +165,9 @@ export class Panel implements Role { * then the shown expanded groups ask GitHub again (the change made them stale). */ private receive(cx: Context): void { - const changes = this.notices.take().flatMap((n) => (n.state ? [n.state] : [])); + const notices = this.notices.take(); + if (notices.some((n) => n.pull)) this.pulls.load(cx, true); + const changes = notices.flatMap((n) => (n.state ? [n.state] : [])); if (changes.length === 0) return; changes.forEach(known.issueChanged); this.issues.show(); diff --git a/src/github/views/pull.ts b/src/github/views/pull.ts index 64432b9..b9234c0 100644 --- a/src/github/views/pull.ts +++ b/src/github/views/pull.ts @@ -2,12 +2,14 @@ import { h_flex, v_flex } from "gpui-base"; import { type Context, div, type Element } from "gpui-kit"; import { type DetailRef, notVisible } from "../core/detail.ts"; +import type { MergeMethod } from "../core/merge.ts"; import type { Projects } from "../core/projects.ts"; import type { PullDetail, ReviewState } from "../core/pull-detail.ts"; +import { announce } from "../io/changes.ts"; import { detailLocation } from "../io/detail-tabs.ts"; import * as gh from "../io/gh.ts"; import { readProjects } from "../io/projects.ts"; -import { readPull } from "../io/pulls.ts"; +import { deletePullBranch, mergePull, readPull } from "../io/pulls.ts"; import { type DetailHost, detailBody, @@ -23,7 +25,7 @@ import { quiet, stateBadge, } from "./detail.ts"; -import { colors, link, PULL_STATES } from "./ui.ts"; +import { button, colors, link, PULL_STATES } from "./ui.ts"; interface Loaded { pull?: PullDetail; @@ -42,6 +44,10 @@ const REVIEWS: Record v_flex() .gap(8) @@ -153,6 +163,79 @@ export class Pull { ); } + private mergeArea(pull: PullDetail): Element { + const info = pull.merge; + const area = v_flex().gap(10).child(div().font_semibold().child("Merge")); + if (!info) return area; + area.child(quiet(info.reason ?? "This branch has no conflicts with the base branch")); + if (this.writeFailure) area.child(quiet(this.writeFailure)); + const act = (cx: Context, remove: boolean) => { + const ref = this.ref, + place = detailLocation(this.host.reader); + if (!ref || !place || this.writing) return; + this.writing = true; + cx.spawn(async (cx) => { + try { + if (remove) { + await deletePullBranch(info, place.on); + info.deletable = false; + } else await mergePull(ref.repo, ref.number, this.method ?? info.methods[0], info.sha, place.on); + announce({ repo: ref.repo, number: ref.number, pull: true }); + if (this.ref === ref) { + this.confirming = false; + this.writeFailure = ""; + if (!remove) this.load(cx); + } + } catch (e) { + if (this.ref === ref) this.writeFailure = gh.failureOf(e).message; + } finally { + this.writing = false; + cx.notify(); + } + }); + }; + if (this.writing) return area.child(quiet("Updating pull request…")); + if (info.deletable) + area.child(button("delete-branch", "Delete branch", "Delete remote branch", (_e, cx) => act(cx, true))); + if (!info.reason) { + for (const method of info.methods) + area.child( + button( + `method-${method}`, + `${(this.method ?? info.methods[0]) === method ? "●" : "○"} ${method === "merge" ? "Create a merge commit" : method === "squash" ? "Squash and merge" : "Rebase and merge"}`, + "Merge method", + (_e, cx) => { + this.method = method; + this.confirming = false; + cx.notify(); + }, + ), + ); + area.child( + button( + "merge-confirm", + this.confirming ? "Confirm Merge" : "Merge Pull Request", + "Merge pull request", + (_e, cx) => { + if (this.confirming) act(cx, false); + else { + this.confirming = true; + cx.notify(); + } + }, + ), + ); + if (this.confirming) + area.child( + button("merge-cancel", "Cancel", "Cancel merge", (_e, cx) => { + this.confirming = false; + cx.notify(); + }), + ); + } + return area; + } + private reviewers(pull: PullDetail): Element { const t = colors(); if (pull.reviewers.length === 0) return quiet("None yet"); diff --git a/test/core/merge.test.ts b/test/core/merge.test.ts new file mode 100644 index 0000000..66e69ae --- /dev/null +++ b/test/core/merge.test.ts @@ -0,0 +1,24 @@ +import { expect, test } from "bun:test"; +import { mergeInfo } from "../../src/github/core/merge.ts"; + +const p = { + state: "open", + mergeable: true, + mergeable_state: "clean", + head: { sha: "abc", ref: "feature", repo: { full_name: "fork/repo", default_branch: "main" } }, +}; +test("allowed methods keep merge/squash/rebase order and first default", () => { + expect(mergeInfo(p, { allow_squash_merge: true, allow_rebase_merge: true }).methods).toEqual(["squash", "rebase"]); + expect(mergeInfo(p, { allow_merge_merge: true }).reason).toBeNull(); +}); +test("conflicts, checks, protection, drafts and unknown states cannot merge", () => { + for (const state of ["dirty", "unstable", "blocked", "behind", "unknown"]) + expect(mergeInfo({ ...p, mergeable_state: state }, { allow_merge_merge: true }).reason).not.toBeNull(); + expect(mergeInfo({ ...p, draft: true }, {}).reason).toContain("draft"); + expect(mergeInfo({ ...p, mergeable: null }, {}).reason).not.toBeNull(); +}); +test("only merged non-default heads can be deleted, including forks", () => { + expect(mergeInfo({ ...p, merged: true }, {})).toMatchObject({ deletable: true, headRepo: "fork/repo" }); + expect(mergeInfo({ ...p, merged: true, head: { ...p.head, ref: "main" } }, {}).deletable).toBe(false); + expect(mergeInfo(p, {}).deletable).toBe(false); +}); diff --git a/test/io/merge.test.ts b/test/io/merge.test.ts new file mode 100644 index 0000000..ebcf68d --- /dev/null +++ b/test/io/merge.test.ts @@ -0,0 +1,30 @@ +import { afterEach, expect, test } from "bun:test"; +import { deletePullBranch, mergePull } from "../../src/github/io/pulls.ts"; +import { execCalls, machine, reset } from "../fake-herdr.ts"; + +afterEach(reset); +test("merge pins the reviewed SHA and method on the reader machine", async () => { + machine("remote", { + "~$ gh api repos/a/b/pulls/1/merge -X PUT -f merge_method=squash -f sha=abc": { + stdout: '{"merged":true,"message":"Pull Request successfully merged"}', + }, + }); + await mergePull("a/b", 1, "squash", "abc", "remote"); +}); +test("merge rejection preserves gh error and never retries writes", async () => { + machine("remote", { + "~$ gh api repos/a/b/pulls/1/merge -X PUT -f merge_method=merge -f sha=abc": { + code: 1, + stderr: "gh: Required status check is expected (HTTP 405)", + }, + }); + await expect(mergePull("a/b", 1, "merge", "abc", "remote")).rejects.toThrow("Required status check"); + expect(execCalls()).toHaveLength(1); +}); +test("delete targets the fork's remote ref, never a local branch", async () => { + machine("remote", { "~$ gh api repos/fork/b/git/refs/heads/feature/topic -X DELETE": { stdout: "" } }); + await deletePullBranch( + { methods: [], reason: null, sha: "abc", headRepo: "fork/b", headRef: "feature/topic", deletable: true }, + "remote", + ); +}); diff --git a/test/io/pull-detail.test.ts b/test/io/pull-detail.test.ts index b8e9a12..4a55710 100644 --- a/test/io/pull-detail.test.ts +++ b/test/io/pull-detail.test.ts @@ -24,6 +24,9 @@ function replies(number: number) { const prefix = `pull-cli-${number}`; const sha = JSON.parse(fixture(`${prefix}.json`)).head.sha; return { + "~$ gh api repos/cli/cli": { + stdout: '{"allow_merge_merge":true,"allow_squash_merge":true,"allow_rebase_merge":true}', + }, [`~$ gh api repos/cli/cli/issues/${number}/timeline?per_page=100 --paginate --slurp`]: { stdout: "[[]]" }, [`~$ gh api repos/cli/cli/pulls/${number}/comments?per_page=100 --paginate --slurp`]: { stdout: "[[]]" }, [`~$ gh api repos/cli/cli/commits/${sha}/check-runs?per_page=100 --paginate --slurp`]: {