🚧 more elegant diff algorithm

This commit is contained in:
Nate Sesti 2023-12-29 20:49:38 -05:00
parent 2817efb016
commit b1f6397d4c
8 changed files with 338 additions and 30 deletions

53
core/diff/diffLines.ts Normal file
View file

@ -0,0 +1,53 @@
import { matchLine } from "./util";
interface DiffLineNew {
type: "new";
newLine: string;
}
interface DiffLineOldOrSame {
type: "old" | "same";
}
export type DiffLine = DiffLineNew | DiffLineOldOrSame;
/**
* https://blog.jcoglan.com/2017/02/12/the-myers-diff-algorithm-part-1/
*/
async function* streamDiff(
oldLines: string[],
newLines: AsyncGenerator<string>
): AsyncGenerator<DiffLine> {
let newLineResult = await newLines.next();
while (oldLines.length > 0 && !newLineResult.done) {
const newLine = newLineResult.value;
const [matchIndex, isPerfectMatch] = matchLine(newLine, oldLines);
if (matchIndex < 0) {
yield { type: "new", newLine };
} else {
for (let i = 0; i < matchIndex; i++) {
yield { type: "old" };
}
if (isPerfectMatch) {
yield { type: "same" };
} else {
yield { type: "old" };
yield { type: "new", newLine };
}
}
newLineResult = await newLines.next();
}
// Once at the edge, only one choice
if (newLineResult.done === true && oldLines.length > 0) {
for (let _ of oldLines) {
yield { type: "old" };
}
} else if (!newLineResult.done && oldLines.length === 0) {
for await (const newLine of newLines) {
yield { type: "new", newLine };
}
}
}

47
core/diff/util.ts Normal file
View file

@ -0,0 +1,47 @@
import { distance } from "fastest-levenshtein";
function linesMatchPerfectly(lineA: string, lineB: string): boolean {
return lineA === lineB;
}
function linesMatch(lineA: string, lineB: string): boolean {
return distance(lineA, lineB) / Math.max(lineA.length, lineB.length) < 0.25;
}
/**
* Return the index of the first match and whether it is a perfect match
*/
export function matchLine(
newLine: string,
oldLines: string[]
): [number, boolean] {
for (let i = 0; i < oldLines.length; i++) {
if (linesMatchPerfectly(newLine, oldLines[i])) {
return [i, true];
} else if (linesMatch(newLine, oldLines[i])) {
return [i, false];
}
}
return [-1, false];
}
/**
* Convert a stream of arbitrary chunks to a stream of lines
*/
export async function* streamLines(
streamCompletion: AsyncGenerator<string>
): AsyncGenerator<string> {
let buffer = "";
for await (const chunk of streamCompletion) {
buffer += chunk;
const lines = buffer.split("\n");
buffer = lines.pop() ?? "";
for (const line of lines) {
yield line;
}
}
if (buffer.length > 0) {
yield buffer;
}
}

View file

