Elffuss BraidHub

kikocis/continue public

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