Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

azureDevOpsDiff.ts

200 lines7.1 KB

1import { quoteGitPatchPath } from "@t3tools/shared/gitPatchPath";
2import { structuredPatch } from "diff";
3​
4import type { AzureDevOpsChangeEntry } from "./azureDevOpsPullRequestJson.ts";
5​
6/** Pin the iteration to prevent pushes from renumbering files during pagination. */
7export interface AzureDevOpsDiffCursor {
8 readonly iterationId: number;
9 readonly fileIndex: number;
11​
12const CURSOR_SEPARATOR = ":";
13​
14const CURSOR_COMPONENT = /^\d+$/;
15​
16export function formatAzureDevOpsDiffCursor(cursor: AzureDevOpsDiffCursor): string {
17 return `${cursor.iterationId}${CURSOR_SEPARATOR}${cursor.fileIndex}`;
19​
20export function parseAzureDevOpsDiffCursor(
21 raw: string | null | undefined,
22): AzureDevOpsDiffCursor | null {
23 if (raw === null || raw === undefined) return null;
24 const [iteration, file, ...rest] = raw.split(CURSOR_SEPARATOR);
25 if (rest.length > 0) return null;
26 if (iteration === undefined || file === undefined) return null;
27 if (!CURSOR_COMPONENT.test(iteration) || !CURSOR_COMPONENT.test(file)) return null;
28 const iterationId = Number(iteration);
29 const fileIndex = Number(file);
30 if (!Number.isSafeInteger(iterationId) || iterationId <= 0) return null;
31 if (!Number.isSafeInteger(fileIndex) || fileIndex < 0) return null;
32 return { iterationId, fileIndex };
34​
35export interface AzureDevOpsFileTexts {
36 readonly oldContents: string;
37 readonly newContents: string;
38 readonly binary: boolean;
40​
41export interface AzureDevOpsFilePatch {
42 readonly section: string;
43 readonly truncated: boolean;
44 readonly abandoned: boolean;
45 readonly edits: number;
47​
48/** Azure returns whole files; oversized files incur both reads before diffing. */
49const MAX_FILE_BYTES = 512 * 1024;
50​
51const PATCH_CONTEXT_LINES = 3;
52​
53/** Edit distance bounds quadratic work independently of machine speed. */
54export const MAX_FILE_DIFF_EDITS = 2_000;
55​
56const MAX_FILE_DIFF_MILLIS = 2_000;
57​
58export const MAX_DIFF_SLICE_EDITS = 6_000;
59​
60export const MAX_DIFF_SLICE_BYTES = 256 * 1024;
61​
62/** Header-only entries can evade the byte and edit budgets. */
63export const MAX_DIFF_SLICE_FILES = 300;
64​
65const NO_NEWLINE_MARKER = "\\ No newline at end of file";
66​
67function contentLines(contents: string): ReadonlyArray<string> {
68 if (contents === "") return [];
69 const lines = contents.split("\n");
70 if (lines.at(-1) === "") lines.pop();
71 return lines;
73​
74function isBinary(contents: string): boolean {
75 return contents.includes("\u0000");
77​
78export const byteLength = (contents: string) => Buffer.byteLength(contents, "utf8");
79​
80/** Git anchors empty ranges at the preceding line, which may be zero. */
81function hunkRange(start: number, lines: number): string {
82 if (lines === 0) return `${start - 1},0`;
83 return lines === 1 ? String(start) : `${start},${lines}`;
85​
86/** Azure omits modes. Quote prefixed paths to preserve tabs/newlines. */
87function patchHeader(change: AzureDevOpsChangeEntry): string {
88 const oldSide = quoteGitPatchPath(`a/${change.oldPath}`);
89 const newSide = quoteGitPatchPath(`b/${change.path}`);
90 const lines = [`diff --git ${oldSide} ${newSide}`];
91 if (change.changeKind === "new") lines.push("new file mode 100644");
92 if (change.changeKind === "deleted") lines.push("deleted file mode 100644");
93 if (change.changeKind === "rename-pure" || change.changeKind === "rename-changed") {
94 lines.push(
95 `rename from ${quoteGitPatchPath(change.oldPath)}`,
96 `rename to ${quoteGitPatchPath(change.path)}`,
97 );
98 }
99 lines.push(
100 `--- ${change.changeKind === "new" ? "/dev/null" : oldSide}`,
101 `+++ ${change.changeKind === "deleted" ? "/dev/null" : newSide}`,
102 );
103 return lines.join("\n");
105​
106function replacementSection(header: string, texts: AzureDevOpsFileTexts): string {
107 const oldLines = contentLines(texts.oldContents);
108 const newLines = contentLines(texts.newContents);
109 const noNewline = (contents: string, lines: ReadonlyArray<string>) =>
110 lines.length > 0 && !contents.endsWith("\n") ? [NO_NEWLINE_MARKER] : [];
111 return [
112 header,
113 `@@ -${hunkRange(1, oldLines.length)} +${hunkRange(1, newLines.length)} @@`,
114 ...oldLines.map((line) => `-${line}`),
115 ...noNewline(texts.oldContents, oldLines),
116 ...newLines.map((line) => `+${line}`),
117 ...noNewline(texts.newContents, newLines),
118 "",
119 ].join("\n");
121​
122export function azureDevOpsFilePatch(input: {
123 readonly change: AzureDevOpsChangeEntry;
124 readonly texts: AzureDevOpsFileTexts;
125}): AzureDevOpsFilePatch {
126 const header = patchHeader(input.change);
127 const { oldContents, newContents } = input.texts;
128​
129 if (input.texts.binary || isBinary(oldContents) || isBinary(newContents)) {
130 const oldSide = quoteGitPatchPath(`a/${input.change.oldPath}`);
131 const newSide = quoteGitPatchPath(`b/${input.change.path}`);
132 const binary = `Binary files ${oldSide} and ${newSide} differ`;
133 return { section: `${header}\n${binary}\n`, truncated: true, abandoned: false, edits: 0 };
134 }
135 if (byteLength(oldContents) > MAX_FILE_BYTES || byteLength(newContents) > MAX_FILE_BYTES) {
136 return { section: `${header}\n`, truncated: true, abandoned: false, edits: 0 };
137 }
138​
139 const created = oldContents === "" && newContents !== "";
140 const deleted = newContents === "" && oldContents !== "";
141 if (created || deleted) {
142 const contents = created ? newContents : oldContents;
143 const lines = contentLines(contents);
144 // Include per-line markers in the byte budget.
145 if (byteLength(contents) + lines.length > MAX_FILE_BYTES) {
146 return { section: `${header}\n`, truncated: true, abandoned: false, edits: lines.length };
147 }
148 const section = replacementSection(header, input.texts);
149 if (byteLength(section) > MAX_FILE_BYTES) {
150 return { section: `${header}\n`, truncated: true, abandoned: false, edits: lines.length };
151 }
152 return { section, truncated: false, abandoned: false, edits: lines.length };
153 }
154​
155 const patch = structuredPatch(
156 `a/${input.change.oldPath}`,
157 `b/${input.change.path}`,
158 oldContents,
159 newContents,
160 undefined,
161 undefined,
162 {
163 context: PATCH_CONTEXT_LINES,
164 maxEditLength: MAX_FILE_DIFF_EDITS,
165 timeout: MAX_FILE_DIFF_MILLIS,
166 },
167 );
168 // A full replacement could bury a small change that hit the edit limit.
169 if (patch === undefined) {
170 return {
171 section: `${header}\n`,
172 truncated: true,
173 abandoned: true,
174 edits: MAX_FILE_DIFF_EDITS,
175 };
176 }
177​
178 let edits = 0;
179 const hunks = patch.hunks.map((hunk) => {
180 for (const line of hunk.lines) {
181 if (line.startsWith("+") || line.startsWith("-")) edits += 1;
182 }
183 return [
184 `@@ -${hunkRange(hunk.oldStart, hunk.oldLines)} +${hunkRange(hunk.newStart, hunk.newLines)} @@`,
185 ...hunk.lines,
186 ].join("\n");
187 });
188 const section = hunks.length === 0 ? `${header}\n` : `${header}\n${hunks.join("\n")}\n`;
189 // Long lines can exceed the byte budget even within the edit budget.
190 if (byteLength(section) > MAX_FILE_BYTES) {
191 return { section: `${header}\n`, truncated: true, abandoned: false, edits };
192 }
193 return { section, truncated: false, abandoned: false, edits };
195​
196export function azureDevOpsUnreadableFilePatch(
197 change: AzureDevOpsChangeEntry,
198): AzureDevOpsFilePatch {
199 return { section: `${patchHeader(change)}\n`, truncated: true, abandoned: false, edits: 0 };