Skip to content
TypeScript

fix(server): load merge request diffs on older GitLab (#15886)

Arav Jaind426166dfd71
diff --git a/packages/source-control-gitlab/src/server/GitLabPullRequestCli.legacy.test.ts b/packages/source-control-gitlab/src/server/GitLabPullRequestCli.legacy.test.ts
new file mode 100644
index 00000000000..2606642b780
--- /dev/null
+++ b/packages/source-control-gitlab/src/server/GitLabPullRequestCli.legacy.test.ts
@@ -0,0 +1,205 @@
+import { afterEach, assert, expect, it, vi } from "@effect/vitest";
+import * as Effect from "effect/Effect";
+import * as Layer from "effect/Layer";
+import { ChildProcessSpawner } from "effect/process";
+import { VcsProcessExitError } from "@t3tools/contracts";
+
+import type * as SourceControlHost from "@t3tools/source-control-core/server/SourceControlHost";
+import * as TestSourceControlHost from "@t3tools/source-control-testing/TestSourceControlHost";
+import * as GitLabCli from "./GitLabCli.ts";
+import * as GitLabPullRequestCli from "./GitLabPullRequestCli.ts";
+
+const run = vi.fn<SourceControlHost.SourceControlHost["Service"]["process"]["run"]>();
+const layer = it.layer(
+ GitLabPullRequestCli.layer.pipe(
+ Layer.provide(GitLabCli.layer),
+ Layer.provide(TestSourceControlHost.layer({ process: { run } })),
+ ),
+);
+const input = { cwd: "/repo", repository: "acme/nested/web", number: 7 };
+const file = {
+ old_path: "src/old.ts",
+ new_path: "src/new.ts",
+ renamed_file: true,
+ new_file: false,
+ deleted_file: false,
+ a_mode: "100644",
+ b_mode: "100644",
+ diff: "@@ -1 +1 @@\n-before\n+after\n",
+};
+/** Supplies JSON at the process boundary while retaining the real CLI adapter and decoder. */
+function output(body: unknown, stdoutTruncated = false) {
+ return Effect.succeed({
+ exitCode: ChildProcessSpawner.ExitCode(0),
+ stdout: JSON.stringify(body),
+ stderr: "",
+ stdoutTruncated,
+ stderrTruncated: false,
+ });
+}
+/** Supplies the failure classification produced by VcsProcess for an unsuccessful glab call. */
+function failure(failureKind: "not-found" | "authentication" | "rate-limited" | "command-failed") {
+ return Effect.fail(
+ new VcsProcessExitError({
+ operation: "GitLabCli.execute",
+ command: "glab",
+ cwd: input.cwd,
+ exitCode: 1,
+ detail: "GitLab HTTP failure",
+ failureKind,
+ }),
+ );
+}
+afterEach(() => run.mockReset());
+
+layer("legacy GitLab diff requests through GitLabCli", (it) => {
+ it.effect.each([0, 1, 100, 247])("returns %s legacy changes as one terminal slice", (count) =>
+ Effect.gen(function* () {
+ run.mockReturnValueOnce(failure("not-found"));
+ run.mockReturnValueOnce(
+ output({
+ changes: Array.from({ length: count }, () => file),
+ overflow: false,
+ changes_count: String(count),
+ }),
+ );
+ const cli = yield* GitLabPullRequestCli.GitLabPullRequestCli;
+ const result = yield* cli.getMergeRequestDiff(input);
+ expect(result.nextCursor).toBeNull();
+ expect(result.truncated).toBe(false);
+ expect(result.patch.match(/^diff --git /gm)?.length ?? 0).toBe(count);
+ if (count > 0) {
+ expect(result.patch).toContain("rename from src/old.ts\nrename to src/new.ts");
+ expect(result.patch).toContain("@@ -1 +1 @@\n-before\n+after\n");
+ expect(result.patch.endsWith("\n")).toBe(true);
+ }
+ expect(run.mock.calls.map(([call]) => call.args)).toEqual([
+ ["api", "projects/acme%2Fnested%2Fweb/merge_requests/7/diffs?per_page=100&page=1"],
+ ["api", "projects/acme%2Fnested%2Fweb/merge_requests/7/changes?access_raw_diffs=true"],
+ ]);
+ expect(run.mock.calls[1]?.[0]).toMatchObject({
+ cwd: "/repo",
+ maxOutputBytes: 8 * 1024 * 1024,
+ timeoutMs: 60_000,
+ });
+ }),
+ );
+ it.effect.each([false, true])("accepts an unavailable legacy count (overflow: %s)", (overflow) =>
+ Effect.gen(function* () {
+ run.mockReturnValueOnce(failure("not-found"));
+ run.mockReturnValueOnce(output({ changes: [file], changes_count: null, overflow }));
+ const cli = yield* GitLabPullRequestCli.GitLabPullRequestCli;
+ const result = yield* cli.getMergeRequestDiff(input);
+ expect(result.truncated).toBe(overflow);
+ expect(result.nextCursor).toBeNull();
+ expect(result.patch).toContain("@@ -1 +1 @@\n-before\n+after\n");
+ }),
+ );
+ it.effect.each([{ overflow: true }, { changes_count: "247+" }])(
+ "marks legacy limits %j truncated",
+ (metadata) =>
+ Effect.gen(function* () {
+ run.mockReturnValueOnce(failure("not-found"));
+ run.mockReturnValueOnce(output({ changes: [file], ...metadata }));
+ const cli = yield* GitLabPullRequestCli.GitLabPullRequestCli;
+ expect(yield* cli.getMergeRequestDiff(input)).toMatchObject({
+ truncated: true,
+ nextCursor: null,
+ });
+ }),
+ );
+ it.effect.each([{}, { changes: null }, { changes: {} }, [file]])(
+ "rejects malformed legacy wrapper %j",
+ (body) =>
+ Effect.gen(function* () {
+ run.mockReturnValueOnce(failure("not-found"));
+ run.mockReturnValueOnce(output(body));
+ const cli = yield* GitLabPullRequestCli.GitLabPullRequestCli;
+ const error = yield* cli.getMergeRequestDiff(input).pipe(Effect.flip);
+ assert.equal(error._tag, "GitLabMergeRequestReadError");
+ }),
+ );
+ it.effect.each([false, true])("marks skipped file entries truncated (legacy: %s)", (legacy) =>
+ Effect.gen(function* () {
+ const entries = [file, { new_path: "missing-old-path.ts" }];
+ if (legacy) run.mockReturnValueOnce(failure("not-found"));
+ run.mockReturnValueOnce(output(legacy ? { changes: entries } : entries));
+ const cli = yield* GitLabPullRequestCli.GitLabPullRequestCli;
+ const result = yield* cli.getMergeRequestDiff(input);
+ expect(result.truncated).toBe(true);
+ expect(result.nextCursor).toBeNull();
+ expect(result.patch.match(/^diff --git /gm)).toHaveLength(1);
+ expect(result.patch).toContain("@@ -1 +1 @@\n-before\n+after\n");
+ }),
+ );
+ it.effect("rejects a byte-truncated legacy response", () =>
+ Effect.gen(function* () {
+ run.mockReturnValueOnce(failure("not-found"));
+ run.mockReturnValueOnce(output({ changes: [file] }, true));
+ const cli = yield* GitLabPullRequestCli.GitLabPullRequestCli;
+ expect((yield* cli.getMergeRequestDiff(input).pipe(Effect.flip))._tag).toBe(
+ "GitLabMergeRequestReadError",
+ );
+ }),
+ );
+ it.effect.each(["authentication", "rate-limited", "command-failed"] as const)(
+ "does not fall back on %s",
+ (kind) =>
+ Effect.gen(function* () {
+ run.mockReturnValueOnce(failure(kind));
+ const cli = yield* GitLabPullRequestCli.GitLabPullRequestCli;
+ yield* cli.getMergeRequestDiff(input).pipe(Effect.flip);
+ expect(run).toHaveBeenCalledTimes(1);
+ }),
+ );
+ it.effect("does not fall back for a missing commit or later MR page", () =>
+ Effect.gen(function* () {
+ const cli = yield* GitLabPullRequestCli.GitLabPullRequestCli;
+ for (const target of [
+ { ...input, commit: "abc1234" },
+ { ...input, cursor: "2" },
+ ]) {
+ run.mockReturnValueOnce(failure("not-found"));
+ yield* cli.getMergeRequestDiff(target).pipe(Effect.flip);
+ }
+ expect(run).toHaveBeenCalledTimes(2);
+ }),
+ );
+ it.effect("propagates failure of the legacy endpoint", () =>
+ Effect.gen(function* () {
+ run.mockReturnValueOnce(failure("not-found"));
+ run.mockReturnValueOnce(failure("not-found"));
+ const cli = yield* GitLabPullRequestCli.GitLabPullRequestCli;
+ expect((yield* cli.getMergeRequestDiff(input).pipe(Effect.flip))._tag).toBe(
+ "GitLabCliCommandError",
+ );
+ expect(run).toHaveBeenCalledTimes(2);
+ }),
+ );
+ it.effect("does not fall back on an unreadable successful modern response", () =>
+ Effect.gen(function* () {
+ run.mockReturnValueOnce(output({ changes: [file] }));
+ const cli = yield* GitLabPullRequestCli.GitLabPullRequestCli;
+ expect((yield* cli.getMergeRequestDiff(input).pipe(Effect.flip))._tag).toBe(
+ "GitLabMergeRequestReadError",
+ );
+ expect(run).toHaveBeenCalledTimes(1);
+ }),
+ );
+ it.effect("keeps modern pagination without requesting legacy changes", () =>
+ Effect.gen(function* () {
+ run.mockReturnValueOnce(output(Array.from({ length: 100 }, () => file)));
+ run.mockReturnValueOnce(output([file]));
+ const cli = yield* GitLabPullRequestCli.GitLabPullRequestCli;
+ const first = yield* cli.getMergeRequestDiff(input);
+ expect(first.nextCursor).toBe("2");
+ expect(
+ (yield* cli.getMergeRequestDiff({ ...input, cursor: first.nextCursor! })).nextCursor,
+ ).toBeNull();
+ expect(run).toHaveBeenCalledTimes(2);
+ expect(run.mock.calls[1]?.[0].args).toContain(
+ "projects/acme%2Fnested%2Fweb/merge_requests/7/diffs?per_page=100&page=2",
+ );
+ }),
+ );
+});
diff --git a/packages/source-control-gitlab/src/server/GitLabPullRequestCli.ts b/packages/source-control-gitlab/src/server/GitLabPullRequestCli.ts
index dd5debf2c99..e812b99f3b7 100644
--- a/packages/source-control-gitlab/src/server/GitLabPullRequestCli.ts
+++ b/packages/source-control-gitlab/src/server/GitLabPullRequestCli.ts
@@ -3,6 +3,7 @@ import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Result from "effect/Result";
import * as Schema from "effect/Schema";
+import { VcsProcessExitError } from "@t3tools/contracts";
import type {
PullRequestAction,
PullRequestComment,
@@ -30,6 +31,7 @@ import {
decodeDiscussionsJson,
decodeMergeRequestDetailJson,
decodeMergeRequestDiffsJson,
+ decodeMergeRequestChangesJson,
decodeMergeRequestListJson,
decodeNotesJson,
decodeOwnAwardIdJson,
@@ -182,6 +184,7 @@ const COMMIT_PAGE_SIZE = 100;
const CONVERSATION_PAGES = 10;
const DIFF_MAX_OUTPUT_BYTES = 8 * 1024 * 1024;
const DIFF_TIMEOUT_MS = 60_000;
+const isVcsProcessExitError = Schema.is(VcsProcessExitError);
const DIFF_FILE_MAX_OUTPUT_BYTES = 1024 * 1024;
export interface GitLabMergeRequestListBatch {
@@ -620,7 +623,27 @@ export const make = Effect.gen(function* () {
maxOutputBytes: DIFF_MAX_OUTPUT_BYTES,
timeoutMs: DIFF_TIMEOUT_MS,
}).pipe(
- Effect.flatMap((result) => {
+ Effect.map((result) => ({ result, legacy: false })),
+ Effect.catchTags({
+ GitLabCliCommandError: (error) => {
+ if (
+ input.commit !== undefined ||
+ input.page !== 1 ||
+ !isVcsProcessExitError(error.cause) ||
+ error.cause.failureKind !== "not-found"
+ ) {
+ return Effect.fail(error);
+ }
+ // GitLab before 15.7 has no /diffs endpoint. /changes returns one complete slice.
+ return api({
+ cwd: input.cwd,
+ path: `projects/${projectPath(input.repository)}/merge_requests/${input.number}/changes?access_raw_diffs=true`,
+ maxOutputBytes: DIFF_MAX_OUTPUT_BYTES,
+ timeoutMs: DIFF_TIMEOUT_MS,
+ }).pipe(Effect.map((result) => ({ result, legacy: true })));
+ },
+ }),
+ Effect.flatMap(({ result, legacy }) => {
// A byte-truncated response is a JSON prefix, so this page cannot be read at all.
// Answering with no cursor would call the diff whole while silently dropping this page
// and every one after it, so the read fails and says which page could not be had.
@@ -636,7 +659,9 @@ export const make = Effect.gen(function* () {
}),
);
}
- const decoded = decodeMergeRequestDiffsJson(result.stdout.trim());
+ const decoded = (legacy ? decodeMergeRequestChangesJson : decodeMergeRequestDiffsJson)(
+ result.stdout.trim(),
+ );
if (!Result.isSuccess(decoded)) {
return Effect.fail(
new GitLabMergeRequestReadError({
@@ -650,7 +675,7 @@ export const make = Effect.gen(function* () {
const patch = decoded.success.patch;
// Counted before decoding, so a page whose files all failed to decode still moves on
// rather than pointing the reader back at the page it just read.
- const morePages = decoded.success.rawCount >= MAX_PAGE_SIZE;
+ const morePages = !legacy && decoded.success.rawCount >= MAX_PAGE_SIZE;
return Effect.succeed({
// The slice ends on a newline, so a file GitLab gave a header and no hunks for does
// not run into the first line of the next slice.
diff --git a/packages/source-control-gitlab/src/server/gitLabMergeRequestJson.ts b/packages/source-control-gitlab/src/server/gitLabMergeRequestJson.ts
index 72eaa7f1194..249283b61f1 100644
--- a/packages/source-control-gitlab/src/server/gitLabMergeRequestJson.ts
+++ b/packages/source-control-gitlab/src/server/gitLabMergeRequestJson.ts
@@ -356,6 +356,13 @@ const decodeNoteEntry = Schema.decodeUnknownExit(RawNoteSchema);
const decodeUserEntry = Schema.decodeUnknownExit(RawUserSchema);
const decodeCommitEntry = Schema.decodeUnknownExit(RawCommitSchema);
const decodeCommit = decodeJsonResult(RawCommitSchema);
+const decodeMergeRequestChanges = decodeJsonResult(
+ Schema.Struct({
+ changes: Schema.Array(Schema.Unknown),
+ overflow: Schema.optional(Schema.Boolean),
+ changes_count: Schema.optional(Schema.NullOr(Schema.String)),
+ }),
+);
const decodeDiffEntry = Schema.decodeUnknownExit(RawDiffSchema);
const decodeDiscussionEntry = Schema.decodeUnknownExit(RawDiscussionSchema);
const decodeDiffRefs = decodeJsonResult(RawDiffRefsSchema);
@@ -613,11 +620,35 @@ export function decodeMergeRequestDiffsJson(
if (!Result.isSuccess(decoded)) {
return Result.fail(decoded.failure);
}
+ return Result.succeed(mergeRequestPatch(decoded.success));
+}
+
+/** Older GitLab instances return all files in a non-paginated merge request wrapper. */
+export function decodeMergeRequestChangesJson(
+ raw: string,
+): Result.Result<GitLabMergeRequestPatch, DecodeFailure> {
+ const decoded = decodeMergeRequestChanges(raw);
+ if (!Result.isSuccess(decoded)) return Result.fail(decoded.failure);
+ const patch = mergeRequestPatch(decoded.success.changes);
+ return Result.succeed({
+ ...patch,
+ truncated:
+ patch.truncated ||
+ decoded.success.overflow === true ||
+ decoded.success.changes_count?.endsWith("+") === true,
+ });
+}
+
+/** Builds file patches, retaining raw counts and recording files whose contents are missing. */
+function mergeRequestPatch(entries: ReadonlyArray<unknown>): GitLabMergeRequestPatch {
const sections: string[] = [];
let truncated = false;
- for (const entry of decoded.success) {
+ for (const entry of entries) {
const file = decodeDiffEntry(entry);
- if (Exit.isFailure(file)) continue;
+ if (Exit.isFailure(file)) {
+ truncated = true;
+ continue;
+ }
const value = file.value;
const hunks = value.diff ?? "";
if (hunks.length === 0) {
@@ -639,11 +670,11 @@ export function decodeMergeRequestDiffsJson(
].join("\n");
sections.push(hunks.length === 0 ? header : `${header}\n${hunks.replace(/\n?$/, "\n")}`);
}
- return Result.succeed({
+ return {
patch: sections.join("\n"),
truncated,
- rawCount: decoded.success.length,
- });
+ rawCount: entries.length,
+ };
}
const GITLAB_AWARD_BY_CONTENT: Readonly<Record<PullRequestReactionContent, string>> = {