Elffuss BraidHub

kikocis/continue public

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