diff --git a/mods/github/main.js b/mods/github/main.js index cb727bf..e0fbbab 100644 --- a/mods/github/main.js +++ b/mods/github/main.js @@ -10359,6 +10359,27 @@ function parseFiles(data) { })); } +// 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(); @@ -10557,6 +10578,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 }), @@ -10572,8 +10597,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 readPullFiles(repo, number, on) { const files = parseFiles(await api(`repos/${repo}/pulls/${number}/files?per_page=100`, { on, paginate: true })); const { viewed } = await readPullViewed(repo, number, on); @@ -11667,6 +11715,7 @@ var Panel = class { */ receive(cx) { const notices = this.notices.take(); + if (notices.some((n) => n.pull)) this.pulls.load(cx, true); const reviews = notices.filter((n) => n.review); for (const notice of reviews) pullReviewed(notice.repo, notice.review.on); const ready = this.ready(); @@ -13079,6 +13128,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; files = null; @@ -13097,6 +13150,9 @@ var Pull = class { this.host = host; } show(cx, ref) { + this.method = null; + this.confirming = false; + this.writeFailure = ""; this.metadata.expanded = false; this.ref = ref; this.entry = null; @@ -13238,6 +13294,7 @@ var Pull = class { ], [ postCard("pull-body", pull, "opened this pull request", onLink), + this.mergeArea(pull), // Discussion metadata is fetched once per PR; report its progress/failure once, not per thread. ...this.discussions?.loading || this.discussions?.failure ? [this.discussions.status()] : [], ...(this.discussions?.published.timeline(pull.timeline ?? []) ?? pull.timeline ?? []).map((item) => { @@ -13268,6 +13325,77 @@ var Pull = class { this.metadata ); } + mergeArea(pull) { + const info = pull.merge; + const area = v_flex11().gap(10).child(div15().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 0b1a386..df4bcb4 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 e13c0f4..d41d64e 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 bfe3b40..23aeb0a 100644 --- a/src/github/io/pulls.ts +++ b/src/github/io/pulls.ts @@ -1,6 +1,7 @@ // Pull requests from GitHub, through gh on the folder's or reader tab's machine (ADR 0003). import { type Comment, parseComment } from "../core/discussion.ts"; import { type ChangedFile, parseFiles } from "../core/files.ts"; +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 { @@ -39,6 +40,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 }), @@ -54,9 +59,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", + }); +} + /** All changed-file pages; GitHub may omit a patch (binary, too large, or a pure rename). */ export async function readPullFiles(repo: string, number: number, on: string | null): Promise { const files = parseFiles(await api(`repos/${repo}/pulls/${number}/files?per_page=100`, { on, paginate: true })); diff --git a/src/github/views/panel.ts b/src/github/views/panel.ts index 0e984c9..c8d2ce1 100644 --- a/src/github/views/panel.ts +++ b/src/github/views/panel.ts @@ -166,6 +166,7 @@ export class Panel implements Role { */ private receive(cx: Context): void { const notices = this.notices.take(); + if (notices.some((n) => n.pull)) this.pulls.load(cx, true); const reviews = notices.filter((n) => n.review); for (const notice of reviews) known.pullReviewed(notice.repo, notice.review!.on); const ready = this.ready(); diff --git a/src/github/views/pull.ts b/src/github/views/pull.ts index 8add2e0..7c2cfd3 100644 --- a/src/github/views/pull.ts +++ b/src/github/views/pull.ts @@ -3,13 +3,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 { ChangedFile } from "../core/files.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 { Notices } from "../io/changes.ts"; +import { announce, Notices } 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, type DetailLayout, @@ -50,6 +51,10 @@ const REVIEWS: Record { @@ -293,6 +302,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`]: {