Elffuss BraidHub

kikocis/continue public

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