✨ codelens to accept/reject vertical diff

This commit is contained in:
Nate Sesti 2024-01-01 14:47:33 -05:00
parent 3e3be61a2b
commit 1f6ff7f222
5 changed files with 257 additions and 75 deletions

View file

@ -6,7 +6,11 @@ import * as vscode from "vscode";
import { ideProtocolClient } from "./activation/activate";
import { debugPanelWebview, getSidebarContent } from "./debugPanel";
import { acceptDiffCommand, rejectDiffCommand } from "./diff/horizontal";
import { streamEdit } from "./diff/verticalPerLine/manager";
import {
editorToVerticalDiffCodeLens,
streamEdit,
verticalPerLineDiffManager,
} from "./diff/verticalPerLine/manager";
function addHighlightedCodeToContext(edit: boolean) {
const editor = vscode.window.activeTextEditor;
@ -75,10 +79,48 @@ async function addEntireFileToContext(filepath: vscode.Uri, edit: boolean) {
});
}
function acceptRejectVerticalDiffBlock(
accept: boolean,
filepath?: string,
index?: number
) {
if (!filepath) {
const activeEditor = vscode.window.activeTextEditor;
if (!activeEditor) {
return;
}
filepath = activeEditor.document.uri.fsPath;
}
if (typeof index === "undefined") {
index = 0;
}
let blocks = editorToVerticalDiffCodeLens.get(filepath);
const block = blocks?.[index];
if (!blocks || !block) {
return;
}
const handler = verticalPerLineDiffManager.getHandlerForFile(filepath);
if (!handler) {
return;
}
// CodeLens object removed from editorToVerticalDiffCodeLens here
handler.acceptRejectBlock(accept, block.start, block.numGreen, block.numRed);
}
// Copy everything over from extension.ts
const commandsMap: { [command: string]: (...args: any) => any } = {
"continue.acceptDiff": acceptDiffCommand,
"continue.rejectDiff": rejectDiffCommand,
"continue.acceptVerticalDiffBlock": (filepath?: string, index?: number) => {
acceptRejectVerticalDiffBlock(true, filepath, index);
},
"continue.rejectVerticalDiffBlock": (filepath?: string, index?: number) => {
acceptRejectVerticalDiffBlock(false, filepath, index);
},
"continue.quickFix": async (message: string, code: string, edit: boolean) => {
ideProtocolClient.sendMainUserInput(
`${

View file

@ -95,4 +95,12 @@ export class DecorationTypeRangeManager {
}
this.editor.setDecorations(this.decorationType, this.ranges);
}
deleteRangeStartingAt(line: number) {
for (let i = 0; i < this.ranges.length; i++) {
if (this.ranges[i].start.line === line) {
return this.ranges.splice(i, 1)[0];
}
}
}
}

View file

@ -7,6 +7,7 @@ import {
indexDecorationType,
redDecorationType,
} from "./decorations";
import { editorToVerticalDiffCodeLens } from "./manager";
export class VerticalPerLineDiffHandler {
private editor: vscode.TextEditor;
@ -33,31 +34,8 @@ export class VerticalPerLineDiffHandler {
);
}
clear(accept: boolean) {
const rangesToDelete = accept
? this.redDecorationManager.getRanges()
: this.greenDecorationManager.getRanges();
this.redDecorationManager.clear();
this.greenDecorationManager.clear();
this.clearIndexLineDecorations();
this.editor.edit((editBuilder) => {
for (const range of rangesToDelete) {
editBuilder.delete(
new vscode.Range(
range.start,
new vscode.Position(range.end.line + 1, 0)
)
);
}
});
this.cancelled = true;
}
get isCancelled() {
return this.cancelled;
private get filepath() {
return this.editor.document.uri.fsPath;
}
private deletionBuffer: string[] = [];
@ -65,21 +43,32 @@ export class VerticalPerLineDiffHandler {
insertedInCurrentBlock = 0;
private async insertDeletionBuffer() {
// Don't remove trailing whitespace line
const totalDeletedContent = this.deletionBuffer.join("\n");
if (
totalDeletedContent === "" &&
this.currentLineIndex >= this.endLine + this.newLinesAdded &&
this.insertedInCurrentBlock === 0
) {
return;
}
if (this.deletionBuffer.length || this.insertedInCurrentBlock > 0) {
const blocks = editorToVerticalDiffCodeLens.get(this.filepath) || [];
blocks.push({
start: this.currentLineIndex - this.insertedInCurrentBlock,
numRed: this.deletionBuffer.length,
numGreen: this.insertedInCurrentBlock,
});
editorToVerticalDiffCodeLens.set(this.filepath, blocks);
}
if (this.deletionBuffer.length === 0) {
this.insertedInCurrentBlock = 0;
return;
}
// Insert the block of deleted lines
const totalDeletedContent = this.deletionBuffer.join("\n");
// Don't remove trailing whitespace line
if (
totalDeletedContent === "" &&
this.currentLineIndex >= this.endLine + this.newLinesAdded
) {
return;
}
await this.insertTextAboveLine(
this.currentLineIndex - this.insertedInCurrentBlock,
totalDeletedContent
@ -102,42 +91,6 @@ export class VerticalPerLineDiffHandler {
this.insertedInCurrentBlock = 0;
}
async handleDiffLine(diffLine: DiffLine) {
switch (diffLine.type) {
case "same":
await this.insertDeletionBuffer();
this.incrementCurrentLineIndex();
break;
case "old":
// Add to deletion buffer and delete the line for now
this.deletionBuffer.push(diffLine.line);
await this.deleteLineAt(this.currentLineIndex);
break;
case "new":
await this.insertLineAboveIndex(this.currentLineIndex, diffLine.line);
this.incrementCurrentLineIndex();
this.insertedInCurrentBlock++;
break;
}
}
async run(diffLineGenerator: AsyncGenerator<DiffLine>) {
// As an indicator of loading
this.updateIndexLineDecorations();
for await (let diffLine of diffLineGenerator) {
if (this.isCancelled) {
return;
}
await this.handleDiffLine(diffLine);
}
// Clear deletion buffer (deletion of end of range)
if (this.deletionBuffer.length) {
await this.insertDeletionBuffer();
}
}
private incrementCurrentLineIndex() {
this.currentLineIndex++;
this.updateIndexLineDecorations();
@ -151,16 +104,18 @@ export class VerticalPerLineDiffHandler {
});
}
async insertLineAboveIndex(index: number, line: string) {
private async insertLineAboveIndex(index: number, line: string) {
await this.insertTextAboveLine(index, line);
this.greenDecorationManager.addLine(index);
this.newLinesAdded++;
}
async deleteLineAt(index: number) {
const line = new vscode.Position(index, 0);
private async deleteLinesAt(index: number, numLines: number = 1) {
const startLine = new vscode.Position(index, 0);
await this.editor.edit((editBuilder) => {
editBuilder.delete(new vscode.Range(line, line.translate(1)));
editBuilder.delete(
new vscode.Range(startLine, startLine.translate(numLines))
);
});
}
@ -189,4 +144,111 @@ export class VerticalPerLineDiffHandler {
this.editor.setDecorations(belowIndexDecorationType, []);
this.editor.setDecorations(indexDecorationType, []);
}
clear(accept: boolean) {
const rangesToDelete = accept
? this.redDecorationManager.getRanges()
: this.greenDecorationManager.getRanges();
this.redDecorationManager.clear();
this.greenDecorationManager.clear();
this.clearIndexLineDecorations();
editorToVerticalDiffCodeLens.delete(this.filepath);
this.editor.edit((editBuilder) => {
for (const range of rangesToDelete) {
editBuilder.delete(
new vscode.Range(
range.start,
new vscode.Position(range.end.line + 1, 0)
)
);
}
});
this.cancelled = true;
}
get isCancelled() {
return this.cancelled;
}
async handleDiffLine(diffLine: DiffLine) {
switch (diffLine.type) {
case "same":
await this.insertDeletionBuffer();
this.incrementCurrentLineIndex();
break;
case "old":
// Add to deletion buffer and delete the line for now
this.deletionBuffer.push(diffLine.line);
await this.deleteLinesAt(this.currentLineIndex);
break;
case "new":
await this.insertLineAboveIndex(this.currentLineIndex, diffLine.line);
this.incrementCurrentLineIndex();
this.insertedInCurrentBlock++;
break;
}
}
async run(diffLineGenerator: AsyncGenerator<DiffLine>) {
// As an indicator of loading
this.updateIndexLineDecorations();
for await (let diffLine of diffLineGenerator) {
if (this.isCancelled) {
return;
}
await this.handleDiffLine(diffLine);
}
// Clear deletion buffer
await this.insertDeletionBuffer();
}
async acceptRejectBlock(
accept: boolean,
startLine: number,
numGreen: number,
numRed: number
) {
if (numGreen > 0) {
// Delete the editor decoration
this.greenDecorationManager.deleteRangeStartingAt(startLine + numRed);
if (!accept) {
// Delete the actual lines
await this.deleteLinesAt(startLine + numRed, numGreen);
}
}
if (numRed > 0) {
const rangeToDelete =
this.redDecorationManager.deleteRangeStartingAt(startLine);
if (accept) {
// Delete the actual lines
await this.deleteLinesAt(startLine, numRed);
}
}
// Shift everything below upward
const offset = -(accept ? numRed : numGreen);
this.redDecorationManager.shiftDownAfterLine(startLine, offset);
this.greenDecorationManager.shiftDownAfterLine(startLine, offset);
// Shift the codelens objects
const blocks =
editorToVerticalDiffCodeLens
.get(this.filepath)
?.filter((x) => x.start !== startLine)
.map((x) => {
if (x.start > startLine) {
return { ...x, start: x.start + offset };
}
return x;
}) || [];
editorToVerticalDiffCodeLens.set(this.filepath, blocks);
}
}

View file

@ -30,6 +30,10 @@ class VerticalPerLineDiffManager {
}
}
getHandlerForFile(filepath: string) {
return this.filepathToEditorMap.get(filepath);
}
clearForFilepath(filepath: string | undefined, accept: boolean) {
if (!filepath) {
const activeEditor = vscode.window.activeTextEditor;
@ -83,3 +87,12 @@ export async function streamEdit(input: string) {
await diffHandler.run(streamDiffLines(rangeContent, llm, input));
}
}
export interface VerticalDiffCodeLens {
start: number;
numRed: number;
numGreen: number;
}
export const editorToVerticalDiffCodeLens: Map<string, VerticalDiffCodeLens[]> =
new Map();

View file

@ -2,9 +2,56 @@ import * as os from "os";
import * as path from "path";
import * as vscode from "vscode";
import { DIFF_DIRECTORY, diffManager } from "../diff/horizontal";
import { editorToVerticalDiffCodeLens } from "../diff/verticalPerLine/manager";
import { editorSuggestionsLocked, editorToSuggestions } from "../suggestions";
import { getMetaKeyLabel } from "../util/util";
import { getExtensionUri } from "../util/vscode";
class VerticalPerLineCodeLensProvider implements vscode.CodeLensProvider {
public provideCodeLenses(
document: vscode.TextDocument,
_: vscode.CancellationToken
): vscode.CodeLens[] | Thenable<vscode.CodeLens[]> {
const filepath = document.uri.fsPath;
const blocks = editorToVerticalDiffCodeLens.get(filepath);
if (!blocks) {
return [];
}
const codeLenses: vscode.CodeLens[] = [];
for (let i = 0; i < blocks.length; i++) {
const block = blocks[i];
const start = new vscode.Position(block.start, 0);
const range = new vscode.Range(
start,
start.translate(block.numGreen + block.numRed)
);
codeLenses.push(
new vscode.CodeLens(range, {
title: "Accept ✅",
command: "continue.acceptVerticalDiffBlock",
arguments: [filepath, i],
}),
new vscode.CodeLens(range, {
title: "Reject ❌",
command: "continue.rejectVerticalDiffBlock",
arguments: [filepath, i],
})
);
if (codeLenses.length === 2) {
codeLenses.push(
new vscode.CodeLens(range, {
title: `(${getMetaKeyLabel()}⇧↩/${getMetaKeyLabel()}⇧⌫ to accept/reject all)`,
command: "",
})
);
}
}
return codeLenses;
}
}
class SuggestionsCodeLensProvider implements vscode.CodeLensProvider {
public provideCodeLenses(
document: vscode.TextDocument,
@ -281,12 +328,16 @@ class TutorialCodeLensProvider implements vscode.CodeLensProvider {
}
}
let verticalPerLineCodeLensProvider: vscode.Disposable | undefined = undefined;
let diffsCodeLensDisposable: vscode.Disposable | undefined = undefined;
let suggestionsCodeLensDisposable: vscode.Disposable | undefined = undefined;
let configPyCodeLensDisposable: vscode.Disposable | undefined = undefined;
let tutorialCodeLensDisposable: vscode.Disposable | undefined = undefined;
export function registerAllCodeLensProviders(context: vscode.ExtensionContext) {
if (verticalPerLineCodeLensProvider) {
verticalPerLineCodeLensProvider.dispose();
}
if (suggestionsCodeLensDisposable) {
suggestionsCodeLensDisposable.dispose();
}
@ -299,6 +350,11 @@ export function registerAllCodeLensProviders(context: vscode.ExtensionContext) {
if (tutorialCodeLensDisposable) {
tutorialCodeLensDisposable.dispose();
}
verticalPerLineCodeLensProvider = vscode.languages.registerCodeLensProvider(
"*",
new VerticalPerLineCodeLensProvider()
);
suggestionsCodeLensDisposable = vscode.languages.registerCodeLensProvider(
"*",
new SuggestionsCodeLensProvider()
@ -315,6 +371,7 @@ export function registerAllCodeLensProviders(context: vscode.ExtensionContext) {
"*",
new TutorialCodeLensProvider()
);
context.subscriptions.push(verticalPerLineCodeLensProvider);
context.subscriptions.push(suggestionsCodeLensDisposable);
context.subscriptions.push(diffsCodeLensDisposable);
context.subscriptions.push(configPyCodeLensDisposable);