feat(pr): delete branches after merge or close (#19257)

This commit is contained in:
Bilal Bakr authored and GitHub committed 2026-10-14 23:52:00 -05:00
1 parent e536bfd33b
commit 339179f50a
24 files changed
+963 -13

No files matched your search

@@ -72,6 +72,7 @@ export const definition = defineSourceControlClient({
"draft",
"close",
"reopen",
"delete-branch",
"update-branch",
"enable-auto-merge",
"disable-auto-merge",
@@ -18,6 +18,7 @@ import * as GitHubQuota from "./GitHubQuota.ts";
import * as SourceControlRateLimit from "@t3tools/source-control-core/server/SourceControlRateLimit";
import * as TestSourceControlHost from "@t3tools/source-control-testing/TestSourceControlHost";
import * as GitHubPullRequestApi from "./GitHubPullRequestApi.ts";
import * as GitHubPullRequestProvider from "./GitHubPullRequestProvider.ts";
import { KnownWorkflowRuns } from "./gitHubConditionalChecks.ts";
const encodeJson = Schema.encodeSync(Schema.fromJsonString(Schema.Unknown));
@@ -2226,6 +2227,249 @@ layer("GitHubPullRequestApi.layer", (it) => {
}),
);
it.effect.each([
{
description: "base-only write",
basePermission: "WRITE",
sourcePermission: "READ",
headRef: { id: "REF" },
expected: false,
actionAllowed: false,
},
{
description: "source-only write",
basePermission: "READ",
sourcePermission: "WRITE",
headRef: { id: "REF" },
expected: true,
actionAllowed: true,
},
{
description: "a deleted branch",
basePermission: "READ",
sourcePermission: "WRITE",
headRef: null,
expected: false,
actionAllowed: true,
},
{
description: "an unavailable source repository",
basePermission: "WRITE",
sourcePermission: null,
headRef: { id: "REF" },
expected: false,
actionAllowed: false,
},
])(
"uses source branch access in both permission reads for $description",
({ basePermission, sourcePermission, headRef, expected, actionAllowed }) =>
Effect.gen(function* () {
const answer = coreResponse({
headRepository: sourcePermission === null ? null : { viewerPermission: sourcePermission },
headRef,
});
answer.data.repository.viewerPermission = basePermission;
mockedExecute.mockReturnValue(Effect.succeed(output(encodeJson(answer))));
const cli = yield* GitHubPullRequestApi.GitHubPullRequestApi;
const input = { cwd: "/w", repository: "acme/web", host: "github.com", number: 7 };
expect((yield* cli.getViewerAccess(input)).canDeleteBranch).toBe(actionAllowed);
expect((yield* cli.getPullRequestDetail(input)).viewerAccess.canDeleteBranch).toBe(
expected,
);
for (const [call] of mockedExecute.mock.calls) {
if (
call.kind === "graphql" &&
!call.query.includes("query PullRequestStackMemberships")
) {
if (call.query.includes("$headRef: String!")) {
expect(call.query).toContain("headRepository { nameWithOwner viewerPermission }");
expect(call.query).toContain("headRef { id }");
} else {
expect(call.query).toContain("headRepository { viewerPermission }");
}
}
}
}),
);
it.effect("preserves the actual source fork name in provider detail", () =>
Effect.gen(function* () {
const answer = coreResponse({
state: "MERGED",
isCrossRepository: true,
headRepository: { nameWithOwner: "contributor/web-fork", viewerPermission: "WRITE" },
headRef: { id: "REF" },
});
mockedExecute.mockReturnValue(Effect.succeed(output(encodeJson(answer))));
const provider = yield* GitHubPullRequestProvider.make;
const detail = yield* provider.getChangeRequest({
cwd: "/w",
repository: "acme/web",
host: "github.com",
number: 7,
});
expect(detail.headRepositoryNameWithOwner).toBe("contributor/web-fork");
expect(detail.viewerPermissions.actions).toContain("delete-branch");
expect(queryAt(0)).toContain("headRepository { nameWithOwner viewerPermission }");
}),
);
const branchToDelete = (pullRequest: Readonly<Record<string, unknown>> = {}) => ({
data: {
repository: {
pullRequest: {
state: "MERGED",
headRefName: "feat/delete",
baseRefName: "main",
headRefOid: "abc123",
headRepository: { id: "FORK_REPO" },
...pullRequest,
},
},
},
});
const sourceBranch = (repository: Readonly<Record<string, unknown>> = {}) => ({
data: {
node: {
defaultBranchRef: { name: "main" },
ref: { target: { oid: "abc123" } },
...repository,
},
},
});
it.effect.each(["MERGED", "CLOSED"])("deletes the exact remote fork branch of a %s PR", (state) =>
Effect.gen(function* () {
route(
["query PullRequestBranchToDelete", branchToDelete({ state })],
["query PullRequestSourceBranch", sourceBranch()],
);
const cli = yield* GitHubPullRequestApi.GitHubPullRequestApi;
yield* cli.runPullRequestAction({
cwd: "/w",
repository: "acme/web",
host: "github.enterprise.test",
number: 7,
action: "delete-branch",
});
expect(variablesOf("query PullRequestBranchToDelete")).toEqual([
{ owner: "acme", name: "web", number: 7 },
]);
expect(variablesOf("query PullRequestSourceBranch")).toEqual([
{ repositoryId: "FORK_REPO", ref: "refs/heads/feat/delete" },
]);
expect(variablesOf("updateRefs(")).toEqual([
{
input: {
repositoryId: "FORK_REPO",
refUpdates: [
{
name: "refs/heads/feat/delete",
beforeOid: "abc123",
afterOid: "0000000000000000000000000000000000000000",
},
],
},
},
]);
expect(mockedExecute.mock.calls.at(-1)?.[0].host).toBe("github.enterprise.test");
expect(variablesOf("mergePullRequest(")).toEqual([]);
expect(variablesOf("closePullRequest(")).toEqual([]);
}),
);
it.effect.each([
{ description: "an open PR", head: { state: "OPEN" }, source: {} },
{ description: "a missing source repository", head: { headRepository: null }, source: {} },
{ description: "the base branch", head: { headRefName: "main" }, source: {} },
{
description: "the default branch",
head: {},
source: { defaultBranchRef: { name: "feat/delete" } },
},
{ description: "a missing default branch", head: {}, source: { defaultBranchRef: null } },
{
description: "a changed branch",
head: {},
source: { ref: { target: { oid: "new-commit" } } },
},
{ description: "an unavailable source repository", head: {}, source: null },
])("refuses to delete $description", ({ head, source }) =>
Effect.gen(function* () {
route(
["query PullRequestBranchToDelete", branchToDelete(head)],
[
"query PullRequestSourceBranch",
source === null ? { data: { node: null } } : sourceBranch(source),
],
);
const cli = yield* GitHubPullRequestApi.GitHubPullRequestApi;
const error = yield* Effect.flip(
cli.runPullRequestAction({
cwd: "/w",
repository: "acme/web",
host: "github.com",
number: 7,
action: "delete-branch",
}),
);
expect(error._tag).toBe("GitHubBranchDeletionRefusedError");
expect(variablesOf("updateRefs(")).toEqual([]);
}),
);
it.effect("accepts an already deleted source branch", () =>
Effect.gen(function* () {
route(
["query PullRequestBranchToDelete", branchToDelete()],
["query PullRequestSourceBranch", sourceBranch({ ref: null })],
);
const cli = yield* GitHubPullRequestApi.GitHubPullRequestApi;
yield* cli.runPullRequestAction({
cwd: "/w",
repository: "acme/web",
host: "github.com",
number: 7,
action: "delete-branch",
});
expect(variablesOf("updateRefs(")).toEqual([]);
}),
);
it.effect("keeps the source branch when GitHub refuses deletion", () =>
Effect.gen(function* () {
route(
["query PullRequestBranchToDelete", branchToDelete()],
["query PullRequestSourceBranch", sourceBranch()],
);
const answer = mockedExecute.getMockImplementation()!;
mockedExecute.mockImplementation((call) =>
call.kind === "graphql" && call.query.includes("updateRefs(")
? Effect.fail(
new GitHubApi.GitHubApiResponseError({
host: call.host,
operation: call.operation,
status: 422,
}),
)
: answer(call),
);
const cli = yield* GitHubPullRequestApi.GitHubPullRequestApi;
const error = yield* Effect.flip(
cli.runPullRequestAction({
cwd: "/w",
repository: "acme/web",
host: "github.com",
number: 7,
action: "delete-branch",
}),
);
expect(error._tag).toBe("GitHubApiResponseError");
expect(variablesOf("mergePullRequest(")).toEqual([]);
expect(variablesOf("closePullRequest(")).toEqual([]);
}),
);
it.effect.each(["merge", "enable-auto-merge"] as const)(
"removes agent credits from the proposed message for %s",
(action) =>
@@ -4103,6 +4347,7 @@ layer("GitHubPullRequestApi.layer", (it) => {
expect(access).toEqual({
mergeCapabilities: { merge: true, squash: false, rebase: true },
canWrite: false,
canDeleteBranch: false,
canTriage: false,
canUpdate: true,
didAuthor: true,
@@ -4213,6 +4458,7 @@ layer("GitHubPullRequestApi.layer", (it) => {
expect(access).toEqual({
mergeCapabilities: { merge: true, squash: false, rebase: true },
canWrite: false,
canDeleteBranch: false,
canTriage: false,
canUpdate: true,
didAuthor: true,
@@ -311,7 +311,37 @@ export class GitHubWorkflowApprovalHeadChangedError extends Schema.TaggedError<G
}
}
export class GitHubBranchDeletionRefusedError extends Schema.TaggedError<GitHubBranchDeletionRefusedError>()(
"GitHubBranchDeletionRefusedError",
{
number: Schema.Int,
reason: Schema.Literals([
"open-pr",
"stack",
"source-unavailable",
"unsafe-branch",
"head-changed",
]),
},
) {
override get message(): string {
switch (this.reason) {
case "open-pr":
return `Close or merge pull request #${this.number} before deleting its source branch.`;
case "stack":
return "Branch deletion is not supported for a stack.";
case "source-unavailable":
return `GitHub did not report a complete source branch for pull request #${this.number}.`;
case "unsafe-branch":
return "The source branch is a default or base branch and cannot be deleted here.";
case "head-changed":
return "The source branch has new commits and was not deleted.";
}
}
}
export type GitHubPullRequestApiError =
| GitHubBranchDeletionRefusedError
| GitHubStackActionError
| GitHubApi.GitHubApiError
| GitHubPullRequestReadError
@@ -1062,6 +1092,60 @@ const MERGE_PULL_REQUEST_GRAPHQL_MUTATION = `mutation($input: MergePullRequestIn
const ENABLE_AUTO_MERGE_GRAPHQL_MUTATION = `mutation($input: EnablePullRequestAutoMergeInput!) {
enablePullRequestAutoMerge(input: $input) { clientMutationId }
}`;
const BRANCH_TO_DELETE_GRAPHQL_QUERY = `query PullRequestBranchToDelete($owner: String!, $name: String!, $number: Int!) {
repository(owner: $owner, name: $name) {
pullRequest(number: $number) {
state
headRefName
baseRefName
headRefOid
headRepository { id }
}
}
}`;
const decodeBranchToDelete = Schema.decodeUnknownResult(
Schema.fromJsonString(
Schema.Struct({
data: Schema.Struct({
repository: Schema.Struct({
pullRequest: Schema.Struct({
state: Schema.Literals(["OPEN", "CLOSED", "MERGED"]),
headRefName: Schema.String,
baseRefName: Schema.String,
headRefOid: Schema.String,
headRepository: Schema.NullOr(Schema.Struct({ id: Schema.String })),
}),
}),
}),
}),
),
);
const SOURCE_BRANCH_GRAPHQL_QUERY = `query PullRequestSourceBranch($repositoryId: ID!, $ref: String!) {
node(id: $repositoryId) {
... on Repository {
defaultBranchRef { name }
ref(qualifiedName: $ref) { target { oid } }
}
}
}`;
const decodeSourceBranch = Schema.decodeUnknownResult(
Schema.fromJsonString(
Schema.Struct({
data: Schema.Struct({
node: Schema.NullOr(
Schema.Struct({
defaultBranchRef: Schema.NullOr(Schema.Struct({ name: Schema.String })),
ref: Schema.NullOr(Schema.Struct({ target: Schema.Struct({ oid: Schema.String }) })),
}),
),
}),
}),
),
);
const DELETE_BRANCH_GRAPHQL_MUTATION = `mutation($input: UpdateRefsInput!) {
updateRefs(input: $input) { clientMutationId }
}`;
const DISABLE_AUTO_MERGE_GRAPHQL_MUTATION = `mutation($pullRequestId: ID!) {
disablePullRequestAutoMerge(input: { pullRequestId: $pullRequestId }) { clientMutationId }
}`;
@@ -2494,6 +2578,100 @@ export const make = Effect.gen(function* () {
},
runPullRequestAction: (input) => {
if (input.action === "delete-branch") {
return Effect.gen(function* () {
if (input.stackNumber !== undefined) {
return yield* new GitHubBranchDeletionRefusedError({
number: input.number,
reason: "stack",
});
}
const { owner, name } = parseRepositorySelector(input.repository);
const response = yield* graphqlRead({
cwd: input.cwd,
host: input.host,
operation: "deletePullRequestBranch",
allowReserve: true,
query: BRANCH_TO_DELETE_GRAPHQL_QUERY,
variables: { owner, name, number: input.number },
decode: decodeBranchToDelete,
});
const branch = response.data.repository.pullRequest;
if (branch.state === "OPEN") {
return yield* new GitHubBranchDeletionRefusedError({
number: input.number,
reason: "open-pr",
});
}
if (
branch.headRepository === null ||
!branch.headRepository.id ||
!branch.headRefName ||
!branch.headRefOid
) {
return yield* new GitHubBranchDeletionRefusedError({
number: input.number,
reason: "source-unavailable",
});
}
if (branch.headRefName === branch.baseRefName) {
return yield* new GitHubBranchDeletionRefusedError({
number: input.number,
reason: "unsafe-branch",
});
}
const ref = `refs/heads/${branch.headRefName}`;
const source = yield* graphqlRead({
cwd: input.cwd,
host: input.host,
operation: "deletePullRequestBranch",
allowReserve: true,
query: SOURCE_BRANCH_GRAPHQL_QUERY,
variables: { repositoryId: branch.headRepository.id, ref },
decode: decodeSourceBranch,
});
const repository = source.data.node;
if (repository === null) {
return yield* new GitHubBranchDeletionRefusedError({
number: input.number,
reason: "source-unavailable",
});
}
if (repository.ref === null) return;
if (
repository.defaultBranchRef === null ||
branch.headRefName === repository.defaultBranchRef.name
) {
return yield* new GitHubBranchDeletionRefusedError({
number: input.number,
reason: "unsafe-branch",
});
}
if (repository.ref.target.oid !== branch.headRefOid) {
return yield* new GitHubBranchDeletionRefusedError({
number: input.number,
reason: "head-changed",
});
}
yield* graphql({
host: input.host,
operation: "deletePullRequestBranch",
query: DELETE_BRANCH_GRAPHQL_MUTATION,
variables: {
input: {
repositoryId: branch.headRepository.id,
refUpdates: [
{
name: ref,
beforeOid: branch.headRefOid,
afterOid: "0000000000000000000000000000000000000000",
},
],
},
},
});
});
}
if (input.stackNumber !== undefined)
return runGitHubStackAction({ ...input, stackNumber: input.stackNumber }).pipe(
Effect.provideService(GitHubApi.GitHubApi, api),
@@ -64,6 +64,48 @@ it.effect("maps credential verification failures without relabeling operation fa
}),
);
it.effect("advertises standalone branch deletion for source repository writers", () =>
Effect.gen(function* () {
let action: string | undefined;
const provider = yield* make.pipe(
Effect.provide(
Layer.mock(GitHubPullRequestApi.GitHubPullRequestApi)({
runPullRequestAction: (input) =>
Effect.sync(() => {
action = input.action;
}),
}),
),
);
expect(provider.capabilities.deleteBranch).toBe(true);
expect(provider.capabilities.actions).toContain("delete-branch");
yield* provider.runAction({
cwd: "/w",
repository: "acme/web",
host: "github.com",
number: 7,
action: "delete-branch",
});
expect(action).toBe("delete-branch");
const access = {
canWrite: false,
canTriage: false,
canUpdate: false,
didAuthor: false,
canDeleteBranch: true,
};
expect(gitHubViewerPermissions(access).actions).toContain("delete-branch");
expect(
gitHubViewerPermissions({
...access,
canWrite: true,
didAuthor: true,
canDeleteBranch: false,
}).actions,
).not.toContain("delete-branch");
}),
);
it.effect("refreshes checks without permissions or comparison reads", () =>
Effect.gen(function* () {
let reads = 0;
@@ -219,6 +261,7 @@ describe("gitHubViewerPermissions", () => {
expect(
gitHubViewerPermissions({
canWrite: true,
canDeleteBranch: true,
canTriage: true,
canUpdate: true,
didAuthor: false,
@@ -226,6 +269,7 @@ describe("gitHubViewerPermissions", () => {
).toEqual({
// Arming a merge for later is the merge, so it travels with it.
actions: [
"delete-branch",
"merge",
"enable-auto-merge",
"disable-auto-merge",
@@ -27,6 +27,7 @@ const CAPABILITIES: PullRequestCapabilities = {
comment: true,
actions: [...definition.changeRequestActions],
mergeMethods: ["merge", "squash", "rebase"],
deleteBranch: true,
updateMethods: ["merge", "rebase"],
search: true,
reactions: true,
@@ -65,6 +66,7 @@ export function gitHubViewerPermissions(access: GitHubViewerAccess): PullRequest
return {
...(access.canWrite ? { stackRebase: true } : {}),
actions: [
...(access.canDeleteBranch === true ? (["delete-branch"] as const) : []),
// Arming a merge and taking the arming back are the merge, deferred: whoever may not
// merge here may not leave an instruction to merge later either.
...(access.canWrite
@@ -1055,6 +1055,7 @@ describe("viewer permission decoding", () => {
canTriage: false,
canUpdate: true,
didAuthor: true,
canDeleteBranch: false,
});
});
@@ -1074,6 +1075,7 @@ describe("viewer permission decoding", () => {
canTriage: false,
canUpdate: false,
didAuthor: false,
canDeleteBranch: false,
});
});
@@ -1087,6 +1089,7 @@ describe("viewer permission decoding", () => {
canTriage: false,
canUpdate: true,
didAuthor: false,
canDeleteBranch: false,
});
});
@@ -558,6 +558,18 @@ const RawViewerFieldsSchema = Schema.Struct({
viewerDidAuthor: Schema.optional(Schema.Boolean),
});
const RawHeadBranchAccessSchema = Schema.Struct({
headRepository: Schema.optional(
Schema.NullOr(
Schema.Struct({
nameWithOwner: Schema.optional(Schema.NullOr(Schema.String)),
viewerPermission: Schema.optional(Schema.NullOr(Schema.String)),
}),
),
),
headRef: Schema.optional(Schema.NullOr(Schema.Struct({ id: Schema.String }))),
});
const RawThreadCommentsSchema = Schema.Struct({
totalCount: Schema.optional(Schema.Int),
pageInfo: Schema.optional(RawPageInfoSchema),
@@ -722,6 +734,7 @@ const RawCoreSchema = Schema.Struct({
pullRequest: Schema.Struct({
...RawDetailSchema.fields,
...RawViewerFieldsSchema.fields,
...RawHeadBranchAccessSchema.fields,
viewerCanUpdateBranch: Schema.Boolean,
baseRef: Schema.NullOr(
Schema.Struct({
@@ -842,6 +855,8 @@ export const pullRequestCoreGraphQlQuery = (host: string) => {
additions deletions changedFiles createdAt updatedAt mergedAt closedAt
headRefName baseRefName headRefOid isCrossRepository
headRepositoryOwner { login }
headRepository { nameWithOwner viewerPermission }
headRef { id }
author { login avatarUrl ... on User { id name } }
autoMergeRequest { mergeMethod }
viewerCanUpdate viewerDidAuthor viewerCanUpdateBranch
@@ -1353,6 +1368,7 @@ export interface GitHubPullRequestDetail extends GitHubPullRequestListItem {
readonly isCrossRepository?: boolean;
/** The owner of the head branch's repository; null where `gh` did not say. */
readonly headRepositoryOwner: string | null;
readonly headRepositoryNameWithOwner?: string | null;
readonly headSha?: string | null;
readonly body: string;
readonly changedFiles: number;
@@ -2358,8 +2374,10 @@ export function decodePullRequestCoreJson(
labels: pr.labels.nodes,
statusCheckRollup: toCheckContexts(contexts?.nodes ?? []),
}),
headRepositoryNameWithOwner: trimmed(pr.headRepository?.nameWithOwner),
viewerAccess: {
canWrite: toCanWrite(repository.viewerPermission),
canDeleteBranch: toCanWrite(pr.headRepository?.viewerPermission) && pr.headRef !== null,
canTriage: toCanTriage(repository.viewerPermission),
...toPullRequestViewerFields(pr),
mergeCapabilities: {
@@ -3181,6 +3199,7 @@ export function buildLabelRequest(labels: ReadonlyArray<string>): {
*/
export interface GitHubViewerAccess {
readonly canWrite: boolean;
readonly canDeleteBranch?: boolean;
/**
* The viewer's role reaches triage, which is the least that may label. Everyone who can write
* can triage; a triager is the one role that can label without being able to merge.
@@ -3201,7 +3220,10 @@ export interface GitHubViewerAccess {
export const VIEWER_PERMISSIONS_GRAPHQL_QUERY = `query($owner: String!, $name: String!, $number: Int!) {
repository(owner: $owner, name: $name) {
mergeCommitAllowed squashMergeAllowed rebaseMergeAllowed viewerPermission
pullRequest(number: $number) { viewerCanUpdate viewerDidAuthor }
pullRequest(number: $number) {
viewerCanUpdate viewerDidAuthor
headRepository { viewerPermission }
}
}
}`;
@@ -3210,7 +3232,9 @@ const RawViewerPermissionsSchema = Schema.Struct({
repository: Schema.Struct({
...RawRepositoryAccessSchema.fields,
/** Null for a number that names no pull request the viewer can see. */
pullRequest: Schema.NullOr(RawViewerFieldsSchema),
pullRequest: Schema.NullOr(
Schema.Struct({ ...RawViewerFieldsSchema.fields, ...RawHeadBranchAccessSchema.fields }),
),
}),
}),
});
@@ -3232,6 +3256,7 @@ export function decodeViewerPermissionsJson(
rebase: repository.rebaseMergeAllowed,
},
canWrite: toCanWrite(repository.viewerPermission),
canDeleteBranch: toCanWrite(repository.pullRequest?.headRepository?.viewerPermission),
canTriage: toCanTriage(repository.viewerPermission),
...toPullRequestViewerFields(repository.pullRequest),
});