Open History to see the last commit
1import { quoteGitPatchPath } from "@t3tools/shared/gitPatchPath";
2import { structuredPatch } from "diff";
3
4import type { AzureDevOpsChangeEntry } from "./azureDevOpsPullRequestJson.ts";
5
6/**
7 * Azure hangs a pull request's changed files off an iteration, so a push landing mid-read would
8 * renumber the list under a cursor that did not also pin the iteration.
9 */
10export interface AzureDevOpsDiffCursor {
11 readonly iterationId: number;
12 readonly fileIndex: number;
13}
14
15const CURSOR_SEPARATOR = ":";
16
17const CURSOR_COMPONENT = /^\d+$/;
18
19export function formatAzureDevOpsDiffCursor(cursor: AzureDevOpsDiffCursor): string {
20 return `${cursor.iterationId}${CURSOR_SEPARATOR}${cursor.fileIndex}`;
21}
22
23export function parseAzureDevOpsDiffCursor(
24 raw: string | null | undefined,
25): AzureDevOpsDiffCursor | null {
26 if (raw === null || raw === undefined) return null;
27 const [iteration, file, ...rest] = raw.split(CURSOR_SEPARATOR);
28 if (rest.length > 0) return null;
29 if (iteration === undefined || file === undefined) return null;
30 if (!CURSOR_COMPONENT.test(iteration) || !CURSOR_COMPONENT.test(file)) return null;
31 const iterationId = Number(iteration);
32 const fileIndex = Number(file);
33 if (!Number.isSafeInteger(iterationId) || iterationId <= 0) return null;
34 if (!Number.isSafeInteger(fileIndex) || fileIndex < 0) return null;
35 return { iterationId, fileIndex };
36}
37
38export interface AzureDevOpsFileTexts {
39 readonly oldContents: string;
40 readonly newContents: string;
41 readonly binary: boolean;
42}
43
44export interface AzureDevOpsFilePatch {
45 readonly section: string;
46 readonly truncated: boolean;
47 readonly abandoned: boolean;
48 readonly edits: number;
49}
50
51/**
52 * Azure hands back whole files rather than a patch, so an oversize file is paid for twice
53 * over before anything can be diffed.
54 */
55const MAX_FILE_BYTES = 512 * 1024;
56
57const PATCH_CONTEXT_LINES = 3;
58
59/**
60 * The line diff costs about the square of the edit distance, so an unbounded pair sharing almost
61 * nothing could hold the whole server. Bounded in edits rather than milliseconds so a change
62 * slices the same way on every machine.
63 */
64export const MAX_FILE_DIFF_EDITS = 2_000;
65
66const MAX_FILE_DIFF_MILLIS = 2_000;
67
68export const MAX_DIFF_SLICE_EDITS = 6_000;
69
70export const MAX_DIFF_SLICE_BYTES = 256 * 1024;
71
72/**
73 * A binary, oversize, or unreadable entry is just a header, so neither budget above stops a
74 * run of thousands of them.
75 */
76export const MAX_DIFF_SLICE_FILES = 300;
77
78const NO_NEWLINE_MARKER = "\\ No newline at end of file";
79
80function contentLines(contents: string): ReadonlyArray<string> {
81 if (contents === "") return [];
82 const lines = contents.split("\n");
83 if (lines.at(-1) === "") lines.pop();
84 return lines;
85}
86
87function isBinary(contents: string): boolean {
88 return contents.includes("\u0000");
89}
90
91export const byteLength = (contents: string) => Buffer.byteLength(contents, "utf8");
92
93/**
94 * Git points an empty range at the line before it, which is line zero for a file that is wholly
95 * new or wholly gone, and writes a single line as its number alone.
96 */
97function hunkRange(start: number, lines: number): string {
98 if (lines === 0) return `${start - 1},0`;
99 return lines === 1 ? String(start) : `${start},${lines}`;
100}
101
102/**
103 * Azure reports no file mode, so the ordinary one stands in. Names are quoted the way git quotes
104 * them, prefix inside the quoting: a header reader stops a bare name at its first tab or newline,
105 * so a path holding either would be truncated and its viewed mark would land on the wrong file.
106 */
107function patchHeader(change: AzureDevOpsChangeEntry): string {
108 const oldSide = quoteGitPatchPath(`a/${change.oldPath}`);
109 const newSide = quoteGitPatchPath(`b/${change.path}`);
110 const lines = [`diff --git ${oldSide} ${newSide}`];
111 if (change.changeKind === "new") lines.push("new file mode 100644");
112 if (change.changeKind === "deleted") lines.push("deleted file mode 100644");
113 if (change.changeKind === "rename-pure" || change.changeKind === "rename-changed") {
114 lines.push(
115 `rename from ${quoteGitPatchPath(change.oldPath)}`,
116 `rename to ${quoteGitPatchPath(change.path)}`,
117 );
118 }
119 lines.push(
120 `--- ${change.changeKind === "new" ? "/dev/null" : oldSide}`,
121 `+++ ${change.changeKind === "deleted" ? "/dev/null" : newSide}`,
122 );
123 return lines.join("\n");
124}
125
126function replacementSection(header: string, texts: AzureDevOpsFileTexts): string {
127 const oldLines = contentLines(texts.oldContents);
128 const newLines = contentLines(texts.newContents);
129 const noNewline = (contents: string, lines: ReadonlyArray<string>) =>
130 lines.length > 0 && !contents.endsWith("\n") ? [NO_NEWLINE_MARKER] : [];
131 return [
132 header,
133 `@@ -${hunkRange(1, oldLines.length)} +${hunkRange(1, newLines.length)} @@`,
134 ...oldLines.map((line) => `-${line}`),
135 ...noNewline(texts.oldContents, oldLines),
136 ...newLines.map((line) => `+${line}`),
137 ...noNewline(texts.newContents, newLines),
138 "",
139 ].join("\n");
140}
141
142export function azureDevOpsFilePatch(input: {
143 readonly change: AzureDevOpsChangeEntry;
144 readonly texts: AzureDevOpsFileTexts;
145}): AzureDevOpsFilePatch {
146 const header = patchHeader(input.change);
147 const { oldContents, newContents } = input.texts;
148
149 if (input.texts.binary || isBinary(oldContents) || isBinary(newContents)) {
150 const oldSide = quoteGitPatchPath(`a/${input.change.oldPath}`);
151 const newSide = quoteGitPatchPath(`b/${input.change.path}`);
152 const binary = `Binary files ${oldSide} and ${newSide} differ`;
153 return { section: `${header}\n${binary}\n`, truncated: true, abandoned: false, edits: 0 };
154 }
155 if (byteLength(oldContents) > MAX_FILE_BYTES || byteLength(newContents) > MAX_FILE_BYTES) {
156 return { section: `${header}\n`, truncated: true, abandoned: false, edits: 0 };
157 }
158
159 const created = oldContents === "" && newContents !== "";
160 const deleted = newContents === "" && oldContents !== "";
161 if (created || deleted) {
162 const contents = created ? newContents : oldContents;
163 const lines = contentLines(contents);
164 // A `+`/`-` marker on every line can put a side that just fits the size ceiling over it.
165 // Checked against bytes-plus-marker-count rather than building the section, since that upper
166 // bound is cheaper and this is exactly the file shape that would cost the most to build.
167 if (byteLength(contents) + lines.length > MAX_FILE_BYTES) {
168 return { section: `${header}\n`, truncated: true, abandoned: false, edits: lines.length };
169 }
170 const section = replacementSection(header, input.texts);
171 if (byteLength(section) > MAX_FILE_BYTES) {
172 return { section: `${header}\n`, truncated: true, abandoned: false, edits: lines.length };
173 }
174 return { section, truncated: false, abandoned: false, edits: lines.length };
175 }
176
177 const patch = structuredPatch(
178 `a/${input.change.oldPath}`,
179 `b/${input.change.path}`,
180 oldContents,
181 newContents,
182 undefined,
183 undefined,
184 {
185 context: PATCH_CONTEXT_LINES,
186 maxEditLength: MAX_FILE_DIFF_EDITS,
187 timeout: MAX_FILE_DIFF_MILLIS,
188 },
189 );
190 // Hitting the edit ceiling lists the file without hunks rather than falling back to a full
191 // replacement: the ceiling is a distance, not a proportion, so a long file can reach it having
192 // changed in one small corner, and both sides in full would bury that corner in a wall of text.
193 if (patch === undefined) {
194 return {
195 section: `${header}\n`,
196 truncated: true,
197 abandoned: true,
198 edits: MAX_FILE_DIFF_EDITS,
199 };
200 }
201
202 let edits = 0;
203 const hunks = patch.hunks.map((hunk) => {
204 for (const line of hunk.lines) {
205 if (line.startsWith("+") || line.startsWith("-")) edits += 1;
206 }
207 return [
208 `@@ -${hunkRange(hunk.oldStart, hunk.oldLines)} +${hunkRange(hunk.newStart, hunk.newLines)} @@`,
209 ...hunk.lines,
210 ].join("\n");
211 });
212 const section = hunks.length === 0 ? `${header}\n` : `${header}\n${hunks.join("\n")}\n`;
213 // The edit ceiling bounds edit distance, not the hunks' size: a handful of very long lines plus
214 // context can still exceed the size ceiling even well inside the edit ceiling.
215 if (byteLength(section) > MAX_FILE_BYTES) {
216 return { section: `${header}\n`, truncated: true, abandoned: false, edits };
217 }
218 return { section, truncated: false, abandoned: false, edits };
219}
220
221export function azureDevOpsUnreadableFilePatch(
222 change: AzureDevOpsChangeEntry,
223): AzureDevOpsFilePatch {
224 return { section: `${patchHeader(change)}\n`, truncated: true, abandoned: false, edits: 0 };
225}