Skip to content

Commit 362ef9a

Browse files
TonybynMp4claudemaria-rcksjuliusmarminge
authored
feat(gitlab): revert a merged merge request (#30556)
Co-authored-by: Claude Opus 5.5 <[email protected]> Co-authored-by: maria-rcks <[email protected]> Co-authored-by: Julius Marminge <[email protected]>
1 parent b6d3097 commit 362ef9a

6 files changed

Lines changed: 343 additions & 0 deletions

File tree

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

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

90+
function commitJson(id: string) {
91+
return { id, title: "Commit", committed_date: "2026-07-01T00:00:00Z" };
92+
}
93+
9094
function sourceBranchJson(overrides: Record<string, unknown>): string {
9195
return JSON.stringify({
9296
data: {
@@ -871,6 +875,182 @@ layer("GitLabPullRequestCli.layer", (it) => {
871875
}),
872876
);
873877

878+
it.effect("reverts a merged merge request onto a new branch and opens a merge request", () =>
879+
Effect.gen(function* () {
880+
const mergeCommit = "dac72fa101758a44b0068a23666559920a74478f";
881+
mockedExecute
882+
.mockReturnValueOnce(
883+
Effect.succeed(
884+
output(
885+
mergeRequestJson({
886+
state: "merged",
887+
merge_commit_sha: mergeCommit,
888+
squash_commit_sha: "cb2d9f660ebe946e5056ae98993db5ea72b9bad1",
889+
}),
890+
),
891+
),
892+
)
893+
.mockReturnValue(Effect.succeed(output("{}")));
894+
const cli = yield* GitLabPullRequestCli.GitLabPullRequestCli;
895+
896+
yield* cli.runMergeRequestAction({
897+
cwd: "/w",
898+
repository: "acme/web",
899+
number: 7,
900+
action: "revert",
901+
});
902+
903+
expect(
904+
mockedExecute.mock.calls.map(([input]) => [
905+
input.args[1],
906+
input.stdin && JSON.parse(input.stdin),
907+
]),
908+
).toEqual([
909+
["projects/acme%2Fweb/merge_requests/7", undefined],
910+
["projects/acme%2Fweb/repository/branches", { branch: "revert-dac72fa1", ref: "main" }],
911+
[
912+
`projects/acme%2Fweb/repository/commits/${mergeCommit}/revert`,
913+
{ branch: "revert-dac72fa1" },
914+
],
915+
[
916+
"projects/acme%2Fweb/merge_requests",
917+
{
918+
source_branch: "revert-dac72fa1",
919+
target_branch: "main",
920+
title: 'Revert "Merge request 7"',
921+
description: "This reverts merge request !7",
922+
remove_source_branch: true,
923+
},
924+
],
925+
]);
926+
}),
927+
);
928+
929+
it.effect.each([
930+
["the revert conflicts", "/revert", "Failure"],
931+
["opening the merge request fails", "/merge_requests", "Failure"],
932+
["the request is interrupted", "/revert", "Interrupt"],
933+
] as const)("deletes the revert branch when %s", ([, failingPath, outcome]) =>
934+
Effect.gen(function* () {
935+
mockedExecute.mockImplementation(({ args, cwd }) =>
936+
args[1]?.endsWith(failingPath) && args.includes("POST")
937+
? outcome === "Interrupt"
938+
? Effect.interrupt
939+
: Effect.fail(
940+
new GitLabCli.GitLabCliCommandError({
941+
operation: "execute",
942+
command: "glab",
943+
cwd,
944+
cause: new Error("GitLab rejected the write"),
945+
}),
946+
)
947+
: Effect.succeed(
948+
output(
949+
mergeRequestJson({
950+
state: "merged",
951+
merge_commit_sha: null,
952+
squash_commit_sha: "abc12345ff",
953+
}),
954+
),
955+
),
956+
);
957+
const cli = yield* GitLabPullRequestCli.GitLabPullRequestCli;
958+
959+
const exit = yield* Effect.exit(
960+
cli.runMergeRequestAction({
961+
cwd: "/w",
962+
repository: "acme/web",
963+
number: 7,
964+
action: "revert",
965+
}),
966+
);
967+
968+
expect(exit._tag).toBe("Failure");
969+
expect(mockedExecute.mock.calls.at(-1)?.[0].args.slice(1, 4)).toEqual([
970+
"projects/acme%2Fweb/repository/branches/revert-abc12345",
971+
"--method",
972+
"DELETE",
973+
]);
974+
}),
975+
);
976+
977+
it.effect.each([
978+
["reverts the sole commit of", [commitJson("1111111122")], "revert-11111111"],
979+
[
980+
"refuses to revert several commits of",
981+
[commitJson("1111111122"), commitJson("2222222233")],
982+
"GitLabRevertUnavailableError",
983+
],
984+
] as const)("%s a fast-forward merge without squash", ([, commits, expected]) =>
985+
Effect.gen(function* () {
986+
mockedExecute
987+
.mockReturnValueOnce(
988+
Effect.succeed(
989+
output(
990+
mergeRequestJson({
991+
state: "merged",
992+
merge_commit_sha: null,
993+
squash_commit_sha: null,
994+
}),
995+
),
996+
),
997+
)
998+
.mockReturnValueOnce(Effect.succeed(output(JSON.stringify(commits))))
999+
.mockReturnValue(Effect.succeed(output("{}")));
1000+
const cli = yield* GitLabPullRequestCli.GitLabPullRequestCli;
1001+
1002+
const result = yield* Effect.result(
1003+
cli.runMergeRequestAction({
1004+
cwd: "/w",
1005+
repository: "acme/web",
1006+
number: 7,
1007+
action: "revert",
1008+
}),
1009+
);
1010+
1011+
expect(argsOfCall(1)[1]).toBe("projects/acme%2Fweb/merge_requests/7/commits?per_page=2");
1012+
if (expected === "GitLabRevertUnavailableError") {
1013+
expect(result).toMatchObject({ _tag: "Failure", failure: { _tag: expected } });
1014+
} else {
1015+
expect(JSON.parse(callAt(2).stdin ?? "")).toEqual({ branch: expected, ref: "main" });
1016+
}
1017+
}),
1018+
);
1019+
1020+
it.effect("refuses to revert a merge request that is not merged before any write", () =>
1021+
Effect.gen(function* () {
1022+
mockedExecute
1023+
.mockReturnValueOnce(
1024+
Effect.succeed(
1025+
output(
1026+
mergeRequestJson({
1027+
state: "opened",
1028+
merge_commit_sha: null,
1029+
squash_commit_sha: null,
1030+
}),
1031+
),
1032+
),
1033+
)
1034+
.mockReturnValue(Effect.succeed(output(JSON.stringify([commitJson("1111111122")]))));
1035+
const cli = yield* GitLabPullRequestCli.GitLabPullRequestCli;
1036+
1037+
const result = yield* Effect.result(
1038+
cli.runMergeRequestAction({
1039+
cwd: "/w",
1040+
repository: "acme/web",
1041+
number: 7,
1042+
action: "revert",
1043+
}),
1044+
);
1045+
1046+
expect(result).toMatchObject({
1047+
_tag: "Failure",
1048+
failure: { _tag: "GitLabRevertUnavailableError", reason: "not-merged" },
1049+
});
1050+
expect(mockedExecute).toHaveBeenCalledTimes(1);
1051+
}),
1052+
);
1053+
8741054
it.effect("sends a comment body over stdin, never in argv", () =>
8751055
Effect.gen(function* () {
8761056
mockedExecute.mockReturnValueOnce(Effect.succeed(output("")));

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

Lines changed: 128 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,7 @@ import {
4343
decodeCommitDiffRefsJson,
4444
decodeCommitsJson,
4545
decodeDiffRefsJson,
46+
decodeRevertTargetJson,
4647
decodeDiscussionsJson,
4748
decodeMaintainerEditsPermissionJson,
4849
decodeLabelNameJson,
@@ -143,6 +144,26 @@ export class GitLabDiffRefsUnavailableError extends Schema.TaggedError<GitLabDif
143144
}
144145
}
145146

147+
export class GitLabRevertUnavailableError extends Schema.TaggedError<GitLabRevertUnavailableError>()(
148+
"GitLabRevertUnavailableError",
149+
{
150+
command: Schema.Literal("glab"),
151+
cwd: Schema.String,
152+
number: Schema.Int,
153+
reason: Schema.Literals(["not-merged", "several-commits"]),
154+
},
155+
) {
156+
get detail(): string {
157+
return this.reason === "not-merged"
158+
? "Only a merged merge request can be reverted."
159+
: "This merge request landed as several commits, so there is no single commit to revert.";
160+
}
161+
162+
override get message(): string {
163+
return `GitLab CLI failed in runMergeRequestAction: ${this.detail}`;
164+
}
165+
}
166+
146167
export class GitLabDiffCursorError extends Schema.TaggedError<GitLabDiffCursorError>()(
147168
"GitLabDiffCursorError",
148169
{
@@ -302,6 +323,7 @@ export type GitLabPullRequestCliError =
302323
| GitLabDiffCommitParentUnavailableError
303324
| GitLabDiffFileContentsUnavailableError
304325
| GitLabDiffRefsUnavailableError
326+
| GitLabRevertUnavailableError
305327
| GitLabViewerUnavailableError
306328
| GitLabMutationRefusedError;
307329

@@ -989,6 +1011,7 @@ function actionArgs(
9891011
case "reopen":
9901012
return ["reopen"];
9911013
case "revert":
1014+
return [];
9921015
case "approve-workflows":
9931016
case "delete-branch":
9941017
throw new Error(`GitLab merge request action ${action} is unsupported`);
@@ -1342,6 +1365,110 @@ export const make = Effect.gen(function* () {
13421365
}),
13431366
);
13441367

1368+
/** GitLab reverts a fast-forward merge without squash only when it landed as one commit. */
1369+
const soleCommitSha = (input: {
1370+
readonly cwd: string;
1371+
readonly host?: string | undefined;
1372+
readonly repository: string;
1373+
readonly number: number;
1374+
}) =>
1375+
api({
1376+
cwd: input.cwd,
1377+
host: input.host,
1378+
path: `projects/${projectPath(input.repository)}/merge_requests/${input.number}/commits?per_page=2`,
1379+
}).pipe(
1380+
Effect.flatMap((result) => {
1381+
const decoded = decodeCommitsJson(result.stdout.trim());
1382+
if (!Result.isSuccess(decoded)) {
1383+
return Effect.fail(
1384+
new GitLabMergeRequestReadError({
1385+
command: "glab",
1386+
cwd: input.cwd,
1387+
operation: "runMergeRequestAction",
1388+
cause: decoded.failure,
1389+
}),
1390+
);
1391+
}
1392+
const [only, ...rest] = decoded.success;
1393+
return Effect.succeed(only !== undefined && rest.length === 0 ? only.oid : null);
1394+
}),
1395+
);
1396+
1397+
/** What GitLab's own Revert button does: revert onto a new branch and open a merge request. */
1398+
const revertMergeRequest = Effect.fn("GitLabPullRequestCli.revertMergeRequest")(
1399+
function* (input: {
1400+
readonly cwd: string;
1401+
readonly host?: string | undefined;
1402+
readonly repository: string;
1403+
readonly number: number;
1404+
}) {
1405+
const project = `projects/${projectPath(input.repository)}`;
1406+
const write = (path: string, body: object) =>
1407+
api({
1408+
cwd: input.cwd,
1409+
host: input.host,
1410+
path: `${project}/${path}`,
1411+
method: "POST",
1412+
stdin: JSON.stringify(body),
1413+
});
1414+
const raw = yield* api({
1415+
cwd: input.cwd,
1416+
host: input.host,
1417+
path: `${project}/merge_requests/${input.number}`,
1418+
});
1419+
const decoded = decodeRevertTargetJson(raw.stdout.trim());
1420+
if (!Result.isSuccess(decoded)) {
1421+
return yield* new GitLabMergeRequestReadError({
1422+
command: "glab",
1423+
cwd: input.cwd,
1424+
operation: "runMergeRequestAction",
1425+
cause: decoded.failure,
1426+
});
1427+
}
1428+
const target = decoded.success;
1429+
if (!target.merged) {
1430+
return yield* new GitLabRevertUnavailableError({
1431+
command: "glab",
1432+
cwd: input.cwd,
1433+
number: input.number,
1434+
reason: "not-merged",
1435+
});
1436+
}
1437+
const commitSha = target.commitSha ?? (yield* soleCommitSha(input));
1438+
if (commitSha === null) {
1439+
return yield* new GitLabRevertUnavailableError({
1440+
command: "glab",
1441+
cwd: input.cwd,
1442+
number: input.number,
1443+
reason: "several-commits",
1444+
});
1445+
}
1446+
const branch = `revert-${commitSha.slice(0, 8)}`;
1447+
yield* write("repository/branches", { branch, ref: target.targetBranch });
1448+
yield* Effect.andThen(
1449+
write(`repository/commits/${commitSha}/revert`, { branch }),
1450+
write("merge_requests", {
1451+
source_branch: branch,
1452+
target_branch: target.targetBranch,
1453+
title: `Revert "${target.title}"`,
1454+
description: `This reverts merge request !${input.number}`,
1455+
remove_source_branch: true,
1456+
}),
1457+
).pipe(
1458+
// Leaving the branch behind would make every retry fail on creating it again. Runs on
1459+
// interruption too, which a cancelled request or a dropped socket causes.
1460+
Effect.onError(() =>
1461+
api({
1462+
cwd: input.cwd,
1463+
host: input.host,
1464+
path: `${project}/repository/branches/${encodeURIComponent(branch)}`,
1465+
method: "DELETE",
1466+
}).pipe(Effect.ignore),
1467+
),
1468+
);
1469+
},
1470+
);
1471+
13451472
const getDiffRefs = (input: {
13461473
readonly cwd: string;
13471474
readonly host?: string | undefined;
@@ -2558,6 +2685,7 @@ export const make = Effect.gen(function* () {
25582685
} = decoded.success;
25592686
return summary;
25602687
}
2688+
if (input.action === "revert") return yield* revertMergeRequest(input);
25612689
const executeMr = (subcommand: string, ...flags: ReadonlyArray<string>) =>
25622690
gitlab.execute({
25632691
cwd: input.cwd,

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

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -139,6 +139,7 @@ describe("gitLabViewerPermissions", () => {
139139
"update-branch",
140140
"enable-auto-merge",
141141
"disable-auto-merge",
142+
"revert",
142143
"delete-branch",
143144
],
144145
comment: true,

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

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -58,12 +58,14 @@ const UNAVAILABLE_REQUIREMENT = {
5858
* The actions `user.can_merge` answers for. Rebasing writes to the source branch rather than to
5959
* the target, so it is not literally the same permission — but GitLab reports nothing narrower,
6060
* and someone it will not let land this change has no business rewriting its branch either.
61+
* Reverting pushes a branch to the target project, which the same permission covers.
6162
*/
6263
const MERGE_ACTIONS: ReadonlySet<string> = new Set([
6364
"merge",
6465
"update-branch",
6566
"enable-auto-merge",
6667
"disable-auto-merge",
68+
"revert",
6769
]);
6870

6971
/** Authors may close/reopen/change draft state regardless of role; REST omits authorship. */

0 commit comments

Comments
 (0)