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

main
ts 191 lines 5.96 KB
Raw
1 import { msg } from "gt-react";
2 import type { FileDiffContentsLoader, FileDiffMetadata } from "@pierre/diffs";
3 import {
4 squashAtomCommandFailure,
5 type AtomCommandResult,
6 } from "@t3tools/client-runtime/state/runtime";
7 import type {
8 EnvironmentId,
9 PullRequestDiffFileContentsInput,
10 PullRequestDiffFileContentsResult,
11 PullRequestRef,
12 ReviewDiffFileContentsInput,
13 ReviewDiffFileContentsResult,
14 ReviewDiffPreviewSourceKind,
15 } from "@t3tools/contracts";
16
17 import { m } from "../i18n/messages";
18 import { resolveFileDiffPath } from "./diffRendering";
19
20 interface GitDiffFileContentsSource {
21 readonly environmentId: EnvironmentId;
22 readonly cwd: string;
23 readonly sourceKind: ReviewDiffPreviewSourceKind;
24 readonly baseRef: string | null;
25 readonly headRef: string | null;
26 readonly cacheKey: string;
27 }
28
29 interface PullRequestDiffFileContentsSource {
30 readonly environmentId: EnvironmentId;
31 readonly reference: PullRequestRef;
32 readonly commit: string | null;
33 readonly cacheKey: string;
34 }
35
36 type GetDiffFileContents<E> = (request: {
37 readonly environmentId: EnvironmentId;
38 readonly input: ReviewDiffFileContentsInput;
39 }) => Promise<AtomCommandResult<ReviewDiffFileContentsResult, E>>;
40
41 type GetPullRequestDiffFileContents<E> = (request: {
42 readonly environmentId: EnvironmentId;
43 readonly input: PullRequestDiffFileContentsInput;
44 }) => Promise<AtomCommandResult<PullRequestDiffFileContentsResult, E>>;
45
46 // Mirrors Pierre's splitFileContents so line counts match its hydration.
47 function splitLines(contents: string): ReadonlyArray<string> {
48 return contents === "" ? [] : contents.split(/(?<=\n)/);
49 }
50
51 // Whitespace-insensitive: `git diff -w` prints context lines from only one side.
52 function sameLine(patchLine: string | undefined, fileLine: string | undefined): boolean {
53 return (
54 patchLine !== undefined &&
55 fileLine !== undefined &&
56 patchLine.replace(/\s/g, "") === fileLine.replace(/\s/g, "")
57 );
58 }
59
60 function hunkSideEnd(start: number, count: number): number {
61 return start - (count === 0 ? 0 : 1) + count;
62 }
63
64 function hunkSideMatches(
65 patchLines: ReadonlyArray<string>,
66 patchIndex: number,
67 fileLines: ReadonlyArray<string>,
68 start: number,
69 count: number,
70 ): boolean {
71 const fileIndex = hunkSideEnd(start, count) - count;
72 for (let offset = 0; offset < count; offset++) {
73 if (!sameLine(patchLines[patchIndex + offset], fileLines[fileIndex + offset])) return false;
74 }
75 return true;
76 }
77
78 // Pierre hydrates a partial patch by trusting its hunk positions, so contents that
79 // changed since the patch was computed make it render corrupt hunks or throw.
80 function reproducesPatch(fileDiff: FileDiffMetadata, oldContents: string, newContents: string) {
81 const lastHunk = fileDiff.hunks.at(-1);
82 if (lastHunk === undefined) return true;
83 const oldLines = splitLines(oldContents);
84 const newLines = splitLines(newContents);
85 const hunksMatch = fileDiff.hunks.every(
86 (hunk) =>
87 hunkSideMatches(
88 fileDiff.deletionLines,
89 hunk.deletionLineIndex,
90 oldLines,
91 hunk.deletionStart,
92 hunk.deletionCount,
93 ) &&
94 hunkSideMatches(
95 fileDiff.additionLines,
96 hunk.additionLineIndex,
97 newLines,
98 hunk.additionStart,
99 hunk.additionCount,
100 ),
101 );
102 return (
103 hunksMatch &&
104 oldLines.length - hunkSideEnd(lastHunk.deletionStart, lastHunk.deletionCount) ===
105 newLines.length - hunkSideEnd(lastHunk.additionStart, lastHunk.additionCount)
106 );
107 }
108
109 function createDiffFileContentsLoader(
110 load: (input: {
111 readonly changeType: PullRequestDiffFileContentsInput["changeType"];
112 readonly oldPath: string;
113 readonly newPath: string;
114 }) => Promise<{ readonly oldContents: string; readonly newContents: string }>,
115 cacheKey: string,
116 ): FileDiffContentsLoader {
117 return async (fileDiff) => {
118 const newPath = resolveFileDiffPath(fileDiff);
119 const oldPath = fileDiff.prevName
120 ? resolveFileDiffPath({ ...fileDiff, name: fileDiff.prevName })
121 : newPath;
122 const contents = await load({ changeType: fileDiff.type, oldPath, newPath });
123 const newFile = {
124 name: newPath,
125 contents: contents.newContents,
126 cacheKey: `${cacheKey}:new:${newPath}`,
127 };
128 if (fileDiff.type === "rename-pure") {
129 return { oldFile: null, newFile };
130 }
131 if (!reproducesPatch(fileDiff, contents.oldContents, contents.newContents)) {
132 throw new Error(
133 m(msg("This file changed since the diff was loaded. Refresh the diff to expand it.")),
134 );
135 }
136 return {
137 oldFile: {
138 name: oldPath,
139 contents: contents.oldContents,
140 cacheKey: `${cacheKey}:old:${oldPath}`,
141 },
142 newFile,
143 };
144 };
145 }
146
147 export function createGitDiffFileContentsLoader<E>(
148 getDiffFileContents: GetDiffFileContents<E>,
149 source: GitDiffFileContentsSource,
150 ): FileDiffContentsLoader {
151 return createDiffFileContentsLoader(async ({ changeType, oldPath, newPath }) => {
152 const result = await getDiffFileContents({
153 environmentId: source.environmentId,
154 input: {
155 cwd: source.cwd,
156 sourceKind: source.sourceKind,
157 changeType,
158 baseRef: source.baseRef,
159 headRef: source.headRef,
160 oldPath,
161 newPath,
162 },
163 });
164 if (result._tag !== "Success") {
165 throw squashAtomCommandFailure(result);
166 }
167 return result.value;
168 }, source.cacheKey);
169 }
170
171 export function createPullRequestDiffFileContentsLoader<E>(
172 getDiffFileContents: GetPullRequestDiffFileContents<E>,
173 source: PullRequestDiffFileContentsSource,
174 ): FileDiffContentsLoader {
175 return createDiffFileContentsLoader(async ({ changeType, oldPath, newPath }) => {
176 const result = await getDiffFileContents({
177 environmentId: source.environmentId,
178 input: {
179 ...source.reference,
180 ...(source.commit === null ? {} : { commit: source.commit }),
181 changeType,
182 oldPath,
183 newPath,
184 },
185 });
186 if (result._tag !== "Success") {
187 throw squashAtomCommandFailure(result);
188 }
189 return result.value;
190 }, source.cacheKey);
191 }