Skip to content

Commit 5586c4c

Browse files
TonybynMp4claude
andcommitted
feat(gitlab): revert a merged merge request
Co-Authored-By: Claude Opus 5.5 <[email protected]>
1 parent a185dd9 commit 5586c4c

6 files changed

Lines changed: 202 additions & 0 deletions

File tree

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

Lines changed: 87 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -466,6 +466,93 @@ layer("GitLabPullRequestCli.layer", (it) => {
466466
}),
467467
);
468468

469+
it.effect("reverts a merged merge request onto a new branch and opens a merge request", () =>
470+
Effect.gen(function* () {
471+
const mergeCommit = "dac72fa101758a44b0068a23666559920a74478f";
472+
mockedExecute
473+
.mockReturnValueOnce(
474+
Effect.succeed(
475+
output(
476+
mergeRequestJson({
477+
merge_commit_sha: mergeCommit,
478+
squash_commit_sha: "cb2d9f660ebe946e5056ae98993db5ea72b9bad1",
479+
}),
480+
),
481+
),
482+
)
483+
.mockReturnValue(Effect.succeed(output("{}")));
484+
const cli = yield* GitLabPullRequestCli.GitLabPullRequestCli;
485+
486+
yield* cli.runMergeRequestAction({
487+
cwd: "/w",
488+
repository: "acme/web",
489+
number: 7,
490+
action: "revert",
491+
});
492+
493+
expect(
494+
mockedExecute.mock.calls.map(([input]) => [
495+
input.args[1],
496+
input.stdin && JSON.parse(input.stdin),
497+
]),
498+
).toEqual([
499+
["projects/acme%2Fweb/merge_requests/7", undefined],
500+
["projects/acme%2Fweb/repository/branches", { branch: "revert-dac72fa1", ref: "main" }],
501+
[
502+
`projects/acme%2Fweb/repository/commits/${mergeCommit}/revert`,
503+
{ branch: "revert-dac72fa1" },
504+
],
505+
[
506+
"projects/acme%2Fweb/merge_requests",
507+
{
508+
source_branch: "revert-dac72fa1",
509+
target_branch: "main",
510+
title: 'Revert "Merge request 7"',
511+
description: "This reverts merge request !7",
512+
remove_source_branch: true,
513+
},
514+
],
515+
]);
516+
}),
517+
);
518+
519+
it.effect("deletes the revert branch when GitLab cannot revert cleanly", () =>
520+
Effect.gen(function* () {
521+
mockedExecute.mockImplementation(({ args, cwd }) =>
522+
args[1]?.endsWith("/revert")
523+
? Effect.fail(
524+
new GitLabCli.GitLabCliCommandError({
525+
operation: "execute",
526+
command: "glab",
527+
cwd,
528+
cause: new Error("Merge request revert failed"),
529+
}),
530+
)
531+
: Effect.succeed(
532+
output(mergeRequestJson({ merge_commit_sha: null, squash_commit_sha: "abc12345ff" })),
533+
),
534+
);
535+
const cli = yield* GitLabPullRequestCli.GitLabPullRequestCli;
536+
537+
const result = yield* Effect.result(
538+
cli.runMergeRequestAction({
539+
cwd: "/w",
540+
repository: "acme/web",
541+
number: 7,
542+
action: "revert",
543+
}),
544+
);
545+
546+
expect(result).toMatchObject({ _tag: "Failure", failure: { _tag: "GitLabCliCommandError" } });
547+
expect(mockedExecute.mock.calls.map(([input]) => input.args.slice(1, 4))).toEqual([
548+
["projects/acme%2Fweb/merge_requests/7"],
549+
["projects/acme%2Fweb/repository/branches", "--method", "POST"],
550+
["projects/acme%2Fweb/repository/commits/abc12345ff/revert", "--method", "POST"],
551+
["projects/acme%2Fweb/repository/branches/revert-abc12345", "--method", "DELETE"],
552+
]);
553+
}),
554+
);
555+
469556
it.effect("sends a comment body over stdin, never in argv", () =>
470557
Effect.gen(function* () {
471558
mockedExecute.mockReturnValueOnce(Effect.succeed(output("")));

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

Lines changed: 83 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,7 @@ import {
3434
decodeCommitDiffRefsJson,
3535
decodeCommitsJson,
3636
decodeDiffRefsJson,
37+
decodeRevertTargetJson,
3738
decodeDiscussionsJson,
3839
decodeMergeRequestDetailJson,
3940
decodeMergeRequestDiffsJson,
@@ -116,6 +117,23 @@ export class GitLabDiffRefsUnavailableError extends Schema.TaggedError<GitLabDif
116117
}
117118
}
118119

120+
export class GitLabRevertUnavailableError extends Schema.TaggedError<GitLabRevertUnavailableError>()(
121+
"GitLabRevertUnavailableError",
122+
{
123+
command: Schema.Literal("glab"),
124+
cwd: Schema.String,
125+
number: Schema.Int,
126+
},
127+
) {
128+
get detail(): string {
129+
return "This merge request landed as several commits, so there is no single commit to revert.";
130+
}
131+
132+
override get message(): string {
133+
return `GitLab CLI failed in runMergeRequestAction: ${this.detail}`;
134+
}
135+
}
136+
119137
export class GitLabDiffCursorError extends Schema.TaggedError<GitLabDiffCursorError>()(
120138
"GitLabDiffCursorError",
121139
{
@@ -193,6 +211,7 @@ export type GitLabPullRequestCliError =
193211
| GitLabDiffCommitParentUnavailableError
194212
| GitLabDiffFileContentsUnavailableError
195213
| GitLabDiffRefsUnavailableError
214+
| GitLabRevertUnavailableError
196215
| GitLabViewerUnavailableError;
197216

198217
/** GitLab's `per_page` limit. */
@@ -596,6 +615,7 @@ function actionArgs(
596615
case "reopen":
597616
return ["reopen"];
598617
case "revert":
618+
return [];
599619
case "approve-workflows":
600620
case "delete-branch":
601621
throw new Error(`GitLab merge request action ${action} is unsupported`);
@@ -908,6 +928,68 @@ export const make = Effect.gen(function* () {
908928
}),
909929
);
910930

931+
/** What GitLab's own Revert button does: revert onto a new branch and open a merge request. */
932+
const revertMergeRequest = Effect.fn("GitLabPullRequestCli.revertMergeRequest")(
933+
function* (input: {
934+
readonly cwd: string;
935+
readonly host?: string | undefined;
936+
readonly repository: string;
937+
readonly number: number;
938+
}) {
939+
const project = `projects/${projectPath(input.repository)}`;
940+
const write = (path: string, body: object) =>
941+
api({
942+
cwd: input.cwd,
943+
host: input.host,
944+
path: `${project}/${path}`,
945+
method: "POST",
946+
stdin: JSON.stringify(body),
947+
});
948+
const raw = yield* api({
949+
cwd: input.cwd,
950+
host: input.host,
951+
path: `${project}/merge_requests/${input.number}`,
952+
});
953+
const decoded = decodeRevertTargetJson(raw.stdout.trim());
954+
if (!Result.isSuccess(decoded)) {
955+
return yield* new GitLabMergeRequestReadError({
956+
command: "glab",
957+
cwd: input.cwd,
958+
operation: "runMergeRequestAction",
959+
cause: decoded.failure,
960+
});
961+
}
962+
const target = decoded.success;
963+
if (target.commitSha === null) {
964+
return yield* new GitLabRevertUnavailableError({
965+
command: "glab",
966+
cwd: input.cwd,
967+
number: input.number,
968+
});
969+
}
970+
const branch = `revert-${target.commitSha.slice(0, 8)}`;
971+
yield* write("repository/branches", { branch, ref: target.targetBranch });
972+
yield* write(`repository/commits/${target.commitSha}/revert`, { branch }).pipe(
973+
// A revert that conflicts leaves nothing worth keeping on the new branch.
974+
Effect.tapError(() =>
975+
api({
976+
cwd: input.cwd,
977+
host: input.host,
978+
path: `${project}/repository/branches/${encodeURIComponent(branch)}`,
979+
method: "DELETE",
980+
}).pipe(Effect.ignore),
981+
),
982+
);
983+
yield* write("merge_requests", {
984+
source_branch: branch,
985+
target_branch: target.targetBranch,
986+
title: `Revert "${target.title}"`,
987+
description: `This reverts merge request !${input.number}`,
988+
remove_source_branch: true,
989+
});
990+
},
991+
);
992+
911993
const getDiffRefs = (input: {
912994
readonly cwd: string;
913995
readonly host?: string | undefined;
@@ -1658,6 +1740,7 @@ export const make = Effect.gen(function* () {
16581740
method: "POST",
16591741
}).pipe(Effect.asVoid);
16601742
}
1743+
if (input.action === "revert") return yield* revertMergeRequest(input);
16611744
const executeMr = (subcommand: string, ...flags: ReadonlyArray<string>) =>
16621745
gitlab.execute({
16631746
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
@@ -132,6 +132,7 @@ describe("gitLabViewerPermissions", () => {
132132
"update-branch",
133133
"enable-auto-merge",
134134
"disable-auto-merge",
135+
"revert",
135136
],
136137
comment: true,
137138
resolve: true,

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

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -52,12 +52,14 @@ const UNAVAILABLE_REQUIREMENT = {
5252
* The actions `user.can_merge` answers for. Rebasing writes to the source branch rather than to
5353
* the target, so it is not literally the same permission — but GitLab reports nothing narrower,
5454
* and someone it will not let land this change has no business rewriting its branch either.
55+
* Reverting pushes a branch to the target project, which the same permission covers.
5556
*/
5657
const MERGE_ACTIONS: ReadonlySet<string> = new Set([
5758
"merge",
5859
"update-branch",
5960
"enable-auto-merge",
6061
"disable-auto-merge",
62+
"revert",
6163
]);
6264

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

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

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -135,6 +135,13 @@ const RawDiffRefsSchema = Schema.Struct({
135135
),
136136
});
137137

138+
const RawRevertTargetSchema = Schema.Struct({
139+
title: Schema.String,
140+
target_branch: Schema.String,
141+
merge_commit_sha: Schema.optional(Schema.NullOr(Schema.String)),
142+
squash_commit_sha: Schema.optional(Schema.NullOr(Schema.String)),
143+
});
144+
138145
const RawCommitSchema = Schema.Struct({
139146
id: TrimmedNonEmptyString,
140147
title: Schema.optional(Schema.NullOr(Schema.String)),
@@ -366,6 +373,7 @@ const decodeMergeRequestChanges = decodeJsonResult(
366373
const decodeDiffEntry = Schema.decodeUnknownExit(RawDiffSchema);
367374
const decodeDiscussionEntry = Schema.decodeUnknownExit(RawDiscussionSchema);
368375
const decodeDiffRefs = decodeJsonResult(RawDiffRefsSchema);
376+
const decodeRevertTarget = decodeJsonResult(RawRevertTargetSchema);
369377
const decodeViewer = decodeJsonResult(RawViewerSchema);
370378
const decodeProjectMergeSettings = decodeJsonResult(RawProjectMergeSettingsSchema);
371379

@@ -582,6 +590,26 @@ export function decodeDiffRefsJson(
582590
);
583591
}
584592

593+
export interface GitLabRevertTarget {
594+
readonly title: string;
595+
readonly targetBranch: string;
596+
/** Null for a fast-forward merge without squash, which landed as several commits. */
597+
readonly commitSha: string | null;
598+
}
599+
600+
export function decodeRevertTargetJson(
601+
raw: string,
602+
): Result.Result<GitLabRevertTarget, DecodeFailure> {
603+
const decoded = decodeRevertTarget(raw);
604+
if (!Result.isSuccess(decoded)) return Result.fail(decoded.failure);
605+
const mr = decoded.success;
606+
return Result.succeed({
607+
title: mr.title,
608+
targetBranch: mr.target_branch,
609+
commitSha: trimmed(mr.merge_commit_sha) ?? trimmed(mr.squash_commit_sha),
610+
});
611+
}
612+
585613
export function decodeNotesJson(
586614
raw: string,
587615
): Result.Result<

‎packages/source-control-gitlab/src/shared/definition.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -56,6 +56,7 @@ export const definition = defineSourceControl({
5656
"update-branch",
5757
"enable-auto-merge",
5858
"disable-auto-merge",
59+
"revert",
5960
] as const),
6061
checkoutCommand: ({ number }) => `glab mr checkout ${number}`,
6162
changeRequestCloseCommand: /\bglab\s+mr\s+(?:merge|close)\b/u,

0 commit comments

Comments
 (0)