Elffuss BraidHub

kikocis/continue public

main · 6.3 KiBRawPermalink
1import { createPatch } from "diff";
2
3export enum DiffFormatType {
4 Unified = "unified",
5 RawBeforeAfter = "beforeAfter",
6 TokenLineDiff = "linediff",
7}
8
9export type BeforeAfterDiff = {
10 filePath: string;
11 beforeContent: string;
12 afterContent: string;
13};
14
15export interface CreateDiffArgs {
16 beforeContent: string;
17 afterContent: string;
18 filePath: string;
19 diffType: DiffFormatType;
20 contextLines: number;
21}
22
23export const createDiff = ({
24 beforeContent,
25 afterContent,
26 filePath,
27 diffType,
28 contextLines,
29}: CreateDiffArgs) => {
30 switch (diffType) {
31 case DiffFormatType.Unified:
32 return createUnifiedDiff(
33 beforeContent,
34 afterContent,
35 filePath,
36 contextLines,
37 );
38 case DiffFormatType.TokenLineDiff:
39 return createTokenLineDiff(beforeContent, afterContent, filePath);
40 }
41 return "";
42};
43
44const createUnifiedDiff = (
45 beforeContent: string,
46 afterContent: string,
47 filePath: string,
48 contextLines: number,
49) => {
50 const normalizedBefore = beforeContent.endsWith("\n")
51 ? beforeContent
52 : beforeContent + "\n";
53 const normalizedAfter = afterContent.endsWith("\n")
54 ? afterContent
55 : afterContent + "\n";
56
57 const patch = createPatch(
58 filePath,
59 normalizedBefore,
60 normalizedAfter,
61 "before",
62 "after",
63 { context: contextLines },
64 );
65
66 return patch;
67};
68
69export const createBeforeAfterDiff = (
70 beforeContent: string,
71 afterContent: string,
72 filePath: string,
73) => {
74 const normalizedBefore = beforeContent.endsWith("\n")
75 ? beforeContent
76 : beforeContent + "\n";
77 const normalizedAfter = afterContent.endsWith("\n")
78 ? afterContent
79 : afterContent + "\n";
80
81 const result: BeforeAfterDiff = {
82 filePath: filePath,
83 beforeContent: normalizedBefore,
84 afterContent: normalizedAfter,
85 };
86
87 return result;
88};
89
90const createTokenLineDiff = (
91 beforeContent: string,
92 afterContent: string,
93 filePath: string,
94) => {
95 // TODO: Implement token line diff
96 return "";
97};
98
99export interface DiffMetadata {
100 oldFilename?: string; // Filename in the original version
101 newFilename?: string; // Filename in the modified version
102 oldTimestamp?: string; // Timestamp of the original file
103 newTimestamp?: string; // Timestamp of the modified file
104 hunks?: Array<{
105 // Information about each change hunk
106 oldStart: number; // Starting line in original file
107 oldCount: number; // Number of lines in original file
108 newStart: number; // Starting line in modified file
109 newCount: number; // Number of lines in modified file
110 header?: string; // Optional section header
111 lines: Array<{
112 type: "context" | "addition" | "deletion";
113 content: string;
114 oldLineNumber?: number;
115 newLineNumber?: number;
116 }>;
117 }>;
118 isBinary?: boolean; // Whether this is a binary file diff
119 isNew?: boolean; // Whether this is a new file
120 isDeleted?: boolean; // Whether this file was deleted
121 isRename?: boolean; // Whether this file was renamed
122}
123
124export function extractMetadataFromUnifiedDiff(
125 unifiedDiff: string,
126): DiffMetadata {
127 const metadata: DiffMetadata = {};
128 const lines = unifiedDiff.split("\n");
129
130 // Parse the header lines (first two lines)
131 if (lines.length >= 2) {
132 // Parse original file info (--- line)
133 const oldFileMatch = lines[0].match(/^--- (a\/)?(.+?)(?:\t(.+))?$/);
134 if (oldFileMatch) {
135 metadata.oldFilename = oldFileMatch[2];
136 metadata.oldTimestamp = oldFileMatch[3];
137
138 // Check if this is a new file
139 if (metadata.oldFilename === "/dev/null") {
140 metadata.isNew = true;
141 }
142 }
143
144 // Parse modified file info (+++ line)
145 const newFileMatch = lines[1].match(/^\+\+\+ (b\/)?(.+?)(?:\t(.+))?$/);
146 if (newFileMatch) {
147 metadata.newFilename = newFileMatch[2];
148 metadata.newTimestamp = newFileMatch[3];
149
150 // Check if this file was deleted
151 if (metadata.newFilename === "/dev/null") {
152 metadata.isDeleted = true;
153 }
154 }
155
156 // Check if this is a rename (different old and new names)
157 if (
158 metadata.oldFilename &&
159 metadata.newFilename &&
160 metadata.oldFilename !== "/dev/null" &&
161 metadata.newFilename !== "/dev/null" &&
162 metadata.oldFilename !== metadata.newFilename
163 ) {
164 metadata.isRename = true;
165 }
166 }
167
168 // Parse hunk headers and content
169 metadata.hunks = [];
170 const hunkHeaderRegex =
171 /^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@(?:\s(.*))?$/;
172
173 let currentHunk: NonNullable<DiffMetadata["hunks"]>[0] | null = null;
174 let oldLineNumber = 0;
175 let newLineNumber = 0;
176
177 for (let i = 2; i < lines.length; i++) {
178 const line = lines[i];
179 const hunkMatch = line.match(hunkHeaderRegex);
180
181 if (hunkMatch) {
182 currentHunk = {
183 oldStart: parseInt(hunkMatch[1], 10), // line number where changes start in original file
184 oldCount: hunkMatch[2] ? parseInt(hunkMatch[2], 10) : 1, // number of changed lines in original file, default to 1 if not specified
185 newStart: parseInt(hunkMatch[3], 10), // line number where changes start in modified file
186 newCount: hunkMatch[4] ? parseInt(hunkMatch[4], 10) : 1, // number of changed lines in modified file, default to 1 if not specified
187 header: hunkMatch[5], // the line starting with @@
188 lines: [], // the actual line changes
189 };
190
191 oldLineNumber = currentHunk.oldStart;
192 newLineNumber = currentHunk.newStart;
193
194 metadata.hunks.push(currentHunk);
195 } else if (
196 currentHunk &&
197 (line.startsWith(" ") || line.startsWith("+") || line.startsWith("-"))
198 ) {
199 // Process hunk content lines.
200 const lineType = line[0];
201 const content = line.slice(1);
202
203 if (lineType === " ") {
204 // Context line (unchanged).
205 currentHunk.lines.push({
206 type: "context",
207 content,
208 oldLineNumber: oldLineNumber++,
209 newLineNumber: newLineNumber++,
210 });
211 } else if (lineType === "+") {
212 currentHunk.lines.push({
213 type: "addition",
214 content,
215 newLineNumber: newLineNumber++,
216 });
217 } else if (lineType === "-") {
218 currentHunk.lines.push({
219 type: "deletion",
220 content,
221 oldLineNumber: oldLineNumber++,
222 });
223 }
224 }
225
226 // Check for binary file marker
227 if (line.includes("Binary files") || line.includes("GIT binary patch")) {
228 metadata.isBinary = true;
229 }
230 }
231
232 return metadata;
233}