Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -1129,6 +1129,90 @@ layer("GitLabPullRequestCli.layer", (it) => {
}),
);

it.effect("counts a file GitLab withheld as too large and offers to read it alone", () =>
Effect.gen(function* () {
mockedExecute
.mockReturnValueOnce(
Effect.succeed(
output(
JSON.stringify([
{ old_path: "src/a.ts", new_path: "src/a.ts", diff: "@@ -1 +1 @@\n-a\n+b\n" },
{ old_path: "src/huge.txt", new_path: "src/huge.txt", diff: "", too_large: true },
]),
),
),
)
.mockReturnValueOnce(
Effect.succeed(
output(
JSON.stringify({
data: {
project: {
mergeRequest: {
diffStatsSummary: { fileCount: 2 },
diffStats: [
{ path: "src/a.ts", additions: 1, deletions: 1 },
{ path: "src/huge.txt", additions: 20000, deletions: 0 },
],
},
},
},
}),
),
),
);
const cli = yield* GitLabPullRequestCli.GitLabPullRequestCli;

const diff = yield* cli.getMergeRequestDiff({ cwd: "/w", repository: "acme/web", number: 7 });

expect(diff.omittedFileStats).toEqual([
{ path: "src/huge.txt", additions: 20000, deletions: 0 },
]);
assert.isTrue(diff.withheldFilesReadable);
}),
);

it.effect("reads one withheld file's section from the merge request's raw diff", () =>
Effect.gen(function* () {
mockedExecute.mockReturnValueOnce(
Effect.succeed(
output(
[
"diff --git a/src/a.ts b/src/a.ts",
"--- a/src/a.ts",
"+++ b/src/a.ts",
"@@ -1 +1 @@",
"-a",
"+b",
"diff --git a/src/huge.txt b/src/huge.txt",
"new file mode 100644",
"--- /dev/null",
"+++ b/src/huge.txt",
"@@ -0,0 +1,2 @@",
"+one",
"+two",
"",
].join("\n"),
),
),
);
const cli = yield* GitLabPullRequestCli.GitLabPullRequestCli;

const diff = yield* cli.getMergeRequestDiff({
cwd: "/w",
repository: "acme/web",
number: 7,
path: "src/huge.txt",
});

expect(argsOfCall(0)[1]).toBe("projects/acme%2Fweb/merge_requests/7/raw_diffs");
assert.strictEqual(
diff.patch,
"diff --git a/src/huge.txt b/src/huge.txt\nnew file mode 100644\n--- /dev/null\n+++ b/src/huge.txt\n@@ -0,0 +1,2 @@\n+one\n+two\n",
);
}),
);

it.effect(
"pages a merge request diff 30 files at a time, which GitLab 15.7 to 17.10 accept",
() =>
Expand Down
122 changes: 108 additions & 14 deletions packages/source-control-gitlab/src/server/GitLabPullRequestCli.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
import { removeAgentCredits } from "@t3tools/source-control-core/server/mergeMessage";
import { isCommitSha } from "@t3tools/source-control-core/server/pullRequestUtils";
import {
diffFileSection,
truncateLongDiffLines,
} from "@t3tools/source-control-core/server/diffFileRevisions";
import * as Context from "effect/Context";
import * as Digest from "effect/crypto/Digest";
import * as DateTime from "effect/DateTime";
Expand All @@ -25,6 +29,7 @@ import type {
PullRequestListState,
PullRequestMergeCapabilities,
PullRequestMergeMethod,
PullRequestOmittedFileStat,
PullRequestReaction,
PullRequestReactionContent,
PullRequestReviewCommentDraft,
Expand Down Expand Up @@ -344,6 +349,9 @@ const diffPageSize = (commit: string | undefined) =>
const CONVERSATION_PAGES = 10;
const DIFF_MAX_OUTPUT_BYTES = 8 * 1024 * 1024;
const DIFF_TIMEOUT_MS = 60_000;
const WITHHELD_FILE_DIFF_MAX_OUTPUT_BYTES = 32 * 1024 * 1024;
// Withheld files are often generated or minified, where one line can be megabytes.
const WITHHELD_FILE_MAX_LINE_LENGTH = 1_000;
const isVcsProcessExitError = Schema.is(VcsProcessExitError);
const DIFF_FILE_MAX_OUTPUT_BYTES = 1024 * 1024;
// REST list rows carry full descriptions, so a page can pass the 1 MB default output cap.
Expand All @@ -370,6 +378,8 @@ export interface GitLabMergeRequestDiffSlice {
readonly patch: string;
readonly truncated: boolean;
readonly nextCursor: string | null;
readonly omittedFileStats?: ReadonlyArray<PullRequestOmittedFileStat>;
readonly withheldFilesReadable?: boolean;
}

export class GitLabPullRequestCli extends Context.Service<
Expand Down Expand Up @@ -482,6 +492,8 @@ export class GitLabPullRequestCli extends Context.Service<
readonly number: number;
readonly cursor?: string | undefined;
readonly commit?: string | undefined;
/** Reads one file a page withheld as too large; ignores `cursor`. */
readonly path?: string | undefined;
}) => Effect.Effect<GitLabMergeRequestDiffSlice, GitLabPullRequestCliError>;

