Skip to content

Commit b871551

Browse files
TonybynMp4claudejuliusmarminge
authored
fix(gitlab): merge requests can delete their source branch (#30453)
Co-authored-by: Claude Opus 5.5 <[email protected]> Co-authored-by: Julius Marminge <[email protected]>
1 parent e136e8e commit b871551

6 files changed

Lines changed: 366 additions & 4 deletions

File tree

‎packages/source-control-gitlab/src/server/GitLabPullRequestCli.test.ts‎

Lines changed: 109 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -87,6 +87,23 @@ function mergeRequestJson(overrides: Record<string, unknown>): string {
8787
});
8888
}
8989

90+
function sourceBranchJson(overrides: Record<string, unknown>): string {
91+
return JSON.stringify({
92+
data: {
93+
project: {
94+
mergeRequest: {
95+
state: "merged",
96+
sourceBranch: "feat/page",
97+
diffHeadSha: "head",
98+
sourceProject: { fullPath: "acme/web" },
99+
userPermissions: { removeSourceBranch: true },
100+
...overrides,
101+
},
102+
},
103+
},
104+
});
105+
}
106+
90107
function argsOfCall(index: number): ReadonlyArray<string> {
91108
return callAt(index).args;
92109
}
@@ -1465,6 +1482,98 @@ layer("GitLabPullRequestCli.layer", (it) => {
14651482
}),
14661483
);
14671484

