Elffuss BraidHub

kikocis/continue public

71fd2e7d4456 · 4.9 KiBRawPermalink
1import { DiffLine } from "../../index";
2
3/**
4 * Checks if a string matches unified diff format by validating:
5 * 1. Has at least one hunk header (@@ -n,m +n,m @@)
6 * 2. Contains valid diff content lines (starting with +, -, or space) which are not header lines
7 */
8export function isUnifiedDiffFormat(diff: string): boolean {
9 const lines = diff.trim().split("\n");
10
11 if (lines.length < 3) {return false;}
12
13 let hasHunkHeader = false;
14 let hasValidContent = false;
15
16 for (const line of lines) {
17 if (line.startsWith("---") || line.startsWith("+++")) {
18 // ignore file headers - they are not required or useful
19 } else if (line.match(/^@@ -\d+,?\d* \+\d+,?\d* @@/)) {
20 hasHunkHeader = true;
21 } else if (line.match(/^[+ -]/) || line === "") {
22 hasValidContent = true;
23 }
24 }
25
26 return hasHunkHeader && hasValidContent;
27}
28
29function extractBeforeLines(hunkLines: string[]): string[] {
30 return hunkLines
31 .filter((line) => line.startsWith("-") || !line.startsWith("+"))
32 .map((line) => line.substring(1));
33}
34
35/**
36 * Applies a unified diff to source code and returns an array of DiffLine objects.
37 * Each DiffLine contains a type ("same", "new", or "old") and the line content.
38 *
39 * @throws Error if the diff cannot be cleanly applied to the source
40 */
41export function applyUnifiedDiff(sourceCode: string, unifiedDiffText: string): DiffLine[] {
42 const sourceLines = sourceCode.split(/\r?\n/);
43 const hunks = parseUnifiedDiff(unifiedDiffText);
44 const diffResult: DiffLine[] = [];
45 let currentPos = 0; // pointer in sourceLines
46
47 for (const hunk of hunks) {
48 const hunkBeforeLines = extractBeforeLines(hunk.lines);
49 const hunkStart = findHunkInSource(sourceLines, hunkBeforeLines, currentPos);
50 if (hunkStart === -1) {
51 // All hunks must be found in the source code. If not, throw an error.
52 throw new Error("Hunk could not be applied cleanly to source code.");
53 }
54
55 // Emit any unchanged lines that come before this hunk.
56 for (let i = currentPos; i < hunkStart; i++) {
57 diffResult.push({ type: "same", line: sourceLines[i] });
58 }
59 let hunkSourcePos = hunkStart;
60
61 for (const dline of hunk.lines) {
62 const srcLine = sourceLines[hunkSourcePos];
63 if (dline.startsWith("+")) {
64 // Insertion: output new line (strip the '+' marker)
65 diffResult.push({ type: "new", line: dline.substring(1) });
66 } else if (dline.startsWith("-")) {
67 // Removal: output the removed (old) line and advance the pointer.
68 diffResult.push({ type: "old", line: srcLine });
69 hunkSourcePos++;
70 } else {
71 // Context line: use the source line (in case the diff’s context has a minor whitespace error)
72 // and advance the pointer.
73 diffResult.push({ type: "same", line: srcLine });
74 hunkSourcePos++;
75 }
76 }
77 currentPos = hunkSourcePos;
78 }
79
80 for (let i = currentPos; i < sourceLines.length; i++) {
81 diffResult.push({ type: "same", line: sourceLines[i] });
82 }
83 return diffResult;
84}
85
86interface Hunk {
87 lines: string[];
88}
89
90/**
91 * Parses a unified diff string into an array of hunks.
92 * It skips the file header lines (starting with "---" or "+++") and hunk header lines (starting with "@@"),
93 * then collects the remaining lines (which may start with '+' or '-' or have no prefix).
94 */
95function parseUnifiedDiff(diffText: string): Hunk[] {
96 const lines = diffText.split(/\r?\n/);
97 const hunks: Hunk[] = [];
98 let currentHunk: Hunk | null = null;
99
100 for (const line of lines) {
101 if (line.startsWith("---") || line.startsWith("+++")) {
102 // Skip file header lines.
103 continue;
104 }
105 if (line.startsWith("@@")) {
106 if (currentHunk) {
107 hunks.push(currentHunk);
108 }
109 currentHunk = { lines: [] };
110 continue;
111 }
112 currentHunk?.lines.push(line);
113 }
114 if (currentHunk) {
115 hunks.push(currentHunk);
116 }
117 return hunks;
118}
119
120/**
121 * Searches for an occurrence of the block of lines (the “before” block) in sourceLines,
122 * starting at startIndex. Comparison is done by checking if the lines are exactly equal,
123 * or if their trimmed versions are equal.
124 *
125 * Returns the index in sourceLines where the block begins, or -1 if no match is found.
126 */
127function findHunkInSource(sourceLines: string[], hunkBeforeLines: string[], startIndex: number): number {
128 for (let i = startIndex; i <= sourceLines.length - hunkBeforeLines.length; i++) {
129 let match = true;
130 for (let j = 0; j < hunkBeforeLines.length; j++) {
131 const sl = sourceLines[i + j];
132 const hl = hunkBeforeLines[j];
133 if (!linesMatch(sl, hl)) {
134 match = false;
135 break;
136 }
137 }
138 if (match) {
139 return i;
140 }
141 }
142 return -1;
143}
144
145/**
146 * Returns true if the two lines are either exactly equal or equal after trimming whitespace and tabs.
147 */
148function linesMatch(a: string, b: string): boolean {
149 const trimmedA = a.replace(/^\s+/, "");
150 const trimmedB = b.replace(/^\s+/, "");
151 return trimmedA === trimmedB;
152}