Elffuss BraidHub

kikocis/continue public

cd33d3613239 · 16.0 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 await this.reapplyWithMyersDiff(diffLines);
178
179 const range = new vscode.Range(this.startLine, 0, this.startLine, 0);
180 this.editor.revealRange(range, vscode.TextEditorRevealType.Default);
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 { undoStopAfter: false, undoStopBefore: false };
337 });
338
339 // Lastly, we apply decorations
340 let numRed = 0;
341 let numGreen = 0;
342
343 const codeLensBlocks: VerticalDiffCodeLens[] = [];
344
345 myersDiffs.forEach((diff, index) => {
346 if (diff.type === "old") {
347 this.removedLineDecorations.addLine(this.startLine + index, diff.line);
348 numRed++;
349 } else if (diff.type === "new") {
350 this.addedLineDecorations.addLine(this.startLine + index);
351 numGreen++;
352 } else if (diff.type === "same" && (numRed > 0 || numGreen > 0)) {
353 codeLensBlocks.push({
354 numRed,
355 numGreen,
356 start: this.startLine + index - numRed - numGreen,
357 });
358 numRed = 0;
359 numGreen = 0;
360 }
361 });
362
363 if (numRed > 0 || numGreen > 0) {
364 codeLensBlocks.push({
365 numGreen,
366 numRed,
367 start: this.startLine + myersDiffs.length - numRed - numGreen,
368 });
369 }
370
371 this.editorToVerticalDiffCodeLens.set(this.fileUri, codeLensBlocks);
372 this.refreshCodeLens();
373 }
374
375 private async insertDeletionBuffer() {
376 if (this.deletionBuffer.length || this.insertedInCurrentBlock > 0) {
377 const blocks = this.editorToVerticalDiffCodeLens.get(this.fileUri) || [];
378
379 blocks.push({
380 start: this.currentLineIndex - this.insertedInCurrentBlock,
381 numRed: this.deletionBuffer.length,
382 numGreen: this.insertedInCurrentBlock,
383 });
384
385 this.editorToVerticalDiffCodeLens.set(this.fileUri, blocks);
386 }
387
388 if (this.deletionBuffer.length === 0) {
389 this.insertedInCurrentBlock = 0;
390 return;
391 }
392
393 // Insert the block of deleted lines as empty new lines
394 await this.insertTextAboveLine(
395 this.currentLineIndex - this.insertedInCurrentBlock,
396 "\n".repeat(this.deletionBuffer.length - 1),
397 );
398
399 this.removedLineDecorations.addLines(
400 this.currentLineIndex - this.insertedInCurrentBlock,
401 this.deletionBuffer,
402 );
403
404 // Shift green decorations downward
405 this.addedLineDecorations.shiftDownAfterLine(
406 this.currentLineIndex - this.insertedInCurrentBlock,
407 this.deletionBuffer.length,
408 );
409
410 // Update line index, clear buffer
411 for (let i = 0; i < this.deletionBuffer.length; i++) {
412 this.incrementCurrentLineIndex();
413 }
414
415 this.deletionBuffer = [];
416 this.insertedInCurrentBlock = 0;
417 this.refreshCodeLens();
418 }
419
420 private incrementCurrentLineIndex() {
421 this.currentLineIndex++;
422 this.updateIndexLineDecorations();
423 const range = new vscode.Range(
424 this.currentLineIndex,
425 0,
426 this.currentLineIndex,
427 0,
428 );
429 this.editor.revealRange(range, vscode.TextEditorRevealType.Default);
430 }
431
432 private async insertTextAboveLine(index: number, text: string) {
433 await this.editor.edit(
434 (editBuilder) => {
435 const lineCount = this.editor.document.lineCount;
436 if (index >= lineCount) {
437 // Append to end of file
438 editBuilder.insert(
439 new vscode.Position(
440 lineCount,
441 this.editor.document.lineAt(lineCount - 1).text.length,
442 ),
443 `\n${text}`,
444 );
445 } else {
446 editBuilder.insert(new vscode.Position(index, 0), `${text}\n`);
447 }
448 },
449 { undoStopAfter: false, undoStopBefore: false },
450 );
451 }
452
453 private async insertLineAboveIndex(index: number, line: string) {
454 await this.insertTextAboveLine(index, line);
455 this.addedLineDecorations.addLine(index);
456 this.newLinesAdded++;
457 }
458
459 private async deleteLinesAt(index: number, numLines = 1) {
460 const startLine = new vscode.Position(index, 0);
461 await this.editor.edit(
462 (editBuilder) => {
463 editBuilder.delete(
464 new vscode.Range(startLine, startLine.translate(numLines)),
465 );
466 },
467 { undoStopAfter: false, undoStopBefore: false },
468 );
469 }
470
471 private async deleteRangeLines(ranges: vscode.Range[]) {
472 await this.editor.edit(
473 (editBuilder) => {
474 for (const range of ranges) {
475 editBuilder.delete(
476 new vscode.Range(
477 range.start,
478 new vscode.Position(range.end.line + 1, 0),
479 ),
480 );
481 }
482 },
483 { undoStopAfter: false, undoStopBefore: false },
484 );
485 }
486
487 private updateIndexLineDecorations() {
488 if (this.options.instant) {
489 // We don't show progress on instant apply
490 return;
491 }
492
493 // Highlight the line at the currentLineIndex
494 // And lightly highlight all lines between that and endLine
495 if (this.currentLineIndex - this.newLinesAdded >= this.endLine) {
496 this.editor.setDecorations(indexDecorationType, []);
497 this.editor.setDecorations(belowIndexDecorationType, []);
498 } else {
499 const start = new vscode.Position(this.currentLineIndex, 0);
500 this.editor.setDecorations(indexDecorationType, [
501 new vscode.Range(
502 start,
503 new vscode.Position(start.line, Number.MAX_SAFE_INTEGER),
504 ),
505 ]);
506 const end = new vscode.Position(this.endLine, 0);
507 this.editor.setDecorations(belowIndexDecorationType, [
508 new vscode.Range(start.translate(1), end.translate(this.newLinesAdded)),
509 ]);
510 }
511 }
512
513 private clearIndexLineDecorations() {
514 this.editor.setDecorations(belowIndexDecorationType, []);
515 this.editor.setDecorations(indexDecorationType, []);
516 }
517
518 private async _handleDiffLine(diffLine: DiffLine) {
519 switch (diffLine.type) {
520 case "same":
521 await this.insertDeletionBuffer();
522 this.incrementCurrentLineIndex();
523 break;
524 case "old":
525 // Add to deletion buffer and delete the line for now
526 this.deletionBuffer.push(diffLine.line);
527 await this.deleteLinesAt(this.currentLineIndex);
528 break;
529 case "new":
530 await this.insertLineAboveIndex(this.currentLineIndex, diffLine.line);
531 this.incrementCurrentLineIndex();
532 this.insertedInCurrentBlock++;
533 break;
534 }
535 }
536
537 private shiftCodeLensObjects(startLine: number, offset: number) {
538 // Shift the codelens objects
539 const blocks =
540 this.editorToVerticalDiffCodeLens
541 .get(this.fileUri)
542 ?.filter((x) => x.start !== startLine)
543 .map((x) => {
544 if (x.start > startLine) {
545 return { ...x, start: x.start + offset };
546 }
547 return x;
548 }) || [];
549 this.editorToVerticalDiffCodeLens.set(this.fileUri, blocks);
550
551 this.refreshCodeLens();
552 }
553}