TypeScript
fix(gitlab): merge requests can delete their source branch (#30453)
Antonyb871551ee25a
diff --git a/packages/source-control-gitlab/src/server/GitLabPullRequestCli.test.ts b/packages/source-control-gitlab/src/server/GitLabPullRequestCli.test.tsindex cefa878781a..0e62a3a615a 100644--- a/packages/source-control-gitlab/src/server/GitLabPullRequestCli.test.ts+++ b/packages/source-control-gitlab/src/server/GitLabPullRequestCli.test.ts@@ -87,6 +87,23 @@ function mergeRequestJson(overrides: Record<string, unknown>): string {});}+function sourceBranchJson(overrides: Record<string, unknown>): string {+ return JSON.stringify({+ data: {+ project: {+ mergeRequest: {+ state: "merged",+ sourceBranch: "feat/page",+ diffHeadSha: "head",+ sourceProject: { fullPath: "acme/web" },+ userPermissions: { removeSourceBranch: true },+ ...overrides,+ },+ },+ },+ });+}+function argsOfCall(index: number): ReadonlyArray<string> {return callAt(index).args;}@@ -1465,6 +1482,98 @@ layer("GitLabPullRequestCli.layer", (it) => {}),);+ it.effect.each([+ { answer: sourceBranchJson({}), expected: true },+ { answer: "not json", expected: false },+ ])("asks GitLab whether a merged merge request's branch can be deleted", ({ answer, expected }) =>+ Effect.gen(function* () {+ mockedExecute+ .mockReturnValueOnce(Effect.succeed(output(mergeRequestJson({ state: "merged" }))))+ .mockReturnValueOnce(Effect.succeed(labelPermission))+ .mockReturnValueOnce(Effect.succeed(output(answer)));+ const cli = yield* GitLabPullRequestCli.GitLabPullRequestCli;++ const detail = yield* cli.getMergeRequestDetail({+ cwd: "/w",+ repository: "acme/web",+ number: 7,+ });++ expect(detail.viewerCanDeleteBranch).toBe(expected);+ expect(argsOfCall(2)).toContain("graphql");+ }),+ );++ it.effect("deletes the source branch in the source project once its head is the merged one", () =>+ Effect.gen(function* () {+ mockedExecute+ .mockReturnValueOnce(+ Effect.succeed(output(sourceBranchJson({ sourceProject: { fullPath: "fork/web" } }))),+ )+ .mockReturnValueOnce(+ Effect.succeed(+ output(+ JSON.stringify({+ default: false,+ commit: { id: "head", authored_date: "2026-11-03T20:29:40.000-07:00" },+ }),+ ),+ ),+ )+ .mockReturnValueOnce(Effect.succeed(output("")));+ const cli = yield* GitLabPullRequestCli.GitLabPullRequestCli;++ yield* cli.runMergeRequestAction({+ cwd: "/w",+ repository: "acme/web",+ number: 7,+ action: "delete-branch",+ });++ expect(argsOfCall(1)).toEqual(["api", "projects/fork%2Fweb/repository/branches/feat%2Fpage"]);+ expect(argsOfCall(2)).toEqual([+ "api",+ "projects/fork%2Fweb/repository/branches/feat%2Fpage",+ "--method",+ "DELETE",+ "--header",+ "If-Unmodified-Since: Wed, 04 Nov 2026 03:29:40 GMT",+ ]);+ }),+ );++ it.effect.each([+ { reason: "open", source: { state: "opened" }, branch: undefined },+ { reason: "open", source: { state: "locked" }, branch: undefined },+ {+ reason: "not-allowed",+ source: { userPermissions: { removeSourceBranch: false } },+ branch: undefined,+ },+ { reason: "default-branch", source: {}, branch: { default: true, commit: { id: "head" } } },+ { reason: "head-changed", source: {}, branch: { default: false, commit: { id: "newer" } } },+ ])("refuses to delete the source branch when it is $reason", ({ reason, source, branch }) =>+ Effect.gen(function* () {+ mockedExecute.mockReturnValueOnce(Effect.succeed(output(sourceBranchJson(source))));+ if (branch !== undefined) {+ mockedExecute.mockReturnValueOnce(Effect.succeed(output(JSON.stringify(branch))));+ }+ const cli = yield* GitLabPullRequestCli.GitLabPullRequestCli;++ const error = yield* cli+ .runMergeRequestAction({+ cwd: "/w",+ repository: "acme/web",+ number: 7,+ action: "delete-branch",+ })+ .pipe(Effect.flip);++ expect(error).toMatchObject({ _tag: "GitLabBranchDeletionRefusedError", reason });+ expect(mockedExecute).toHaveBeenCalledTimes(branch === undefined ? 1 : 2);+ }),+ );+it.effect("reads who has access to the project and who is already on the merge request", () =>Effect.gen(function* () {mockedExecutediff --git a/packages/source-control-gitlab/src/server/GitLabPullRequestCli.ts b/packages/source-control-gitlab/src/server/GitLabPullRequestCli.tsindex fc0a8577851..ece38c97dbc 100644--- a/packages/source-control-gitlab/src/server/GitLabPullRequestCli.ts+++ b/packages/source-control-gitlab/src/server/GitLabPullRequestCli.ts@@ -1,8 +1,10 @@import { removeAgentCredits } from "@t3tools/source-control-core/server/mergeMessage";import { isCommitSha } from "@t3tools/source-control-core/server/pullRequestUtils";import * as Context from "effect/Context";+import * as DateTime from "effect/DateTime";import * as Effect from "effect/Effect";import * as Layer from "effect/Layer";+import * as Option from "effect/Option";import * as Result from "effect/Result";import * as Schema from "effect/Schema";import { resolvePullRequestAuthorFilter, VcsProcessExitError } from "@t3tools/contracts";@@ -33,6 +35,7 @@ import * as GitLabCli from "./GitLabCli.ts";import {AWARD_EMOJI_GRAPHQL_QUERY,decodeAwardEmojiJson,+ decodeBranchJson,decodeCommitDiffRefsJson,decodeCommitsJson,decodeDiffRefsJson,@@ -53,6 +56,7 @@ import {decodeProjectUsersJson,decodeRepositoryBlobsJson,decodeReviewDecisionsJson,+ decodeSourceBranchJson,decodeTriggerJobChecksJson,decodeViewerJson,gitLabAwardName,@@ -62,6 +66,7 @@ import {MERGE_REQUEST_STATS_GRAPHQL_QUERY,REPOSITORY_BLOBS_GRAPHQL_QUERY,REVIEW_DECISIONS_GRAPHQL_QUERY,+ SOURCE_BRANCH_GRAPHQL_QUERY,type GitLabDiffRefs,type GitLabMergeRequestDetail,type GitLabMergeRequestListItem,@@ -193,6 +198,41 @@ export class GitLabDiffFileContentsUnavailableError extends Schema.TaggedError<G}}+export class GitLabBranchDeletionRefusedError extends Schema.TaggedError<GitLabBranchDeletionRefusedError>()(+ "GitLabBranchDeletionRefusedError",+ {+ command: Schema.Literal("glab"),+ cwd: Schema.String,+ number: Schema.Int,+ reason: Schema.Literals([+ "open",+ "not-allowed",+ "source-unavailable",+ "default-branch",+ "head-changed",+ ]),+ },+) {+ get detail(): string {+ switch (this.reason) {+ case "open":+ return `Close or merge merge request !${this.number} before deleting its source branch.`;+ case "not-allowed":+ return "GitLab does not let you delete this source branch. It may be protected, or you may not be able to push to it.";+ case "source-unavailable":+ return `GitLab did not report a source project for merge request !${this.number}.`;+ case "default-branch":+ return "The source branch is its project's default branch and cannot be deleted here.";+ case "head-changed":+ return "The source branch has new commits and was not deleted.";+ }+ }++ override get message(): string {+ return `GitLab CLI failed in deleteSourceBranch: ${this.detail}`;+ }+}+export class GitLabUnknownLabelError extends Schema.TaggedError<GitLabUnknownLabelError>()("GitLabUnknownLabelError",{@@ -212,6 +252,7 @@ export class GitLabUnknownLabelError extends Schema.TaggedError<GitLabUnknownLabexport type GitLabPullRequestCliError =| GitLabCli.GitLabCliError+ | GitLabBranchDeletionRefusedError| GitLabMergeRequestReadError| GitLabUnknownLabelError| GitLabDiffCursorError@@ -657,6 +698,7 @@ export const make = Effect.gen(function* () {readonly path: string;readonly method?: string;readonly stdin?: string;+ readonly headers?: ReadonlyArray<string>;readonly maxOutputBytes?: number;readonly timeoutMs?: number;}) =>@@ -671,6 +713,7 @@ export const make = Effect.gen(function* () {...(input.stdin === undefined? []: ["--input", "-", "--header", "Content-Type: application/json"]),+ ...(input.headers ?? []).flatMap((header) => ["--header", header]),],...(input.stdin === undefined ? {} : { stdin: input.stdin }),...(input.maxOutputBytes === undefined ? {} : { maxOutputBytes: input.maxOutputBytes }),@@ -1281,6 +1324,88 @@ export const make = Effect.gen(function* () {),);+ const sourceBranch = (input: {+ readonly cwd: string;+ readonly host?: string | undefined;+ readonly repository: string;+ readonly number: number;+ }) =>+ graphqlRead({+ cwd: input.cwd,+ host: input.host,+ operation: "getSourceBranch",+ query: SOURCE_BRANCH_GRAPHQL_QUERY,+ variables: { fullPath: input.repository, iid: String(input.number) },+ decode: decodeSourceBranchJson,+ });++ const deleteSourceBranch = Effect.fn("GitLabPullRequestCli.deleteSourceBranch")(+ function* (input: {+ readonly cwd: string;+ readonly host?: string | undefined;+ readonly repository: string;+ readonly number: number;+ }) {+ const refuse = (reason: GitLabBranchDeletionRefusedError["reason"]) =>+ new GitLabBranchDeletionRefusedError({+ command: "glab",+ cwd: input.cwd,+ number: input.number,+ reason,+ });+ const source = yield* sourceBranch(input);+ if (source === null) {+ return yield* new GitLabMergeRequestReadError({+ command: "glab",+ cwd: input.cwd,+ operation: "getSourceBranch",+ cause: new Error("GitLab reported no merge request."),+ });+ }+ if (source.open) return yield* refuse("open");+ if (!source.canDelete) return yield* refuse("not-allowed");+ if (source.sourceProject === null || source.headSha === null) {+ return yield* refuse("source-unavailable");+ }+ const path = `projects/${projectPath(source.sourceProject)}/repository/branches/${encodeURIComponent(source.branch)}`;+ const branch = yield* api({ cwd: input.cwd, host: input.host, path }).pipe(+ Effect.flatMap((result) => {+ const decoded = decodeBranchJson(result.stdout.trim());+ return Result.isSuccess(decoded)+ ? Effect.succeed(decoded.success)+ : Effect.fail(+ new GitLabMergeRequestReadError({+ command: "glab",+ cwd: input.cwd,+ operation: "getSourceBranch",+ cause: decoded.failure,+ }),+ );+ }),+ );+ if (branch.isDefault) return yield* refuse("default-branch");+ if (branch.headSha !== source.headSha) return yield* refuse("head-changed");+ // GitLab's branch delete takes no expected SHA. It answers 412 when the head's authored+ // date is newer than If-Unmodified-Since, which catches a commit pushed after this read but+ // not a force-push of an older-dated commit (a rebase keeps author dates).+ const authoredAt =+ branch.headAuthoredDate === null ? Option.none() : DateTime.make(branch.headAuthoredDate);+ yield* api({+ cwd: input.cwd,+ host: input.host,+ path,+ method: "DELETE",+ ...(Option.isNone(authoredAt)+ ? {}+ : {+ headers: [+ `If-Unmodified-Since: ${DateTime.toDateUtc(authoredAt.value).toUTCString()}`,+ ],+ }),+ });+ },+ );+const mergeRequestStats = (input: {readonly cwd: string;readonly host?: string | undefined;@@ -1472,7 +1597,26 @@ export const make = Effect.gen(function* () {[mergeRequestDetail(input), labelPermission(input)],{ concurrency: 2 },);- const detail = { ...read, viewerCanEditLabels };+ // Only a closed or merged merge request offers its branch for deletion, so an open one,+ // the page most often read, skips the extra query.+ const detail =+ read.state === "open"+ ? { ...read, viewerCanEditLabels }+ : {+ ...read,+ viewerCanEditLabels,+ viewerCanDeleteBranch: yield* sourceBranch(input).pipe(+ Effect.map((source) => source?.canDelete === true),+ // The answer gates one optional action; an unusable CLI or account still surfaces.+ Effect.catchIf(+ (cause) =>+ cause._tag !== "GitLabCliUnavailableError" &&+ cause._tag !== "GitLabCliAuthenticationError" &&+ cause._tag !== "GitLabCliRateLimitError",+ () => Effect.succeed(false),+ ),+ ),+ };if (input.downstreamChecks === false || detail.headPipeline === undefined) return detail;const downstream = yield* triggerJobChecks({cwd: input.cwd,@@ -1820,6 +1964,7 @@ export const make = Effect.gen(function* () {// `glab mr merge` arms auto-merge and never disarms it, so the one direction the CLI has// no flag for is asked of GitLab directly through the same `api` passthrough the rest of// this module writes with.+ if (input.action === "delete-branch") return yield* deleteSourceBranch(input);if (input.action === "disable-auto-merge") {const result = yield* api({cwd: input.cwd,diff --git a/packages/source-control-gitlab/src/server/GitLabPullRequestProvider.test.ts b/packages/source-control-gitlab/src/server/GitLabPullRequestProvider.test.tsindex 26dde73a9fe..e3b80e7c3b6 100644--- a/packages/source-control-gitlab/src/server/GitLabPullRequestProvider.test.ts+++ b/packages/source-control-gitlab/src/server/GitLabPullRequestProvider.test.ts@@ -123,7 +123,13 @@ it.effect.each(["merge", "disable-auto-merge"] as const)(describe("gitLabViewerPermissions", () => {it("offers everything to a viewer GitLab says can merge", () => {- expect(gitLabViewerPermissions({ viewerCanMerge: true, viewerCanEditLabels: true })).toEqual({+ expect(+ gitLabViewerPermissions({+ viewerCanMerge: true,+ viewerCanDeleteBranch: true,+ viewerCanEditLabels: true,+ }),+ ).toEqual({actions: ["merge","ready",@@ -133,6 +139,7 @@ describe("gitLabViewerPermissions", () => {"update-branch","enable-auto-merge","disable-auto-merge",+ "delete-branch",],comment: true,resolve: true,diff --git a/packages/source-control-gitlab/src/server/GitLabPullRequestProvider.ts b/packages/source-control-gitlab/src/server/GitLabPullRequestProvider.tsindex f852b96f351..8368747a261 100644--- a/packages/source-control-gitlab/src/server/GitLabPullRequestProvider.ts+++ b/packages/source-control-gitlab/src/server/GitLabPullRequestProvider.ts@@ -27,6 +27,7 @@ const CAPABILITIES: PullRequestCapabilities = {comment: true,actions: [...definition.changeRequestActions],mergeMethods: ["merge", "squash", "rebase"],+ deleteBranch: true,// GitLab has no merge-target-into-source operation.updateMethods: ["rebase"],search: true,@@ -66,11 +67,14 @@ const MERGE_ACTIONS: ReadonlySet<string> = new Set([/** Authors may close/reopen/change draft state regardless of role; REST omits authorship. */export function gitLabViewerPermissions(input: {readonly viewerCanMerge: boolean;+ readonly viewerCanDeleteBranch?: boolean;readonly viewerCanEditLabels?: boolean | undefined;}): PullRequestViewerPermissions {return {- actions: CAPABILITIES.actions.filter(- (action) => !MERGE_ACTIONS.has(action) || input.viewerCanMerge,+ actions: CAPABILITIES.actions.filter((action) =>+ action === "delete-branch"+ ? input.viewerCanDeleteBranch === true+ : !MERGE_ACTIONS.has(action) || input.viewerCanMerge,),comment: true,resolve: true,diff --git a/packages/source-control-gitlab/src/server/gitLabMergeRequestJson.ts b/packages/source-control-gitlab/src/server/gitLabMergeRequestJson.tsindex 1b6c1239449..1796778aa49 100644--- a/packages/source-control-gitlab/src/server/gitLabMergeRequestJson.ts+++ b/packages/source-control-gitlab/src/server/gitLabMergeRequestJson.ts@@ -201,6 +201,8 @@ export interface GitLabMergeRequestDetail extends GitLabMergeRequestListItem {readonly reviewers: ReadonlyArray<PullRequestActor>;readonly checks: ReadonlyArray<PullRequestCheck>;readonly viewerCanMerge: boolean;+ /** Read only for a closed or merged merge request; absent on an open one. */+ readonly viewerCanDeleteBranch?: boolean;/** Set by the detail read, which asks GraphQL; REST carries no label permission. */readonly viewerCanEditLabels?: boolean;readonly reviewerIds: ReadonlyArray<number>;@@ -1067,6 +1069,100 @@ export function decodeRepositoryBlobsJson(return Result.succeed(blobs);}+export const SOURCE_BRANCH_GRAPHQL_QUERY = `query($fullPath: ID!, $iid: String!) {+ project(fullPath: $fullPath) {+ mergeRequest(iid: $iid) {+ state sourceBranch diffHeadSha+ sourceProject { fullPath }+ userPermissions { removeSourceBranch }+ }+ }+}`;++const RawSourceBranchSchema = Schema.Struct({+ data: Schema.Struct({+ project: Schema.NullOr(+ Schema.Struct({+ mergeRequest: Schema.NullOr(+ Schema.Struct({+ state: Schema.String,+ sourceBranch: Schema.String,+ diffHeadSha: Schema.optional(Schema.NullOr(Schema.String)),+ sourceProject: Schema.optional(+ Schema.NullOr(Schema.Struct({ fullPath: Schema.String })),+ ),+ userPermissions: Schema.optional(+ Schema.NullOr(+ Schema.Struct({+ removeSourceBranch: Schema.optional(Schema.NullOr(Schema.Boolean)),+ }),+ ),+ ),+ }),+ ),+ }),+ ),+ }),+});++const decodeSourceBranch = decodeJsonResult(RawSourceBranchSchema);++export interface GitLabSourceBranch {+ readonly open: boolean;+ readonly branch: string;+ readonly headSha: string | null;+ /** Null when the source project is gone or hidden from the viewer, as a deleted fork is. */+ readonly sourceProject: string | null;+ /** GitLab's own answer: false once the branch is gone, protected, or out of the viewer's reach. */+ readonly canDelete: boolean;+}++export function decodeSourceBranchJson(+ raw: string,+): Result.Result<GitLabSourceBranch | null, DecodeFailure> {+ return Result.map(decodeSourceBranch(raw), (decoded) => {+ const mergeRequest = decoded.data.project?.mergeRequest;+ if (mergeRequest == null) return null;+ return {+ // `locked` is GitLab's transient state while a merge runs, so only these two are settled.+ open: mergeRequest.state !== "merged" && mergeRequest.state !== "closed",+ branch: mergeRequest.sourceBranch,+ headSha: trimmed(mergeRequest.diffHeadSha),+ sourceProject: mergeRequest.sourceProject?.fullPath ?? null,+ canDelete: mergeRequest.userPermissions?.removeSourceBranch === true,+ };+ });+}++const decodeBranch = decodeJsonResult(+ Schema.Struct({+ default: Schema.optional(Schema.NullOr(Schema.Boolean)),+ commit: Schema.optional(+ Schema.NullOr(+ Schema.Struct({+ id: Schema.String,+ authored_date: Schema.optional(Schema.NullOr(Schema.String)),+ }),+ ),+ ),+ }),+);++export function decodeBranchJson(raw: string): Result.Result<+ {+ readonly isDefault: boolean;+ readonly headSha: string | null;+ readonly headAuthoredDate: string | null;+ },+ DecodeFailure+> {+ return Result.map(decodeBranch(raw), (branch) => ({+ isDefault: branch.default === true,+ headSha: trimmed(branch.commit?.id),+ headAuthoredDate: trimmed(branch.commit?.authored_date),+ }));+}+export const MERGE_MESSAGES_GRAPHQL_QUERY = `query($fullPath: ID!, $iid: String!) {project(fullPath: $fullPath) {mergeRequest(iid: $iid) { title squashOnMerge defaultMergeCommitMessage defaultSquashCommitMessage }diff --git a/packages/source-control-gitlab/src/shared/definition.ts b/packages/source-control-gitlab/src/shared/definition.tsindex 0360cde8812..d31c7d9dfd1 100644--- a/packages/source-control-gitlab/src/shared/definition.ts+++ b/packages/source-control-gitlab/src/shared/definition.ts@@ -56,6 +56,7 @@ export const definition = defineSourceControl({"update-branch","enable-auto-merge","disable-auto-merge",+ "delete-branch",] as const),checkoutCommand: ({ number }) => `glab mr checkout ${number}`,changeRequestCloseCommand: /\bglab\s+mr\s+(?:merge|close)\b/u,