@devries-cameron20 / t3code Mirror · read-only / commits / 362ef9a88a
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 23:30 UTC

feat(gitlab): revert a merged merge request (#30556)

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: maria-rcks <maria@kuuro.net> Co-authored-by: Julius Marminge <julius0216@outlook.com>

Antony committed Nov 11, 2026 at 08:07 UTC 362ef9a88a18b7f692864409c35c15cc28d7a09e
6 files changed +343
packages/source-control-gitlab/src/server/GitLabPullRequestCli.test.ts
+180
@@ -87,6 +87,10 @@ function mergeRequestJson(overrides: Record<string, unknown>): string {
87 });
88 }
89
90 +function commitJson(id: string) {
91 + return { id, title: "Commit", committed_date: "2026-07-01T00:00:00Z" };
92 +}
93 +
94 function sourceBranchJson(overrides: Record<string, unknown>): string {
95 return JSON.stringify({
96 data: {
@@ -871,6 +875,182 @@ layer("GitLabPullRequestCli.layer", (it) => {
875 }),
876 );
877
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 +
1054 it.effect("sends a comment body over stdin, never in argv", () =>
1055 Effect.gen(function* () {
1056 mockedExecute.mockReturnValueOnce(Effect.succeed(output("")));
packages/source-control-gitlab/src/server/GitLabPullRequestCli.ts
+128
@@ -43,6 +43,7 @@ import {
43 decodeCommitDiffRefsJson,
44 decodeCommitsJson,
45 decodeDiffRefsJson,
46 + decodeRevertTargetJson,
47 decodeDiscussionsJson,
48 decodeMaintainerEditsPermissionJson,
49 decodeLabelNameJson,
@@ -143,6 +144,26 @@ export class GitLabDiffRefsUnavailableError extends Schema.TaggedError<GitLabDif
144 }
145 }
146
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 +
167 export class GitLabDiffCursorError extends Schema.TaggedError<GitLabDiffCursorError>()(
168 "GitLabDiffCursorError",
169 {
@@ -302,6 +323,7 @@ export type GitLabPullRequestCliError =
323 | GitLabDiffCommitParentUnavailableError
324 | GitLabDiffFileContentsUnavailableError
325 | GitLabDiffRefsUnavailableError
326 + | GitLabRevertUnavailableError
327 | GitLabViewerUnavailableError
328 | GitLabMutationRefusedError;
329
@@ -989,6 +1011,7 @@ function actionArgs(
1011 case "reopen":
1012 return ["reopen"];
1013 case "revert":
1014 + return [];
1015 case "approve-workflows":
1016 case "delete-branch":
1017 throw new Error(`GitLab merge request action ${action} is unsupported`);
@@ -1342,6 +1365,110 @@ export const make = Effect.gen(function* () {
1365 }),
1366 );
1367
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 +
1472 const getDiffRefs = (input: {
1473 readonly cwd: string;
1474 readonly host?: string | undefined;
@@ -2558,6 +2685,7 @@ export const make = Effect.gen(function* () {
2685 } = decoded.success;
2686 return summary;
2687 }
2688 + if (input.action === "revert") return yield* revertMergeRequest(input);
2689 const executeMr = (subcommand: string, ...flags: ReadonlyArray<string>) =>
2690 gitlab.execute({
2691 cwd: input.cwd,
packages/source-control-gitlab/src/server/GitLabPullRequestProvider.test.ts
+1
@@ -139,6 +139,7 @@ describe("gitLabViewerPermissions", () => {
139 "update-branch",
140 "enable-auto-merge",
141 "disable-auto-merge",
142 + "revert",
143 "delete-branch",
144 ],
145 comment: true,
packages/source-control-gitlab/src/server/GitLabPullRequestProvider.ts
+2
@@ -58,12 +58,14 @@ const UNAVAILABLE_REQUIREMENT = {
58 * The actions `user.can_merge` answers for. Rebasing writes to the source branch rather than to
59 * the target, so it is not literally the same permission — but GitLab reports nothing narrower,
60 * 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.
62 */
63 const MERGE_ACTIONS: ReadonlySet<string> = new Set([
64 "merge",
65 "update-branch",
66 "enable-auto-merge",
67 "disable-auto-merge",
68 + "revert",
69 ]);
70
71 /** Authors may close/reopen/change draft state regardless of role; REST omits authorship. */
packages/source-control-gitlab/src/server/gitLabMergeRequestJson.ts
+31
@@ -149,6 +149,14 @@ const RawDiffRefsSchema = Schema.Struct({
149 diff_refs: Schema.optional(Schema.NullOr(RawDiffRefs)),
150 });
151
152 +const RawRevertTargetSchema = Schema.Struct({
153 + title: Schema.String,
154 + state: Schema.String,
155 + target_branch: Schema.String,
156 + merge_commit_sha: Schema.optional(Schema.NullOr(Schema.String)),
157 + squash_commit_sha: Schema.optional(Schema.NullOr(Schema.String)),
158 +});
159 +
160 const RawCommitSchema = Schema.Struct({
161 id: TrimmedNonEmptyString,
162 title: Schema.optional(Schema.NullOr(Schema.String)),
@@ -564,6 +572,7 @@ const decodeMergeRequestChanges = decodeJsonResult(
572 const decodeDiffEntry = Schema.decodeUnknownExit(RawDiffSchema);
573 const decodeDiscussionEntry = Schema.decodeUnknownExit(RawDiscussionSchema);
574 const decodeDiffRefs = decodeJsonResult(RawDiffRefsSchema);
575 +const decodeRevertTarget = decodeJsonResult(RawRevertTargetSchema);
576 const decodeViewer = decodeJsonResult(RawViewerSchema);
577 const decodeProjectMergeSettings = decodeJsonResult(RawProjectMergeSettingsSchema);
578
@@ -867,6 +876,28 @@ export function decodeDiffRefsJson(
876 return Result.succeed(refs ? toDiffRefs(refs) : null);
877 }
878
879 +export interface GitLabRevertTarget {
880 + readonly merged: boolean;
881 + readonly title: string;
882 + readonly targetBranch: string;
883 + /** Null for a fast-forward merge without squash, which records neither SHA. */
884 + readonly commitSha: string | null;
885 +}
886 +
887 +export function decodeRevertTargetJson(
888 + raw: string,
889 +): Result.Result<GitLabRevertTarget, DecodeFailure> {
890 + const decoded = decodeRevertTarget(raw);
891 + if (!Result.isSuccess(decoded)) return Result.fail(decoded.failure);
892 + const mr = decoded.success;
893 + return Result.succeed({
894 + merged: mr.state === "merged",
895 + title: mr.title,
896 + targetBranch: mr.target_branch,
897 + commitSha: trimmed(mr.merge_commit_sha) ?? trimmed(mr.squash_commit_sha),
898 + });
899 +}
900 +
901 export function decodeNotesJson(
902 raw: string,
903 ): Result.Result<
packages/source-control-gitlab/src/shared/definition.ts
+1
@@ -63,6 +63,7 @@ export const definition = defineSourceControl({
63 "update-branch",
64 "enable-auto-merge",
65 "disable-auto-merge",
66 + "revert",
67 "delete-branch",
68 ] as const),
69 checkoutCommand: ({ number }) => `glab mr checkout ${number}`,