Elffuss BraidHub

kikocis/continue public

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