Skip to content

Commit a4cd1ba

Browse files
TonybynMp4claude
andcommitted
fix(gitlab): ranged comments carry GitLab's line codes for changed lines
An added or removed line's line_code holds the other side's diff counter, which GitLab uses to highlight the commented range. Read it from the merge request diff instead of sending 0. Co-Authored-By: Claude Opus 5.5 <[email protected]>
1 parent 6bc6850 commit a4cd1ba

2 files changed

Lines changed: 124 additions & 21 deletions

File tree

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

Lines changed: 24 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -906,6 +906,21 @@ layer("GitLabPullRequestCli.layer", (it) => {
906906
),
907907
),
908908
);
909+
// Line 12 is added after a removed line, so GitLab's old counter there is 11, not 0.
910+
mockedExecute.mockReturnValueOnce(
911+
Effect.succeed(
912+
output(
913+
JSON.stringify([
914+
{
915+
old_path: "src/a.ts",
916+
new_path: "src/b.ts",
917+
renamed_file: true,
918+
diff: "@@ -8,4 +9,4 @@\n a\n b\n-c\n+d\n+e\n f\n-g\n",
919+
},
920+
]),
921+
),
922+
),
923+
);
909924
mockedExecute.mockReturnValue(Effect.succeed(output("{}")));
910925
const cli = yield* GitLabPullRequestCli.GitLabPullRequestCli;
911926

