💄 more vertical diff improvements

This commit is contained in:
Nate Sesti 2023-12-30 17:37:25 -05:00
parent a1c5513f60
commit 824e111efb
4 changed files with 59 additions and 49 deletions

View file

@ -1,8 +1,8 @@
import { ContextItemWithId, DiffLine, ILLM, SlashCommand } from "../..";
import { streamDiff } from "../../diff/diffLines";
import { streamLines } from "../../diff/util";
import { LineStream, streamLines } from "../../diff/util";
import { gptEditPrompt } from "../../llm/templates/edit";
import { renderPromptTemplate } from "../../util";
import { dedentAndGetCommonWhitespace, renderPromptTemplate } from "../../util";
import {
RangeInFileWithContents,
contextItemToRangeInFileWithContents,
@ -12,9 +12,7 @@ function shouldRemoveLineBeforeStart(line: string): boolean {
return line.startsWith("```");
}
async function* filterLines(
rawLines: AsyncGenerator<string>
): AsyncGenerator<string> {
async function* filterLines(rawLines: LineStream): LineStream {
let seenValidLine = false;
let waitingToSeeIfLineIsLast = undefined;
@ -43,28 +41,42 @@ async function* filterLines(
}
}
function constructPrompt(oldLines: string[], llm: ILLM, input: string): string {
function constructPrompt(
codeToEdit: string,
llm: ILLM,
userInput: string
): string {
const template = llm.promptTemplates?.edit ?? gptEditPrompt;
const rendered = renderPromptTemplate(template, [], {
userInput: input,
codeToEdit: oldLines.join("\n"),
userInput,
codeToEdit,
});
return typeof rendered === "string"
? rendered
: rendered[rendered.length - 1].content;
}
export function streamDiffLines(
oldLines: string[],
export async function* streamDiffLines(
oldCode: string,
llm: ILLM,
input: string
): AsyncGenerator<DiffLine> {
const prompt = constructPrompt(oldLines, llm, input);
// Strip common indentation for the LLM, then add back after generation
const [withoutIndentation, commonIndentation] =
dedentAndGetCommonWhitespace(oldCode);
oldCode = withoutIndentation;
const prompt = constructPrompt(oldCode, llm, input);
const completion = llm.streamComplete(prompt);
const newLines = filterLines(streamLines(completion));
const diffLineGenerator = streamDiff(oldLines, newLines);
return diffLineGenerator;
const diffLineGenerator = streamDiff(oldCode.split("\n"), newLines);
for await (const diffLine of diffLineGenerator) {
yield {
...diffLine,
line: commonIndentation + diffLine.line,
};
}
}
const VerticalEditSlashCommand: SlashCommand = {
@ -83,12 +95,11 @@ const VerticalEditSlashCommand: SlashCommand = {
const rif: RangeInFileWithContents =
contextItemToRangeInFileWithContents(contextItemToEdit);
const oldLines = rif.contents.split("\n");
const startLine = rif.range.start.line;
const endLine = rif.range.end.line;
const filepath = rif.filepath;
const diffLineGenerator = streamDiffLines(oldLines, llm, input);
const diffLineGenerator = streamDiffLines(rif.contents, llm, input);
for await (const diffLine of diffLineGenerator) {
await ide.verticalDiffUpdate(filepath, startLine, endLine, diffLine);

View file

@ -1,19 +1,21 @@
import { DiffLine } from "..";
import { matchLine } from "./util";
import { LineStream, matchLine } from "./util";
/**
* https://blog.jcoglan.com/2017/02/12/the-myers-diff-algorithm-part-1/
*/
export async function* streamDiff(
oldLines: string[],
newLines: AsyncGenerator<string>
newLines: LineStream
): AsyncGenerator<DiffLine> {
oldLines = [...oldLines]; // be careful
let newLineResult = await newLines.next();
while (oldLines.length > 0 && !newLineResult.done) {
const newLine = newLineResult.value;
const [matchIndex, isPerfectMatch] = matchLine(newLine, oldLines);
let newLine = newLineResult.value;
const [matchIndex, isPerfectMatch, newLineWithCorrectIndentation] =
matchLine(newLine, oldLines);
newLine = newLineWithCorrectIndentation;
if (matchIndex < 0) {
yield { type: "new", line: newLine };

View file

@ -1,7 +1,9 @@
import { distance } from "fastest-levenshtein";
export type LineStream = AsyncGenerator<string>;
function linesMatchPerfectly(lineA: string, lineB: string): boolean {
return lineA === lineB;
return lineA === lineB && lineA !== "";
}
function linesMatch(lineA: string, lineB: string): boolean {
@ -15,28 +17,31 @@ function linesMatch(lineA: string, lineB: string): boolean {
/**
* Return the index of the first match and whether it is a perfect match
* Also return a version of the line with correct indentation if needs fixing
*/
export function matchLine(
newLine: string,
oldLines: string[]
): [number, boolean] {
): [number, boolean, string] {
for (let i = 0; i < oldLines.length; i++) {
if (linesMatchPerfectly(newLine, oldLines[i])) {
return [i, true];
return [i, true, newLine];
} else if (linesMatch(newLine, oldLines[i])) {
return [i, false];
// This is a way to fix indentation, but only for sufficiently long lines to avoid matching whitespace or short lines
if (newLine === oldLines[i].trimStart() && newLine.trim().length > 8) {
return [i, true, oldLines[i]];
}
return [i, false, newLine];
}
}
return [-1, false];
return [-1, false, newLine];
}
/**
* Convert a stream of arbitrary chunks to a stream of lines
*/
export async function* streamLines(
streamCompletion: AsyncGenerator<string>
): AsyncGenerator<string> {
export async function* streamLines(streamCompletion: LineStream): LineStream {
let buffer = "";
for await (const chunk of streamCompletion) {
buffer += chunk;

View file

@ -123,7 +123,7 @@ export class VerticalPerLineDiffHandler {
case "same":
break;
case "old":
this.setLineAtIndexRed(this.currentLineIndex);
this.setLineAtIndexRed(this.currentLineIndex, diffLine.line);
break;
case "new":
await this.insertLineAboveIndex(this.currentLineIndex, diffLine.line);
@ -141,13 +141,9 @@ export class VerticalPerLineDiffHandler {
private redDecorationManager: DecorationTypeRangeManager;
private greenDecorationManager: DecorationTypeRangeManager;
private setLineAtIndexRed(index: number) {
private setLineAtIndexRed(index: number, line: string) {
// Don't remove trailing whitespace line
const editorLines = this.editor.document.getText().split("\n");
if (
index >= editorLines.length &&
editorLines[editorLines.length - 1] === ""
) {
if (line === "" && index >= this.endLine + this.newLinesAdded) {
return;
}
@ -181,7 +177,7 @@ export class VerticalPerLineDiffHandler {
]);
const end = new vscode.Position(this.endLine, 0);
this.editor.setDecorations(belowIndexDecorationType, [
new vscode.Range(start.translate(1), end),
new vscode.Range(start.translate(1), end.translate(this.newLinesAdded)),
]);
}
}
@ -252,8 +248,8 @@ export async function streamEdit(input: string) {
if (diffHandler) {
const selectedRange = new vscode.Range(
editor.selection.start,
editor.selection.end
editor.selection.start.with(undefined, 0),
editor.selection.end.with(undefined, Number.MAX_SAFE_INTEGER)
);
const rangeContent = editor.document.getText(selectedRange);
const llm = await llmFromTitle();
@ -264,21 +260,17 @@ export async function streamEdit(input: string) {
editor.selection.active
);
for await (const diffLine of streamDiffLines(
rangeContent.split("\n"),
llm,
input
)) {
for await (const diffLine of streamDiffLines(rangeContent, llm, input)) {
if (diffHandler.isCancelled) {
break;
}
// console.log(
// (diffLine.type === "new"
// ? "+ "
// : diffLine.type === "old"
// ? "- "
// : " ") + diffLine.line
// );
console.log(
(diffLine.type === "new"
? "+ "
: diffLine.type === "old"
? "- "
: " ") + diffLine.line
);
await diffHandler.handleDiffLine(diffLine);
}
}