1485+
it.effect.each([
1486+
{ answer: sourceBranchJson({}), expected: true },
1487+
{ answer: "not json", expected: false },
1488+
])("asks GitLab whether a merged merge request's branch can be deleted", ({ answer, expected }) =>
1489+
Effect.gen(function* () {
1490+
mockedExecute
1491+
.mockReturnValueOnce(Effect.succeed(output(mergeRequestJson({ state: "merged" }))))
1492+
.mockReturnValueOnce(Effect.succeed(labelPermission))
1493+
.mockReturnValueOnce(Effect.succeed(output(answer)));
1494+
const cli = yield* GitLabPullRequestCli.GitLabPullRequestCli;
1495+
1496+
const detail = yield* cli.getMergeRequestDetail({
1497+
cwd: "/w",
1498+
repository: "acme/web",
1499+
number: 7,
1500+
});
1501+
1502+
expect(detail.viewerCanDeleteBranch).toBe(expected);
1503+
expect(argsOfCall(2)).toContain("graphql");
1504+
}),
1505+
);
1506+
1507+
it.effect("deletes the source branch in the source project once its head is the merged one", () =>
1508+
Effect.gen(function* () {
1509+
mockedExecute
1510+
.mockReturnValueOnce(
1511+
Effect.succeed(output(sourceBranchJson({ sourceProject: { fullPath: "fork/web" } }))),
1512+
)
1513+
.mockReturnValueOnce(
1514+
Effect.succeed(
1515+
output(
1516+
JSON.stringify({
1517+
default: false,
1518+
commit: { id: "head", authored_date: "2026-11-03T20:29:40.000-07:00" },
1519+
}),
1520+
),
1521+
),
1522+
)
1523+
.mockReturnValueOnce(Effect.succeed(output("")));
1524+
const cli = yield* GitLabPullRequestCli.GitLabPullRequestCli;
1525+
1526+
yield* cli.runMergeRequestAction({
1527+
cwd: "/w",
1528+
repository: "acme/web",
1529+
number: 7,
1530+
action: "delete-branch",
1531+
});
1532+
1533+
expect(argsOfCall(1)).toEqual(["api", "projects/fork%2Fweb/repository/branches/feat%2Fpage"]);
1534+
expect(argsOfCall(2)).toEqual([
1535+
"api",
1536+
"projects/fork%2Fweb/repository/branches/feat%2Fpage",
1537+
"--method",
1538+
"DELETE",
1539+
"--header",
1540+
"If-Unmodified-Since: Wed, 04 Nov 2026 03:29:40 GMT",
1541+
]);
1542+
}),
1543+
);
1544+
1545+
it.effect.each([
1546+
{ reason: "open", source: { state: "opened" }, branch: undefined },
1547+
{ reason: "open", source: { state: "locked" }, branch: undefined },
1548+
{
1549+
reason: "not-allowed",
1550+
source: { userPermissions: { removeSourceBranch: false } },
1551+
branch: undefined,
1552+
},
1553+
{ reason: "default-branch", source: {}, branch: { default: true, commit: { id: "head" } } },
1554+
{ reason: "head-changed", source: {}, branch: { default: false, commit: { id: "newer" } } },
1555+
])("refuses to delete the source branch when it is $reason", ({ reason, source, branch }) =>
1556+
Effect.gen(function* () {
1557+
mockedExecute.mockReturnValueOnce(Effect.succeed(output(sourceBranchJson(source))));
1558+
if (branch !== undefined) {
1559+
mockedExecute.mockReturnValueOnce(Effect.succeed(output(JSON.stringify(branch))));
1560+
}
1561+
const cli = yield* GitLabPullRequestCli.GitLabPullRequestCli;
1562+
1563+
const error = yield* cli
1564+
.runMergeRequestAction({
1565+
cwd: "/w",
1566+
repository: "acme/web",
1567+
number: 7,
1568+
action: "delete-branch",
1569+
})
1570+
.pipe(Effect.flip);
1571+
1572+
expect(error).toMatchObject({ _tag: "GitLabBranchDeletionRefusedError", reason });
1573+
expect(mockedExecute).toHaveBeenCalledTimes(branch === undefined ? 1 : 2);
1574+
}),
1575+
);
1576+
14681577
it.effect("reads who has access to the project and who is already on the merge request", () =>
14691578
Effect.gen(function* () {
14701579
mockedExecute

‎packages/source-control-gitlab/src/server/GitLabPullRequestCli.ts‎

Lines changed: 146 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,10 @@
11
import { removeAgentCredits } from "@t3tools/source-control-core/server/mergeMessage";
22
import { isCommitSha } from "@t3tools/source-control-core/server/pullRequestUtils";
33
import * as Context from "effect/Context";
4+
import * as DateTime from "effect/DateTime";
45
import * as Effect from "effect/Effect";
56
import * as Layer from "effect/Layer";
7+
import * as Option from "effect/Option";
68
import * as Result from "effect/Result";
79
import * as Schema from "effect/Schema";
810
import { resolvePullRequestAuthorFilter, VcsProcessExitError } from "@t3tools/contracts";
@@ -33,6 +35,7 @@ import * as GitLabCli from "./GitLabCli.ts";
3335
import {
3436
AWARD_EMOJI_GRAPHQL_QUERY,
3537
decodeAwardEmojiJson,
38+
decodeBranchJson,
3639
decodeCommitDiffRefsJson,
3740
decodeCommitsJson,
3841
decodeDiffRefsJson,
@@ -53,6 +56,7 @@ import {
5356
decodeProjectUsersJson,
5457
decodeRepositoryBlobsJson,
5558
decodeReviewDecisionsJson,
59+
decodeSourceBranchJson,
5660
decodeTriggerJobChecksJson,
5761
decodeViewerJson,
5862
gitLabAwardName,
@@ -62,6 +66,7 @@ import {
6266
MERGE_REQUEST_STATS_GRAPHQL_QUERY,
6367
REPOSITORY_BLOBS_GRAPHQL_QUERY,
6468
REVIEW_DECISIONS_GRAPHQL_QUERY,
69+
SOURCE_BRANCH_GRAPHQL_QUERY,
6570
type GitLabDiffRefs,
6671
type GitLabMergeRequestDetail,
6772
type GitLabMergeRequestListItem,
@@ -193,6 +198,41 @@ export class GitLabDiffFileContentsUnavailableError extends Schema.TaggedError<G
193198
}
194199
}
195200

201+
export class GitLabBranchDeletionRefusedError extends Schema.TaggedError<GitLabBranchDeletionRefusedError>()(
202+
"GitLabBranchDeletionRefusedError",
203+
{
204+
command: Schema.Literal("glab"),
205+
cwd: Schema.String,
206+
number: Schema.Int,
207+
reason: Schema.Literals([
208+
"open",
209+
"not-allowed",
210+
"source-unavailable",
211+
"default-branch",
212+
"head-changed",
213+
]),
214+
},
215+
) {
216+
get detail(): string {
217+
switch (this.reason) {
218+
case "open":
219+
return `Close or merge merge request !${this.number} before deleting its source branch.`;
220+
case "not-allowed":
221+
return "GitLab does not let you delete this source branch. It may be protected, or you may not be able to push to it.";
222+
case "source-unavailable":
223+
return `GitLab did not report a source project for merge request !${this.number}.`;
224+
case "default-branch":
225+
return "The source branch is its project's default branch and cannot be deleted here.";
226+
case "head-changed":
227+
return "The source branch has new commits and was not deleted.";
228+
}
229+
}
230+
231+
override get message(): string {
232+
return `GitLab CLI failed in deleteSourceBranch: ${this.detail}`;
233+
}
234+
}
235+
196236
export class GitLabUnknownLabelError extends Schema.TaggedError<GitLabUnknownLabelError>()(
197237
"GitLabUnknownLabelError",
198238
{
@@ -212,6 +252,7 @@ export class GitLabUnknownLabelError extends Schema.TaggedError<GitLabUnknownLab
212252

213253
export type GitLabPullRequestCliError =
214254
| GitLabCli.GitLabCliError
255+
| GitLabBranchDeletionRefusedError
215256
| GitLabMergeRequestReadError
216257
| GitLabUnknownLabelError
217258
| GitLabDiffCursorError
@@ -657,6 +698,7 @@ export const make = Effect.gen(function* () {
657698
readonly path: string;
658699
readonly method?: string;
659700
readonly stdin?: string;
701+
readonly headers?: ReadonlyArray<string>;
660702
readonly maxOutputBytes?: number;
661703
readonly timeoutMs?: number;
662704
}) =>
@@ -671,6 +713,7 @@ export const make = Effect.gen(function* () {
671713
...(input.stdin === undefined
672714
? []
673715
: ["--input", "-", "--header", "Content-Type: application/json"]),
716+
...(input.headers ?? []).flatMap((header) => ["--header", header]),
674717
],
675718
...(input.stdin === undefined ? {} : { stdin: input.stdin }),
676719
...(input.maxOutputBytes === undefined ? {} : { maxOutputBytes: input.maxOutputBytes }),
@@ -1281,6 +1324,88 @@ export const make = Effect.gen(function* () {
12811324
),
12821325
);
12831326

1327+
const sourceBranch = (input: {
1328+
readonly cwd: string;
1329+
readonly host?: string | undefined;
1330+
readonly repository: string;
1331+
readonly number: number;
1332+
}) =>
1333+
graphqlRead({
1334+
cwd: input.cwd,
1335+
host: input.host,
1336+
operation: "getSourceBranch",
1337+
query: SOURCE_BRANCH_GRAPHQL_QUERY,
1338+
variables: { fullPath: input.repository, iid: String(input.number) },
1339+
decode: decodeSourceBranchJson,
1340+
});
1341+
1342+
const deleteSourceBranch = Effect.fn("GitLabPullRequestCli.deleteSourceBranch")(
1343+
function* (input: {
1344+
readonly cwd: string;
1345+
readonly host?: string | undefined;
1346+
readonly repository: string;
1347+
readonly number: number;
1348+
}) {
1349+
const refuse = (reason: GitLabBranchDeletionRefusedError["reason"]) =>
1350+
new GitLabBranchDeletionRefusedError({
1351+
command: "glab",
1352+
cwd: input.cwd,
1353+
number: input.number,
1354+
reason,
1355+
});
1356+
const source = yield* sourceBranch(input);
1357+
if (source === null) {
1358+
return yield* new GitLabMergeRequestReadError({
1359+
command: "glab",
1360+
cwd: input.cwd,
1361+
operation: "getSourceBranch",
1362+
cause: new Error("GitLab reported no merge request."),
1363+
});
1364+
}
1365+
if (source.open) return yield* refuse("open");
1366+
if (!source.canDelete) return yield* refuse("not-allowed");
1367+
if (source.sourceProject === null || source.headSha === null) {
1368+
return yield* refuse("source-unavailable");
1369+
}
1370+
const path = `projects/${projectPath(source.sourceProject)}/repository/branches/${encodeURIComponent(source.branch)}`;
1371+
const branch = yield* api({ cwd: input.cwd, host: input.host, path }).pipe(
1372+
Effect.flatMap((result) => {
1373+
const decoded = decodeBranchJson(result.stdout.trim());
1374+
return Result.isSuccess(decoded)
1375+
? Effect.succeed(decoded.success)
1376+
: Effect.fail(
1377+
new GitLabMergeRequestReadError({
1378+
command: "glab",
1379+
cwd: input.cwd,
1380+
operation: "getSourceBranch",
1381+
cause: decoded.failure,
1382+
}),
1383+
);
1384+
}),
1385+
);
1386+
if (branch.isDefault) return yield* refuse("default-branch");
1387+
if (branch.headSha !== source.headSha) return yield* refuse("head-changed");
1388+
// GitLab's branch delete takes no expected SHA. It answers 412 when the head's authored
1389+
// date is newer than If-Unmodified-Since, which catches a commit pushed after this read but
1390+
// not a force-push of an older-dated commit (a rebase keeps author dates).
1391+
const authoredAt =
1392+
branch.headAuthoredDate === null ? Option.none() : DateTime.make(branch.headAuthoredDate);
1393+
yield* api({
1394+
cwd: input.cwd,
1395+
host: input.host,
1396+
path,
1397+
method: "DELETE",
1398+
...(Option.isNone(authoredAt)
1399+
? {}
1400+
: {
1401+
headers: [
1402+
`If-Unmodified-Since: ${DateTime.toDateUtc(authoredAt.value).toUTCString()}`,
1403+
],
1404+
}),
1405+
});
1406+
},
1407+
);
1408+
12841409
const mergeRequestStats = (input: {
12851410
readonly cwd: string;
12861411
readonly host?: string | undefined;
@@ -1472,7 +1597,26 @@ export const make = Effect.gen(function* () {
14721597
[mergeRequestDetail(input), labelPermission(input)],
14731598
{ concurrency: 2 },
14741599
);
1475-
const detail = { ...read, viewerCanEditLabels };
1600+
// Only a closed or merged merge request offers its branch for deletion, so an open one,
1601+
// the page most often read, skips the extra query.
1602+
const detail =
1603+
read.state === "open"
1604+
? { ...read, viewerCanEditLabels }
1605+
: {
1606+
...read,
1607+
viewerCanEditLabels,
1608+
viewerCanDeleteBranch: yield* sourceBranch(input).pipe(
1609+
Effect.map((source) => source?.canDelete === true),
1610+
// The answer gates one optional action; an unusable CLI or account still surfaces.
1611+
Effect.catchIf(
1612+
(cause) =>
1613+
cause._tag !== "GitLabCliUnavailableError" &&
1614+
cause._tag !== "GitLabCliAuthenticationError" &&
1615+
cause._tag !== "GitLabCliRateLimitError",
1616+
() => Effect.succeed(false),
1617+
),
1618+
),
1619+
};
14761620
if (input.downstreamChecks === false || detail.headPipeline === undefined) return detail;
14771621
const downstream = yield* triggerJobChecks({
14781622
cwd: input.cwd,
@@ -1820,6 +1964,7 @@ export const make = Effect.gen(function* () {
18201964
// `glab mr merge` arms auto-merge and never disarms it, so the one direction the CLI has
18211965
// no flag for is asked of GitLab directly through the same `api` passthrough the rest of
18221966
// this module writes with.
1967+
if (input.action === "delete-branch") return yield* deleteSourceBranch(input);
18231968
if (input.action === "disable-auto-merge") {
18241969
const result = yield* api({
18251970
cwd: input.cwd,

‎packages/source-control-gitlab/src/server/GitLabPullRequestProvider.test.ts‎

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -123,7 +123,13 @@ it.effect.each(["merge", "disable-auto-merge"] as const)(
123123

124124
describe("gitLabViewerPermissions", () => {
125125
it("offers everything to a viewer GitLab says can merge", () => {
126-
expect(gitLabViewerPermissions({ viewerCanMerge: true, viewerCanEditLabels: true })).toEqual({
126+
expect(
127+
gitLabViewerPermissions({
128+
viewerCanMerge: true,
129+
viewerCanDeleteBranch: true,
130+
viewerCanEditLabels: true,
131+
}),
132+
).toEqual({
127133
actions: [
128134
"merge",
129135
"ready",
@@ -133,6 +139,7 @@ describe("gitLabViewerPermissions", () => {
133139
"update-branch",
134140
"enable-auto-merge",
135141
"disable-auto-merge",
142+
"delete-branch",
136143
],
137144
comment: true,
138145
resolve: true,

‎packages/source-control-gitlab/src/server/GitLabPullRequestProvider.ts‎

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,7 @@ const CAPABILITIES: PullRequestCapabilities = {
2727
comment: true,
2828
actions: [...definition.changeRequestActions],
2929
mergeMethods: ["merge", "squash", "rebase"],
30+
deleteBranch: true,
3031
// GitLab has no merge-target-into-source operation.
3132
updateMethods: ["rebase"],
3233
search: true,
@@ -66,11 +67,14 @@ const MERGE_ACTIONS: ReadonlySet<string> = new Set([
6667
/** Authors may close/reopen/change draft state regardless of role; REST omits authorship. */
6768
export function gitLabViewerPermissions(input: {
6869
readonly viewerCanMerge: boolean;
70+
readonly viewerCanDeleteBranch?: boolean;
6971
readonly viewerCanEditLabels?: boolean | undefined;
7072
}): PullRequestViewerPermissions {
7173
return {
72-
actions: CAPABILITIES.actions.filter(
73-
(action) => !MERGE_ACTIONS.has(action) || input.viewerCanMerge,
74+
actions: CAPABILITIES.actions.filter((action) =>
75+
action === "delete-branch"
76+
? input.viewerCanDeleteBranch === true
77+
: !MERGE_ACTIONS.has(action) || input.viewerCanMerge,
7478
),
7579
comment: true,
7680
resolve: true,

0 commit comments

Comments
 (0)