@@ -924,6 +939,7 @@ layer("GitLabPullRequestCli.layer", (it) => {
924939
},
925940
{
926941
path: "src/b.ts",
942+
oldPath: "src/a.ts",
927943
startPosition: { kind: "context", oldLine: 9, newLine: 10, side: "right" },
928944
position: { kind: "added", newLine: 12 },
929945
body: "this block",
@@ -938,8 +954,9 @@ layer("GitLabPullRequestCli.layer", (it) => {
938954
});
939955

940956
expect(argsOfCall(0)[1]).toContain("merge_requests/7");
941-
expect(argsOfCall(1)[1]).toContain("/discussions");
942-
expect(JSON.parse(callAt(1).stdin ?? "")).toEqual({
957+
expect(argsOfCall(1)[1]).toContain("merge_requests/7/diffs");
958+
expect(argsOfCall(2)[1]).toContain("/discussions");
959+
expect(JSON.parse(callAt(2).stdin ?? "")).toEqual({
943960
body: "why remove?",
944961
position: {
945962
base_sha: "base",
@@ -953,16 +970,16 @@ layer("GitLabPullRequestCli.layer", (it) => {
953970
});
954971
// sha1("src/b.ts")
955972
const fileHash = "e55a8d6c5dd26e72538fd71fb7695dd829c8dab5";
956-
expect(JSON.parse(callAt(2).stdin ?? "").position).toMatchObject({
973+
expect(JSON.parse(callAt(3).stdin ?? "").position).toMatchObject({
957974
new_line: 12,
958975
line_range: {
959976
start: { line_code: `${fileHash}_9_10`, type: null, old_line: 9, new_line: 10 },
960-
end: { line_code: `${fileHash}_0_12`, type: "new", new_line: 12 },
977+
end: { line_code: `${fileHash}_11_12`, type: "new", new_line: 12 },
961978
},
962979
});
963-
expect(JSON.parse(callAt(3).stdin ?? "").position).not.toHaveProperty("line_range");
964-
expect(argsOfCall(4)[1]).toContain("/notes");
965-
expect(argsOfCall(5)[1]).toContain("/approve");
980+
expect(JSON.parse(callAt(4).stdin ?? "").position).not.toHaveProperty("line_range");
981+
expect(argsOfCall(5)[1]).toContain("/notes");
982+
expect(argsOfCall(6)[1]).toContain("/approve");
966983
}),
967984
);
968985

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

Lines changed: 100 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ import * as Layer from "effect/Layer";
66
import * as Result from "effect/Result";
77
import * as Schema from "effect/Schema";
88
import { resolvePullRequestAuthorFilter, VcsProcessExitError } from "@t3tools/contracts";
9+
import { quoteGitPatchPath } from "@t3tools/shared/gitPatchPath";
910
import type {
1011
PullRequestAction,
1112
PullRequestActor,
@@ -498,15 +499,65 @@ function gitLabReviewPositionLines(
498499
}
499500
}
500501

502+
function gitLabDiffHeader(oldPath: string, newPath: string): string {
503+
return `diff --git ${quoteGitPatchPath(`a/${oldPath}`)} ${quoteGitPatchPath(`b/${newPath}`)}\n`;
504+
}
505+
506+
/**
507+
* The old and new line counters GitLab's diff parser holds at a changed line. An added line
508+
* keeps the old counter where it stands, and a removed line the new one, so neither side of a
509+
* changed line's `line_code` is known without walking its hunk.
510+
*/
511+
function gitLabLineCounters(
512+
patch: string,
513+
header: string,
514+
position: PullRequestReviewPosition,
515+
): { readonly old: number; readonly new: number } | undefined {
516+
if (position.kind === "context") return { old: position.oldLine, new: position.newLine };
517+
const start = `\n${patch}`.indexOf(`\n${header}`);
518+
if (start === -1) return undefined;
519+
const end = patch.indexOf("\ndiff --git ", start + header.length - 1);
520+
const section = patch.slice(start, end === -1 ? undefined : end);
521+
const firstHunk = section.indexOf("\n@@ ");
522+
if (firstHunk === -1) return undefined;
523+
let oldLine = 0;
524+
let newLine = 0;
525+
for (const line of section.slice(firstHunk + 1).split("\n")) {
526+
const hunk = /^@@ -(\d+)(?:,\d+)? \+(\d+)(?:,\d+)? @@/u.exec(line);
527+
if (hunk) {
528+
oldLine = Number(hunk[1]);
529+
newLine = Number(hunk[2]);
530+
} else if (line.startsWith("+")) {
531+
if (position.kind === "added" && newLine === position.newLine) {
532+
return { old: oldLine, new: newLine };
533+
}
534+
newLine += 1;
535+
} else if (line.startsWith("-")) {
536+
if (position.kind === "deleted" && oldLine === position.oldLine) {
537+
return { old: oldLine, new: newLine };
538+
}
539+
oldLine += 1;
540+
} else if (line.startsWith(" ")) {
541+
oldLine += 1;
542+
newLine += 1;
543+
}
544+
}
545+
return undefined;
546+
}
547+
501548
/**
502-
* One end of a ranged comment. Only `line_code`'s own side is read back: GitLab shows a range
503-
* as "lines +3 to +6" from it. The other side of an added or removed line is a counter only the
504-
* diff knows, so it is sent as 0.
549+
* One end of a ranged comment. GitLab labels the range from `old_line`/`new_line` and `type`,
550+
* the way its own UI sends them (`type` is null on a context line), and finds the lines to
551+
* highlight by `line_code`, which needs both counters from the diff.
505552
*/
506-
function gitLabLineRangeEnd(fileHash: string, position: PullRequestReviewPosition) {
553+
function gitLabLineRangeEnd(
554+
fileHash: string,
555+
position: PullRequestReviewPosition,
556+
counters: { readonly old: number; readonly new: number } | undefined,
557+
) {
507558
const lines = gitLabReviewPositionLines(position);
508-
const oldLine = "old_line" in lines ? lines.old_line : 0;
509-
const newLine = "new_line" in lines ? lines.new_line : 0;
559+
const oldLine = counters?.old ?? ("old_line" in lines ? lines.old_line : 0);
560+
const newLine = counters?.new ?? ("new_line" in lines ? lines.new_line : 0);
510561
return {
511562
line_code: `${fileHash}_${oldLine}_${newLine}`,
512563
type: position.kind === "added" ? "new" : position.kind === "deleted" ? "old" : null,
@@ -519,14 +570,16 @@ const gitLabFileHash = Effect.fnUntraced(function* (path: string) {
519570
return yield* digest.digestHex(Digest.sha1, new TextEncoder().encode(path));
520571
}, Effect.provide(Digest.layerWebCrypto));
521572

522-
function gitLabLineRange(
523-
fileHash: string,
524-
start: PullRequestReviewPosition | undefined,
525-
end: PullRequestReviewPosition,
526-
) {
573+
function gitLabLineRange(fileHash: string, patch: string, comment: PullRequestReviewCommentDraft) {
574+
const start = comment.startPosition;
527575
if (start === undefined) return {};
528-
const first = gitLabLineRangeEnd(fileHash, start);
529-
const last = gitLabLineRangeEnd(fileHash, end);
576+
const header = gitLabDiffHeader(comment.oldPath ?? comment.path, comment.path);
577+
const first = gitLabLineRangeEnd(fileHash, start, gitLabLineCounters(patch, header, start));
578+
const last = gitLabLineRangeEnd(
579+
fileHash,
580+
comment.position,
581+
gitLabLineCounters(patch, header, comment.position),
582+
);
530583
return first.line_code === last.line_code ? {} : { line_range: { start: first, end: last } };
531584
}
532585

@@ -852,6 +905,28 @@ export const make = Effect.gen(function* () {
852905
}),
853906
);
854907

908+
/** Reads diff pages only until every header is found, for the files ranged comments sit on. */
909+
const patchCovering = (
910+
input: {
911+
readonly cwd: string;
912+
readonly host?: string | undefined;
913+
readonly repository: string;
914+
readonly number: number;
915+
},
916+
headers: ReadonlyArray<string>,
917+
page: number,
918+
collected: string,
919+
): Effect.Effect<string, GitLabPullRequestCliError> =>
920+
headers.every((header) => `\n${collected}`.includes(`\n${header}`))
921+
? Effect.succeed(collected)
922+
: diffPage({ ...input, page }).pipe(
923+
Effect.flatMap((slice) =>
924+
slice.nextCursor === null
925+
? Effect.succeed(collected + slice.patch)
926+
: patchCovering(input, headers, page + 1, collected + slice.patch),
927+
),
928+
);
929+
855930
const notesPage = (input: {
856931
readonly cwd: string;
857932
readonly host?: string | undefined;
@@ -1762,6 +1837,17 @@ export const make = Effect.gen(function* () {
17621837
// the verdict goes last — a half-sent review is never an approval.
17631838
if (input.comments.length > 0) {
17641839
const refs = yield* getDiffRefs(input);
1840+
const rangedFileHeaders = input.comments.flatMap((comment) =>
1841+
comment.startPosition !== undefined &&
1842+
(comment.startPosition.kind !== "context" || comment.position.kind !== "context")
1843+
? [gitLabDiffHeader(comment.oldPath ?? comment.path, comment.path)]
1844+
: [],
1845+
);
1846+
// Line codes only steer GitLab's highlight of a range, so an unreadable diff falls back
1847+
// to codes without the other side's counter rather than blocking the review.
1848+
const patch = yield* patchCovering(input, rangedFileHeaders, 1, "").pipe(
1849+
Effect.orElseSucceed(() => ""),
1850+
);
17651851
yield* Effect.forEach(
17661852
input.comments,
17671853
(comment) =>
@@ -1788,7 +1874,7 @@ export const make = Effect.gen(function* () {
17881874
old_path: comment.oldPath ?? comment.path,
17891875
new_path: comment.path,
17901876
...gitLabReviewPositionLines(comment.position),
1791-
...gitLabLineRange(fileHash, comment.startPosition, comment.position),
1877+
...gitLabLineRange(fileHash, patch, comment),
17921878
},
17931879
}),
17941880
}),

0 commit comments

Comments
 (0)