Elffuss BraidHub

kikocis/continue public

6ae8fdd230bd · 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 { VerticalDiffCodeLens } from "./manager";
13import type { ApplyState, DiffLine } from "core";
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(range, vscode.TextEditorRevealType.Default);
178
179 this.options.onStatusUpdate(
180 "done",
181 this.editorToVerticalDiffCodeLens.get(this.fileUri)?.length ?? 0,
182 this.editor.document.getText(),
183 );
184
185 // Reject on user typing
186 // const listener = vscode.workspace.onDidChangeTextDocument((e) => {
187 // if (URI.equal(e.document.uri.toString(), this.fileUri)) {
188 // this.clear(false);
189 // listener.dispose();
190 // }
191 // });
192 } catch (e) {
193 this.clearForFileUri(this.fileUri, false);
194 throw e;
195 }
196 return diffLines;
197 }
198
199 async acceptRejectBlock(
200 accept: boolean,
201 startLine: number,
202 numGreen: number,
203 numRed: number,
204 skipStatusUpdate?: boolean,
205 ) {
206 if (numGreen > 0) {
207 // Delete the editor decoration
208 this.addedLineDecorations.deleteRangeStartingAt(startLine + numRed);
209 if (!accept) {
210 // Delete the actual lines
211 await this.deleteLinesAt(startLine + numRed, numGreen);
212 }
213 }
214
215 if (numRed > 0) {
216 const deleted =
217 this.removedLineDecorations.deleteRangesStartingAt(startLine);
218
219 await this.deleteLinesAt(startLine, numRed);
220 if (deleted && !accept) {
221 await this.insertTextAboveLine(
222 startLine,
223 deleted.map((r) => r.line).join("\n"),
224 );
225 }
226 }
227
228 // Shift everything below upward
229 const offset = -(accept ? numRed : numGreen);
230
231 this.removedLineDecorations.shiftDownAfterLine(startLine, offset);
232 this.addedLineDecorations.shiftDownAfterLine(startLine, offset);
233
234 // Shift the codelens objects
235 this.shiftCodeLensObjects(startLine, offset);
236
237 if (!skipStatusUpdate) {
238 const numDiffs =
239 this.editorToVerticalDiffCodeLens.get(this.fileUri)?.length ?? 0;
240
241 const status = numDiffs === 0 ? "closed" : undefined;
242
243 this.options.onStatusUpdate(
244 status,
245 numDiffs,
246 this.editor.document.getText(),
247 );
248 }
249 }
250
251 public updateLineDelta(
252 fileUri: string,
253 startLine: number,
254 lineDelta: number,
255 ) {
256 // Retrieve the diff blocks for the given file
257 const blocks = this.editorToVerticalDiffCodeLens.get(fileUri);
258 if (!blocks) {
259 return;
260 }
261
262 // Update decorations
263 this.removedLineDecorations.shiftDownAfterLine(startLine, lineDelta);
264 this.addedLineDecorations.shiftDownAfterLine(startLine, lineDelta);
265
266 // Update code lens
267 this.shiftCodeLensObjects(startLine, lineDelta);
268 }
269
270 public hasDiffForCurrentFile(): boolean {
271 const diffBlocks = this.editorToVerticalDiffCodeLens.get(this.fileUri);
272 return diffBlocks !== undefined && diffBlocks.length > 0;
273 }
274
275 clearDecorations() {
276 this.removedLineDecorations.clear();
277 this.addedLineDecorations.clear();
278 this.clearIndexLineDecorations();
279 this.editorToVerticalDiffCodeLens.delete(this.fileUri);
280 this.refreshCodeLens();
281 }
282
283 /**
284 * This method is used to apply diff decorations after the intiial stream.
285 * This is to handle scenarios where we miscalculate the original diff blocks,
286 * and decide to follow up with a deterministic algorithm like Myers Diff once
287 * we have received all of the diff lines.
288 */
289 async reapplyWithMyersDiff(diffLines: DiffLine[]) {
290 // Diff is messed up without this delay.
291 await new Promise((resolve) => setTimeout(resolve, 100));
292
293 // First, we reset the original diff by rejecting all pending diff blocks
294 const blocks = this.editorToVerticalDiffCodeLens.get(this.fileUri) ?? [];
295 for (const block of blocks.reverse()) {
296 await this.acceptRejectBlock(
297 false,
298 block.start,
299 block.numGreen,
300 block.numRed,
301 true,
302 );
303 }
304
305 this.clearDecorations();
306
307 // Then, get our old/new file content based on the original lines
308 // We need the input to be "newline terminated" rather than
309 // newline separated, because myersDiff() would consider
310 // ["A"] => "A" and ["A", ""] => "A\n" to be the same single line.
311 // "A\n" and "A\n\n" are unambiguous.
312 const oldFileContent =
313 diffLines
314 .filter((line) => line.type === "same" || line.type === "old")
315 .map((line) => line.line)
316 .join("\n") + "\n";
317
318 const newFileContent =
319 diffLines
320 .filter((line) => line.type === "same" || line.type === "new")
321 .map((line) => line.line)
322 .join("\n") + "\n";
323
324 const myersDiffs = myersDiff(oldFileContent, newFileContent);
325
326 const replaceContent = myersDiffs
327 .map((diff) => (diff.type === "old" ? "" : diff.line))
328 .join("\n");
329
330 // Then, we insert our diff lines
331 await this.editor.edit((editBuilder) => {
332 editBuilder.replace(this.range, replaceContent),
333 {
334 undoStopAfter: false,
335 undoStopBefore: false,
336 };
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 {
450 undoStopAfter: false,
451 undoStopBefore: false,
452 },
453 );
454 }
455
456 private async insertLineAboveIndex(index: number, line: string) {
457 await this.insertTextAboveLine(index, line);
458 this.addedLineDecorations.addLine(index);
459 this.newLinesAdded++;
460 }
461
462 private async deleteLinesAt(index: number, numLines = 1) {
463 const startLine = new vscode.Position(index, 0);
464 await this.editor.edit(
465 (editBuilder) => {
466 editBuilder.delete(
467 new vscode.Range(startLine, startLine.translate(numLines)),
468 );
469 },
470 {
471 undoStopAfter: false,
472 undoStopBefore: false,
473 },
474 );
475 }
476
477 private async deleteRangeLines(ranges: vscode.Range[]) {
478 await this.editor.edit(
479 (editBuilder) => {
480 for (const range of ranges) {
481 editBuilder.delete(
482 new vscode.Range(
483 range.start,
484 new vscode.Position(range.end.line + 1, 0),
485 ),
486 );
487 }
488 },
489 {
490 undoStopAfter: false,
491 undoStopBefore: false,
492 },
493 );
494 }
495
496 private updateIndexLineDecorations() {
497 if (this.options.instant) {
498 // We don't show progress on instant apply
499 return;
500 }
501
502 // Highlight the line at the currentLineIndex
503 // And lightly highlight all lines between that and endLine
504 if (this.currentLineIndex - this.newLinesAdded >= this.endLine) {
505 this.editor.setDecorations(indexDecorationType, []);
506 this.editor.setDecorations(belowIndexDecorationType, []);
507 } else {
508 const start = new vscode.Position(this.currentLineIndex, 0);
509 this.editor.setDecorations(indexDecorationType, [
510 new vscode.Range(
511 start,
512 new vscode.Position(start.line, Number.MAX_SAFE_INTEGER),
513 ),
514 ]);
515 const end = new vscode.Position(this.endLine, 0);
516 this.editor.setDecorations(belowIndexDecorationType, [
517 new vscode.Range(start.translate(1), end.translate(this.newLinesAdded)),
518 ]);
519 }
520 }
521
522 private clearIndexLineDecorations() {
523 this.editor.setDecorations(belowIndexDecorationType, []);
524 this.editor.setDecorations(indexDecorationType, []);
525 }
526
527 private async _handleDiffLine(diffLine: DiffLine) {
528 switch (diffLine.type) {
529 case "same":
530 await this.insertDeletionBuffer();
531 this.incrementCurrentLineIndex();
532 break;
533 case "old":
534 // Add to deletion buffer and delete the line for now
535 this.deletionBuffer.push(diffLine.line);
536 await this.deleteLinesAt(this.currentLineIndex);
537 break;
538 case "new":
539 await this.insertLineAboveIndex(this.currentLineIndex, diffLine.line);
540 this.incrementCurrentLineIndex();
541 this.insertedInCurrentBlock++;
542 break;
543 }
544 }
545
546 private shiftCodeLensObjects(startLine: number, offset: number) {
547 // Shift the codelens objects
548 const blocks =
549 this.editorToVerticalDiffCodeLens
550 .get(this.fileUri)
551 ?.filter((x) => x.start !== startLine)
552 .map((x) => {
553 if (x.start > startLine) {
554 return { ...x, start: x.start + offset };
555 }
556 return x;
557 }) || [];
558 this.editorToVerticalDiffCodeLens.set(this.fileUri, blocks);
559
560 this.refreshCodeLens();
561 }
562}