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

main
ts 53 lines 1.86 KB
Raw
1 import type { PullRequestReviewPosition } from "@t3tools/contracts";
2
3 import { HUNK_HEADER, headerPath } from "./pullRequestReviewGuideNormalize.ts";
4
5 /** `new` numbers a line in the PR's head, `old` in its base. */
6 export type ReviewLineSide = "new" | "old";
7
8 /** Where a line of `path` sits in a unified patch, or null when the patch does not show it. */
9 export function reviewPositionInPatch(
10 patch: string,
11 path: string,
12 line: number,
13 side: ReviewLineSide,
14 ): PullRequestReviewPosition | null {
15 let oldPath: string | null = null;
16 let inFile = false;
17 let inHunks = false;
18 let oldLine = 0;
19 let newLine = 0;
20 for (const text of patch.split("\n")) {
21 if (text.startsWith("diff --git ")) {
22 oldPath = null;
23 inFile = false;
24 inHunks = false;
25 } else if (!inHunks && text.startsWith("--- ")) {
26 oldPath = headerPath(text, "a/");
27 } else if (!inHunks && text.startsWith("+++ ")) {
28 inFile = (headerPath(text, "b/") ?? oldPath) === path;
29 } else if (text.startsWith("@@")) {
30 // Every file's hunks count, so another file's `+++ ` source line is never a header.
31 const header = HUNK_HEADER.exec(text);
32 if (header === null) continue;
33 inHunks = true;
34 oldLine = Number(header[1]);
35 newLine = Number(header[3]);
36 } else if (inFile && inHunks) {
37 if (text.startsWith("+")) {
38 if (side === "new" && newLine === line) return { kind: "added", newLine };
39 newLine += 1;
40 } else if (text.startsWith("-")) {
41 if (side === "old" && oldLine === line) return { kind: "deleted", oldLine };
42 oldLine += 1;
43 } else if (text.startsWith(" ")) {
44 if ((side === "new" ? newLine : oldLine) === line) {
45 return { kind: "context", oldLine, newLine, side: side === "new" ? "right" : "left" };
46 }
47 oldLine += 1;
48 newLine += 1;
49 }
50 }
51 }
52 return null;
53 }