readonly getMergeRequestDiffFileContents: (input: {
Expand Down Expand Up @@ -1174,7 +1186,13 @@ export const make = Effect.gen(function* () {
readonly number: number;
readonly page: number;
readonly commit?: string | undefined;
}): Effect.Effect<GitLabMergeRequestDiffSlice, GitLabPullRequestCliError> =>
}): Effect.Effect<
GitLabMergeRequestDiffSlice & {
readonly withheldPaths: ReadonlyArray<string>;
readonly legacy: boolean;
},
GitLabPullRequestCliError
> =>
api({
cwd: input.cwd,
host: input.host,
Expand Down Expand Up @@ -1246,6 +1264,8 @@ export const make = Effect.gen(function* () {
patch: patch.length === 0 ? patch : patch.replace(/\n?$/, "\n"),
truncated: decoded.success.truncated,
nextCursor: morePages ? String(input.page + 1) : null,
withheldPaths: decoded.success.withheldPaths,
legacy,
});
}),
);
Expand Down Expand Up @@ -1847,6 +1867,67 @@ export const make = Effect.gen(function* () {
): Effect.Effect<A, GitLabPullRequestCliError> =>
read.pipe(Effect.catchIf(isOptionalReadFailure, () => Effect.succeed(fallback)));

const mergeRequestFileStats = (input: {
readonly cwd: string;
readonly host?: string | undefined;
readonly repository: string;
readonly number: number;
}) =>
graphqlRead({
cwd: input.cwd,
host: input.host,
operation: "getMergeRequestFileStats",
query: MERGE_REQUEST_FILE_STATS_GRAPHQL_QUERY,
variables: { fullPath: input.repository, iid: String(input.number) },
decode: decodeMergeRequestFileStatsJson,
});

// GitLab has no per-file diff, so a withheld file is cut from the whole raw diff here and
// only its section reaches the client. `/raw_diffs` needs GitLab 17.9 or newer.
const withheldFileDiff = (input: {
readonly cwd: string;
readonly host?: string | undefined;
readonly repository: string;
readonly number: number;
readonly commit?: string | undefined;
readonly path: string;
}): Effect.Effect<GitLabMergeRequestDiffSlice, GitLabPullRequestCliError> => {
const readError = (message: string) =>
new GitLabMergeRequestReadError({
command: "glab",
cwd: input.cwd,
operation: "getMergeRequestDiff",
cause: new Error(message),
});
if (input.commit !== undefined) {
return Effect.fail(readError("A commit's withheld files cannot be read one at a time."));
}
return api({
cwd: input.cwd,
host: input.host,
path: `projects/${projectPath(input.repository)}/merge_requests/${input.number}/raw_diffs`,
maxOutputBytes: WITHHELD_FILE_DIFF_MAX_OUTPUT_BYTES,
timeoutMs: DIFF_TIMEOUT_MS,
}).pipe(
Effect.flatMap((result) => {
const section = result.stdoutTruncated ? null : diffFileSection(result.stdout, input.path);
return section === null
? Effect.fail(
readError(
result.stdoutTruncated
? `The diff for ${input.path} is too large to load.`
: `GitLab's diff does not include ${input.path}.`,
),
)
: Effect.succeed({
patch: truncateLongDiffLines(section, WITHHELD_FILE_MAX_LINE_LENGTH),
truncated: false,
nextCursor: null,
});
}),
);
};

const graphqlMutation = (input: {
readonly cwd: string;
readonly host?: string | undefined;
Expand Down Expand Up @@ -2305,15 +2386,8 @@ export const make = Effect.gen(function* () {

listMergeRequestStats,

getMergeRequestFileStats: Effect.fn("GitLabPullRequestCli.getMergeRequestFileStats")((input) =>
graphqlRead({
cwd: input.cwd,
host: input.host,
operation: "getMergeRequestFileStats",
query: MERGE_REQUEST_FILE_STATS_GRAPHQL_QUERY,
variables: { fullPath: input.repository, iid: String(input.number) },
decode: decodeMergeRequestFileStatsJson,
}),
getMergeRequestFileStats: Effect.fn("GitLabPullRequestCli.getMergeRequestFileStats")(
mergeRequestFileStats,
),

getMergeRequestWatchFingerprint: Effect.fn(
Expand Down Expand Up @@ -2426,13 +2500,33 @@ export const make = Effect.gen(function* () {
number: input.number,
...(input.commit === undefined ? {} : { commit: input.commit }),
};
if (input.cursor === undefined) {
return yield* diffPage({ ...target, page: 1 });
if (input.path !== undefined) {
return yield* withheldFileDiff({ ...target, path: input.path });
}
const page = diffCursorPage(input.cursor);
const page = input.cursor === undefined ? 1 : diffCursorPage(input.cursor);
if (page === null)
return yield* new GitLabDiffCursorError({ command: "glab", cwd: input.cwd });
return yield* diffPage({ ...target, page });
const { withheldPaths, legacy, ...slice } = yield* diffPage({ ...target, page });
// A commit's diff has no per-file counts or raw diff to read a withheld file from.
if (input.commit !== undefined) return slice;
const readable = page === 1 && !legacy ? { withheldFilesReadable: true } : {};
if (withheldPaths.length === 0) return { ...slice, ...readable };
const stats = yield* orWhenUnanswered(mergeRequestFileStats(target), {
files: [],
truncated: true,
});
const statsByPath = new Map(stats.files.map((file) => [file.path, file]));
const omittedFileStats = withheldPaths.flatMap((path) => {
const stat = statsByPath.get(path);
return stat === undefined
? []
: [{ path, additions: stat.additions, deletions: stat.deletions }];
});
return {
...slice,
...readable,
...(omittedFileStats.length === 0 ? {} : { omittedFileStats }),
};
}),

getMergeRequestDiffFileContents: Effect.fn(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@ const CAPABILITIES: PullRequestCapabilities = {
reviewers: { request: true, listCandidates: true, searchCandidates: true },
labels: true,
edit: { changeRequest: true, comment: true, maintainerEdits: true },
withheldFileDiff: true,
};

const UNAVAILABLE_REQUIREMENT = {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -681,6 +681,7 @@ describe("decodeMergeRequestDiffsJson", () => {

expect(result.truncated).toBe(true);
expect(result.patch).toContain("diff --git a/big.bin b/big.bin");
expect(result.withheldPaths).toEqual(["big.bin"]);
});

it("reports how many files GitLab returned, so the caller can page", () => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1014,6 +1014,8 @@ export interface GitLabMergeRequestPatch {
readonly patch: string;
readonly truncated: boolean;
readonly rawCount: number;
/** Files GitLab sent without their diff because they are too large or collapsed. */
readonly withheldPaths: ReadonlyArray<string>;
}

export function decodeMergeRequestDiffsJson(
Expand Down Expand Up @@ -1044,6 +1046,7 @@ export function decodeMergeRequestChangesJson(

function mergeRequestPatch(entries: ReadonlyArray<unknown>): GitLabMergeRequestPatch {
const sections: string[] = [];
const withheldPaths: string[] = [];
let truncated = false;
for (const entry of entries) {
const file = decodeDiffEntry(entry);
Expand All @@ -1053,8 +1056,9 @@ function mergeRequestPatch(entries: ReadonlyArray<unknown>): GitLabMergeRequestP
}
const value = file.value;
const hunks = value.diff ?? "";
if (hunks.length === 0) {
truncated = truncated || value.too_large === true || value.collapsed === true;
if (hunks.length === 0 && (value.too_large === true || value.collapsed === true)) {
truncated = true;
withheldPaths.push(value.new_path);
}
const { from, to } = diffHeaderPaths(value);
const header = [
Expand All @@ -1078,6 +1082,7 @@ function mergeRequestPatch(entries: ReadonlyArray<unknown>): GitLabMergeRequestP
patch: sections.join("\n"),
truncated,
rawCount: entries.length,
withheldPaths,
};
}

Expand Down
Loading