@ -11,6 +11,7 @@
"license": "Apache-2.0",
"dependencies": {
"dotenv": "^16.3.1",
"fastest-levenshtein": "^1.0.16",
"handlebars": "^4.7.8",
"js-tiktoken": "^1.0.8",
"openai": "^4.20.1",
@ -2024,6 +2025,14 @@
"integrity": "sha512-lhd/wF+Lk98HZoTCtlVraHtfh5XYijIjalXck7saUtuanSDyLMxnHhSXEDJqHxD7msR8D0uCmqlkwjCV8xvwHw==",
"dev": true
},
"node_modules/fastest-levenshtein": {
"version": "1.0.16",
"resolved": "https://registry.npmjs.org/fastest-levenshtein/-/fastest-levenshtein-1.0.16.tgz",
"integrity": "sha512-eRnCtTTtGZFpQCwhJiUOuxPQWRXVKYDn0b2PeHfXL6/Zi53SLAzAHfVhVWK2AryC/WH05kGfxhFIPvTF0SXQzg==",
"engines": {
"node": ">= 4.9.1"
}
},
"node_modules/fb-watchman": {
"version": "2.0.2",
"resolved": "https://registry.npmjs.org/fb-watchman/-/fb-watchman-2.0.2.tgz",

View file

@ -24,6 +24,7 @@
},
"dependencies": {
"dotenv": "^16.3.1",
"fastest-levenshtein": "^1.0.16",
"handlebars": "^4.7.8",
"js-tiktoken": "^1.0.8",
"openai": "^4.20.1",

View file

@ -0,0 +1,94 @@
import { matchLine } from "core/diff/util";
interface NextLineEvent {
type: "nextLine";
}
interface InsertDeletionEvent {
type: "insertDeletion";
lines: string[];
aboveLineAtIndex: number;
}
interface ReplaceLineEvent {
type: "replaceLine";
index: number;
newLine: string;
}
interface InsertLineEvent {
type: "insertLine";
aboveLineAtIndex: number;
line: string;
}
type VerticalPerLineDiffEvent =
| NextLineEvent
| InsertDeletionEvent
| ReplaceLineEvent
| InsertLineEvent;
async function* streamVerticalPerLineDiff(
lineGenerator: AsyncGenerator<string>,
oldCode: string
): AsyncGenerator<VerticalPerLineDiffEvent> {
const remainingLines = oldCode.split("\n");
let index = 0; // Index in terms of oldCode
let accumulatedDeletedLines: string[] = [];
for await (const line of lineGenerator) {
const [matchIndex, isPerfectMatch] = matchLine(line, remainingLines);
if (matchIndex < 0) {
// No match, so insert above remainingLines[0]
yield {
type: "insertLine",
aboveLineAtIndex: index,
line,
};
} else if (matchIndex === 0) {
if (isPerfectMatch) {
// Perfect match of the next line, so insert and clear existing block
yield {
type: "insertDeletion",
lines: accumulatedDeletedLines,
aboveLineAtIndex: index,
};
remainingLines.shift();
accumulatedDeletedLines = [];
} else {
// Replace next line, so part of same block if one exists
yield {
type: "replaceLine",
index,
newLine: line,
};
let nextLine = remainingLines.shift();
nextLine && accumulatedDeletedLines.push();
}
} else {
// Already in a block, which is disconnected from this one, so insert and clear it
accumulatedDeletedLines.push(...remainingLines.splice(0, matchIndex));
if (isPerfectMatch) {
yield {
type: "insertDeletion",
lines: accumulatedDeletedLines,
aboveLineAtIndex: index - accumulatedDeletedLines.length,
};
accumulatedDeletedLines = [];
} else {
// Add to the current block all of the lines in between, then replace with the new line
yield {
type: "insertLine",
aboveLineAtIndex: index - accumulatedDeletedLines.length,
line,
};
}
}
index += Math.max(0, matchIndex);
remainingLines.splice(0, matchIndex);
}
}

View file

@ -1,30 +0,0 @@
interface DiffBlock {
startLine: number;
endLine: number;
replacement: string[];
}
function linesMatch(lineA: string, lineB: string): boolean {
return lineA === lineB;
}
function matchLine(newLine: string, oldLines: string[]): number {
let matchIndex = -1;
for (let i = 0; i < oldLines.length; i++) {
if (linesMatch(newLine, oldLines[i])) {
matchIndex = i;
break;
}
}
return matchIndex;
}
async function* streamDiffBlocks(
newLinesStream: AsyncGenerator<string>,
oldCode: string
): AsyncGenerator<DiffBlock> {}
// But you also want to stream between the diff blocks.
// So...not only do you want to stream DiffBlocks
// Next is stream lines: {line: string, type: "match" | ""}

View file

@ -0,0 +1,90 @@
import { matchLine } from "core/diff/util";
interface DiffBlock {
startLine: number;
endLine: number;
replacement: string[];
}
interface LineUpdate {
content: string;
line: number;
replace: boolean;
}
type DiffEvent = LineUpdate | DiffBlock;
/**
* Returns a stream of characters, but with "undefined" inserted into the stream whenever there is a new line
*/
async function* streamWithLineBreaks(
completionStream: AsyncGenerator<string>
): AsyncGenerator<string | undefined> {
for await (const chunk of completionStream) {
if (chunk.includes("\n")) {
const lines = chunk.split("\n");
for (let i = 0; i < lines.length; i++) {
yield lines[i];
if (i < lines.length - 1) {
yield undefined;
}
}
} else {
yield chunk;
}
}
}
async function* streamDiffEvents(
completionStream: AsyncGenerator<string>,
oldCode: string
): AsyncGenerator<DiffEvent> {
let remainingLines = oldCode.split("\n");
let i = 0;
let oldLine = remainingLines.shift();
let newLine = "";
let alreadyReplacedCurrentLine = false;
for await (const chunk of streamWithLineBreaks(completionStream)) {
if (chunk === undefined) {
// Decide whether there is a match
const matchIndex = matchLine(newLine, remainingLines);
// Delete all of the lines in the middle
// TODO
// Start a new line
oldLine = remainingLines.shift();
newLine = "";
alreadyReplacedCurrentLine = false;
i++;
} else {
// Continue current line
newLine += chunk;
if (oldLine?.startsWith(newLine)) {
// Match, do nothing
} else {
// Difference, send the update
// This also handles when we are past all of the oldLines
if (alreadyReplacedCurrentLine) {
yield {
content: chunk,
line: i,
replace: false,
};
} else {
yield {
content: newLine,
line: i,
replace: true,
};
alreadyReplacedCurrentLine = true;
}
}
}
}
}
// But you also want to stream between the diff blocks.
// So...not only do you want to stream DiffBlocks
// Next is stream lines: {line: string, type: "match" | ""}

View file

@ -0,0 +1,44 @@
import { DiffLine } from "core/diff/diffLines";
class VerticalPerLineDiffHandler {
private startLine: number;
private endLine: number;
private currentLineIndex: number;
constructor(startLine: number, endLine: number) {
this.startLine = startLine;
this.endLine = endLine;
this.currentLineIndex = startLine;
}
async *displayVerticalPerLineDiff(
diffLineGenerator: AsyncGenerator<DiffLine>
) {
for await (const diffLine of diffLineGenerator) {
this.handleDiffLine(diffLine);
}
}
handleDiffLine(diffLine: DiffLine) {
switch (diffLine.type) {
case "same":
this.currentLineIndex++;
break;
case "old":
this.setLineAtIndexRed(this.currentLineIndex);
this.currentLineIndex++;
break;
case "new":
break;
}
this.updateIndexLineDecorations();
}
setLineAtIndexRed(index: number) {}
updateIndexLineDecorations() {
// Highlight the line at the currentLineIndex
// And lightly highlight all lines between that and endLine
}
}