GETCODEDIFF
import { getCodeDiff } from "@donedeal0/superdiff";Compares two codes and returns a structured diff: lines first, then the tokens of each changed line. Whitespace is kept, so indentation changes are reported too.
To diff files, read them first: getCodeDiff(await previousFile.text(), await currentFile.text()).
FORMAT
Input
previousCode: string | null | undefined,
currentCode: string | null | undefined,Output
type CodeDiff = {
type: "code";
status: "added" | "deleted" | "equal" | "updated";
diff: {
value: string;
previousValue?: string;
line: number | null;
previousLine: number | null;
status: "added" | "deleted" | "equal" | "updated";
diff?: {
value: string;
previousValue?: string;
status: "added" | "deleted" | "equal" | "updated";
}[];
}[];
};Lines start at 1. line is null if the line was deleted, previousLine is null if it was added. diff holds the token changes of an updated line.
USAGE
Input
getCodeDiff(
- "const MAX = 280;\n\nfunction preview(post) {\n return post.body;\n}",
+ "const MAX_LENGTH = 320;\n\nfunction preview(post) {\n const text = post.body;\n return text.slice(0, MAX_LENGTH);\n}"
);Output
{
type: "code",
+ status: "updated",
diff: [
{
+ value: "const MAX_LENGTH = 320;",
+ previousValue: "const MAX = 280;",
line: 1,
previousLine: 1,
+ status: "updated",
diff: [
{ value: "const", status: "equal" },
+ { value: " MAX_LENGTH", previousValue: " MAX", status: "updated" },
{ value: " =", status: "equal" },
+ { value: " 320", previousValue: " 280", status: "updated" },
{ value: ";", status: "equal" },
],
},
{
value: "",
previousValue: "",
line: 2,
previousLine: 2,
status: "equal",
},
{
value: "function preview(post) {",
previousValue: "function preview(post) {",
line: 3,
previousLine: 3,
status: "equal",
},
{
+ value: " const text = post.body;",
+ previousValue: " return post.body;",
line: 4,
previousLine: 4,
+ status: "updated",
diff: [
+ { value: " const", previousValue: " return", status: "updated" },
+ { value: " text", status: "added" },
+ { value: " =", status: "added" },
{ value: " post", status: "equal" },
{ value: ".", status: "equal" },
{ value: "body", status: "equal" },
{ value: ";", status: "equal" },
],
},
{
+ value: " return text.slice(0, MAX_LENGTH);",
line: 5,
previousLine: null,
+ status: "added",
},
{
value: "}",
previousValue: "}",
line: 6,
previousLine: 5,
status: "equal",
},
],
}