Elffuss BraidHub

kikocis/continue public

54ea0739010d · 16.1 KiBRawPermalink
1import { myersDiff } from "core/diff/myers";
2import * as URI from "uri-js";
3import * as vscode from "vscode";
4
5import {
6 AddedLineDecorationManager,
7 RemovedLineDecorationManager,
8 belowIndexDecorationType,
9 indexDecorationType,
10} from "./decorations";
11
12import type { ApplyState, DiffLine } from "core";
13import type { VerticalDiffCodeLens } from "./manager";
14
15export interface VerticalDiffHandlerOptions {
16 input?: string;
17 instant?: boolean;
18 onStatusUpdate: (
19 status?: ApplyState["status"],
20 numDiffs?: ApplyState["numDiffs"],
21 fileContent?: ApplyState["fileContent"],
22 ) => void;
23}
24
25export class VerticalDiffHandler implements vscode.Disposable {
26 public insertedInCurrentBlock = 0;
27 disposables: vscode.Disposable[] = [];
28 private currentLineIndex: number;
29 private cancelled = false;
30 private newLinesAdded = 0;
31 private deletionBuffer: string[] = [];
32 private removedLineDecorations: RemovedLineDecorationManager;
33 private addedLineDecorations: AddedLineDecorationManager;
34 private _diffLinesQueue: DiffLine[] = [];
35 private _queueLock = false;
36
37 constructor(
38 private startLine: number,
39 private endLine: number,
40 private editor: vscode.TextEditor,
41 private readonly editorToVerticalDiffCodeLens: Map<
42 string,
43 VerticalDiffCodeLens[]
44 >,
45 private readonly clearForFileUri: (
46 fileUri: string | undefined,
47 accept: boolean,
48 ) => void,
49 private readonly refreshCodeLens: () => void,
50 public options: VerticalDiffHandlerOptions,
51 ) {
52 this.currentLineIndex = startLine;
53
54 this.removedLineDecorations = new RemovedLineDecorationManager(this.editor);
55 this.addedLineDecorations = new AddedLineDecorationManager(this.editor);
56
57 const disposable = vscode.window.onDidChangeActiveTextEditor((editor) => {
58 if (!editor) {
59 return;
60 }
61 // When we switch away and back to this editor, need to re-draw decorations
62 if (URI.equal(editor.document.uri.toString(), this.fileUri)) {
63 this.editor = editor;
64 this.removedLineDecorations.applyToNewEditor(editor);
65 this.addedLineDecorations.applyToNewEditor(editor);
66 this.updateIndexLineDecorations();
67 this.refreshCodeLens();
68
69 // Handle any lines received while editor was closed
70 this.queueDiffLine(undefined);
71 }
72 });
73 this.disposables.push(disposable);
74 }
75
76 public get range(): vscode.Range {
77 const startLine = Math.min(this.startLine, this.endLine);
78 const endLine = Math.max(this.startLine, this.endLine);
79 return new vscode.Range(startLine, 0, endLine, Number.MAX_SAFE_INTEGER);
80 }
81
82 get isCancelled() {
83 return this.cancelled;
84 }
85
86 private get fileUri() {
87 return this.editor.document.uri.toString();
88 }
89
90 async clear(accept: boolean) {
91 vscode.commands.executeCommand(
92 "setContext",
93 "continue.streamingDiff",
94 false,
95 );
96
97 const removedRanges = this.removedLineDecorations.ranges;
98 if (accept) {
99 // Accept all: delete all the red ranges and clear green decorations
100 await this.deleteRangeLines(removedRanges.map((r) => r.range));
101 } else {
102 // Reject all: Re-insert red lines, delete green ones
103 for (const r of removedRanges) {
104 await this.deleteRangeLines([r.range]);
105 await this.insertTextAboveLine(r.range.start.line, r.line);
106 }
107 await this.deleteRangeLines(this.addedLineDecorations.ranges);
108 }
109
110 this.clearDecorations();
111
112 this.options.onStatusUpdate(
113 "closed",
114 this.editorToVerticalDiffCodeLens.get(this.fileUri)?.length ?? 0,
115 this.editor.document.getText(),
116 );
117
118 this.cancelled = true;
119 this.refreshCodeLens();
120 this.dispose();
121 }
122
123 dispose() {
124 this.disposables.forEach((disposable) => disposable.dispose());
125 }
126
127 async queueDiffLine(diffLine: DiffLine | undefined) {
128 if (diffLine) {
129 this._diffLinesQueue.push(diffLine);
130 }
131
132 if (this._queueLock || this.editor !== vscode.window.activeTextEditor) {
133 return;
134 }
135
136 this._queueLock = true;
137
138 while (this._diffLinesQueue.length) {
139 const line = this._diffLinesQueue.shift();
140 if (!line) {
141 break;
142 }
143
144 try {
145 await this._handleDiffLine(line);
146 } catch (e) {
147 // If editor is switched between calling _handleDiffLine and the edit actually being executed
148 this._diffLinesQueue.push(line);
149 break;
150 }
151 }
152
153 this._queueLock = false;
154 }
155
156 async run(diffLineGenerator: AsyncGenerator<DiffLine>) {
157 let diffLines = [];
158
159 try {
160 // As an indicator of loading
161 this.updateIndexLineDecorations();
162
163 for await (const diffLine of diffLineGenerator) {
164 if (this.isCancelled) {
165 return;
166 }
167 diffLines.push(diffLine);
168 await this.queueDiffLine(diffLine);
169 }
170
171 // Clear deletion buffer
172 await this.insertDeletionBuffer();
173
174 await this.reapplyWithMyersDiff(diffLines);
175
176 const range = new vscode.Range(this.startLine, 0, this.startLine, 0);
177 this.editor.revealRange(
178 range,
179 vscode.TextEditorRevealType.Default,
180 );
181
182 this.options.onStatusUpdate(
183 "done",
184 this.editorToVerticalDiffCodeLens.get(this.fileUri)?.length ?? 0,
185 this.editor.document.getText(),
186 );
187
188 // Reject on user typing
189 // const listener = vscode.workspace.onDidChangeTextDocument((e) => {
190 // if (URI.equal(e.document.uri.toString(), this.fileUri)) {
191 // this.clear(false);
192 // listener.dispose();
193 // }
194 // });
195 } catch (e) {
196 this.clearForFileUri(this.fileUri, false);
197 throw e;
198 }
199 return diffLines;
200 }
201
202 async acceptRejectBlock(
203 accept: boolean,
204 startLine: number,
205 numGreen: number,
206 numRed: number,
207 skipStatusUpdate?: boolean,
208 ) {
209 if (numGreen > 0) {
210 // Delete the editor decoration
211 this.addedLineDecorations.deleteRangeStartingAt(startLine + numRed);
212 if (!accept) {
213 // Delete the actual lines
214 await this.deleteLinesAt(startLine + numRed, numGreen);
215 }
216 }
217
218 if (numRed > 0) {
219 const deleted =
220 this.removedLineDecorations.deleteRangesStartingAt(startLine);
221
222 await this.deleteLinesAt(startLine, numRed);
223 if (deleted && !accept) {
224 await this.insertTextAboveLine(
225 startLine,
226 deleted.map((r) => r.line).join("\n"),
227 );
228 }
229 }
230
231 // Shift everything below upward
232 const offset = -(accept ? numRed : numGreen);
233
234 this.removedLineDecorations.shiftDownAfterLine(startLine, offset);
235 this.addedLineDecorations.shiftDownAfterLine(startLine, offset);
236
237 // Shift the codelens objects
238 this.shiftCodeLensObjects(startLine, offset);
239
240 if (!skipStatusUpdate) {
241 const numDiffs =
242 this.editorToVerticalDiffCodeLens.get(this.fileUri)?.length ?? 0;
243
244 const status = numDiffs === 0 ? "closed" : undefined;
245
246 this.options.onStatusUpdate(
247 status,
248 numDiffs,
249 this.editor.document.getText(),
250 );
251 }
252 }
253
254 public updateLineDelta(
255 fileUri: string,
256 startLine: number,
257 lineDelta: number,
258 ) {
259 // Retrieve the diff blocks for the given file
260 const blocks = this.editorToVerticalDiffCodeLens.get(fileUri);
261 if (!blocks) {
262 return;
263 }
264
265 // Update decorations
266 this.removedLineDecorations.shiftDownAfterLine(startLine, lineDelta);
267 this.addedLineDecorations.shiftDownAfterLine(startLine, lineDelta);
268
269 // Update code lens
270 this.shiftCodeLensObjects(startLine, lineDelta);
271 }
272
273 public hasDiffForCurrentFile(): boolean {
274 const diffBlocks = this.editorToVerticalDiffCodeLens.get(this.fileUri);
275 return diffBlocks !== undefined && diffBlocks.length > 0;
276 }
277
278 clearDecorations() {
279 this.removedLineDecorations.clear();
280 this.addedLineDecorations.clear();
281 this.clearIndexLineDecorations();
282 this.editorToVerticalDiffCodeLens.delete(this.fileUri);
283 this.refreshCodeLens();
284 }
285
286 /**
287 * This method is used to apply diff decorations after the intiial stream.
288 * This is to handle scenarios where we miscalculate the original diff blocks,
289 * and decide to follow up with a deterministic algorithm like Myers Diff once
290 * we have received all of the diff lines.
291 */
292 async reapplyWithMyersDiff(diffLines: DiffLine[]) {
293 // Diff is messed up without this delay.
294 await new Promise((resolve) => setTimeout(resolve, 100));
295
296 // First, we reset the original diff by rejecting all pending diff blocks
297 const blocks = this.editorToVerticalDiffCodeLens.get(this.fileUri) ?? [];
298 for (const block of blocks.reverse()) {
299 await this.acceptRejectBlock(
300 false,
301 block.start,
302 block.numGreen,
303 block.numRed,
304 true,
305 );
306 }
307
308 this.clearDecorations();
309
310 // Then, get our old/new file content based on the original lines
311 // We need the input to be "newline terminated" rather than
312 // newline separated, because myersDiff() would consider
313 // ["A"] => "A" and ["A", ""] => "A\n" to be the same single line.
314 // "A\n" and "A\n\n" are unambiguous.
315 const oldFileContent =
316 diffLines
317 .filter((line) => line.type === "same" || line.type === "old")
318 .map((line) => line.line)
319 .join("\n") + "\n";
320
321 const newFileContent =
322 diffLines
323 .filter((line) => line.type === "same" || line.type === "new")
324 .map((line) => line.line)
325 .join("\n") + "\n";
326
327 const myersDiffs = myersDiff(oldFileContent, newFileContent);
328
329 const replaceContent = myersDiffs
330 .map((diff) => (diff.type === "old" ? "" : diff.line))
331 .join("\n");
332
333 // Then, we insert our diff lines
334 await this.editor.edit((editBuilder) => {
335 editBuilder.replace(this.range, replaceContent),
336 {
337 undoStopAfter: false,
338 undoStopBefore: false,
339 };
340 });
341
342 // Lastly, we apply decorations
343 let numRed = 0;
344 let numGreen = 0;
345
346 const codeLensBlocks: VerticalDiffCodeLens[] = [];
347
348 myersDiffs.forEach((diff, index) => {
349 if (diff.type === "old") {
350 this.removedLineDecorations.addLine(this.startLine + index, diff.line);
351 numRed++;
352 } else if (diff.type === "new") {
353 this.addedLineDecorations.addLine(this.startLine + index);
354 numGreen++;
355 } else if (diff.type === "same" && (numRed > 0 || numGreen > 0)) {
356 codeLensBlocks.push({
357 numRed,
358 numGreen,
359 start: this.startLine + index - numRed - numGreen,
360 });
361 numRed = 0;
362 numGreen = 0;
363 }
364 });
365
366 if (numRed > 0 || numGreen > 0) {
367 codeLensBlocks.push({
368 numGreen,
369 numRed,
370 start: this.startLine + myersDiffs.length - numRed - numGreen,
371 });
372 }
373
374 this.editorToVerticalDiffCodeLens.set(this.fileUri, codeLensBlocks);
375 this.refreshCodeLens();
376 }
377
378 private async insertDeletionBuffer() {
379 if (this.deletionBuffer.length || this.insertedInCurrentBlock > 0) {
380 const blocks = this.editorToVerticalDiffCodeLens.get(this.fileUri) || [];
381
382 blocks.push({
383 start: this.currentLineIndex - this.insertedInCurrentBlock,
384 numRed: this.deletionBuffer.length,
385 numGreen: this.insertedInCurrentBlock,
386 });
387
388 this.editorToVerticalDiffCodeLens.set(this.fileUri, blocks);
389 }
390
391 if (this.deletionBuffer.length === 0) {
392 this.insertedInCurrentBlock = 0;
393 return;
394 }
395
396 // Insert the block of deleted lines as empty new lines
397 await this.insertTextAboveLine(
398 this.currentLineIndex - this.insertedInCurrentBlock,
399 "\n".repeat(this.deletionBuffer.length - 1),
400 );
401
402 this.removedLineDecorations.addLines(
403 this.currentLineIndex - this.insertedInCurrentBlock,
404 this.deletionBuffer,
405 );
406
407 // Shift green decorations downward
408 this.addedLineDecorations.shiftDownAfterLine(
409 this.currentLineIndex - this.insertedInCurrentBlock,
410 this.deletionBuffer.length,
411 );
412
413 // Update line index, clear buffer
414 for (let i = 0; i < this.deletionBuffer.length; i++) {
415 this.incrementCurrentLineIndex();
416 }
417
418 this.deletionBuffer = [];
419 this.insertedInCurrentBlock = 0;
420 this.refreshCodeLens();
421 }
422
423 private incrementCurrentLineIndex() {
424 this.currentLineIndex++;
425 this.updateIndexLineDecorations();
426 const range = new vscode.Range(this.currentLineIndex, 0, this.currentLineIndex, 0);
427 this.editor.revealRange(
428 range,
429 vscode.TextEditorRevealType.Default,
430 );
431 }
432
433 private async insertTextAboveLine(index: number, text: string) {
434 await this.editor.edit(
435 (editBuilder) => {
436 const lineCount = this.editor.document.lineCount;
437 if (index >= lineCount) {
438 // Append to end of file
439 editBuilder.insert(
440 new vscode.Position(
441 lineCount,
442 this.editor.document.lineAt(lineCount - 1).text.length,
443 ),
444 `\n${text}`,
445 );
446 } else {
447 editBuilder.insert(new vscode.Position(index, 0), `${text}\n`);
448 }
449 },
450 {
451 undoStopAfter: false,
452 undoStopBefore: false,
453 },
454 );
455 }
456
457 private async insertLineAboveIndex(index: number, line: string) {
458 await this.insertTextAboveLine(index, line);
459 this.addedLineDecorations.addLine(index);
460 this.newLinesAdded++;
461 }
462
463 private async deleteLinesAt(index: number, numLines = 1) {
464 const startLine = new vscode.Position(index, 0);
465 await this.editor.edit(
466 (editBuilder) => {
467 editBuilder.delete(
468 new vscode.Range(startLine, startLine.translate(numLines)),
469 );
470 },
471 {
472 undoStopAfter: false,
473 undoStopBefore: false,
474 },
475 );
476 }
477
478 private async deleteRangeLines(ranges: vscode.Range[]) {
479 await this.editor.edit(
480 (editBuilder) => {
481 for (const range of ranges) {
482 editBuilder.delete(
483 new vscode.Range(
484 range.start,
485 new vscode.Position(range.end.line + 1, 0),
486 ),
487 );
488 }
489 },
490 {
491 undoStopAfter: false,
492 undoStopBefore: false,
493 },
494 );
495 }
496
497 private updateIndexLineDecorations() {
498 if (this.options.instant) {
499 // We don't show progress on instant apply
500 return;
501 }
502
503 // Highlight the line at the currentLineIndex
504 // And lightly highlight all lines between that and endLine
505 if (this.currentLineIndex - this.newLinesAdded >= this.endLine) {
506 this.editor.setDecorations(indexDecorationType, []);
507 this.editor.setDecorations(belowIndexDecorationType, []);
508 } else {
509 const start = new vscode.Position(this.currentLineIndex, 0);
510 this.editor.setDecorations(indexDecorationType, [
511 new vscode.Range(
512 start,
513 new vscode.Position(start.line, Number.MAX_SAFE_INTEGER),
514 ),
515 ]);
516 const end = new vscode.Position(this.endLine, 0);
517 this.editor.setDecorations(belowIndexDecorationType, [
518 new vscode.Range(start.translate(1), end.translate(this.newLinesAdded)),
519 ]);
520 }
521 }
522
523 private clearIndexLineDecorations() {
524 this.editor.setDecorations(belowIndexDecorationType, []);
525 this.editor.setDecorations(indexDecorationType, []);
526 }
527
528 private async _handleDiffLine(diffLine: DiffLine) {
529 switch (diffLine.type) {
530 case "same":
531 await this.insertDeletionBuffer();
532 this.incrementCurrentLineIndex();
533 break;
534 case "old":
535 // Add to deletion buffer and delete the line for now
536 this.deletionBuffer.push(diffLine.line);
537 await this.deleteLinesAt(this.currentLineIndex);
538 break;
539 case "new":
540 await this.insertLineAboveIndex(this.currentLineIndex, diffLine.line);
541 this.incrementCurrentLineIndex();
542 this.insertedInCurrentBlock++;
543 break;
544 }
545 }
546
547 private shiftCodeLensObjects(startLine: number, offset: number) {
548 // Shift the codelens objects
549 const blocks =
550 this.editorToVerticalDiffCodeLens
551 .get(this.fileUri)
552 ?.filter((x) => x.start !== startLine)
553 .map((x) => {
554 if (x.start > startLine) {
555 return { ...x, start: x.start + offset };
556 }
557 return x;
558 }) || [];
559 this.editorToVerticalDiffCodeLens.set(this.fileUri, blocks);
560
561 this.refreshCodeLens();
562 }
563}