98 lines
2.4 KiB
TypeScript
98 lines
2.4 KiB
TypeScript
export interface DiffLine {
|
|
type: 'equal' | 'add' | 'del';
|
|
oldLine?: number;
|
|
newLine?: number;
|
|
text: string;
|
|
}
|
|
|
|
export interface DiffResult {
|
|
lines: DiffLine[];
|
|
unified: string;
|
|
additions: number;
|
|
deletions: number;
|
|
}
|
|
|
|
export function computeLineDiff(
|
|
oldText: string,
|
|
newText: string,
|
|
oldLabel = 'revision',
|
|
newLabel = 'current',
|
|
): DiffResult {
|
|
const a = oldText.replace(/\r\n/g, '\n').split('\n');
|
|
const b = newText.replace(/\r\n/g, '\n').split('\n');
|
|
const m = a.length;
|
|
const n = b.length;
|
|
|
|
let lines: DiffLine[];
|
|
|
|
// DP LCS works cleanly for config files up to a few thousand lines
|
|
if (m * n <= 2_500_000) {
|
|
const dp = new Int32Array((m + 1) * (n + 1));
|
|
const stride = n + 1;
|
|
|
|
for (let i = m - 1; i >= 0; i--) {
|
|
for (let j = n - 1; j >= 0; j--) {
|
|
if (a[i] === b[j]) {
|
|
dp[i * stride + j] = dp[(i + 1) * stride + (j + 1)]! + 1;
|
|
} else {
|
|
const down = dp[(i + 1) * stride + j]!;
|
|
const right = dp[i * stride + (j + 1)]!;
|
|
dp[i * stride + j] = down >= right ? down : right;
|
|
}
|
|
}
|
|
}
|
|
|
|
lines = [];
|
|
let i = 0;
|
|
let j = 0;
|
|
while (i < m && j < n) {
|
|
if (a[i] === b[j]) {
|
|
lines.push({ type: 'equal', oldLine: i + 1, newLine: j + 1, text: a[i]! });
|
|
i++;
|
|
j++;
|
|
} else if (dp[(i + 1) * stride + j]! >= dp[i * stride + (j + 1)]!) {
|
|
lines.push({ type: 'del', oldLine: i + 1, text: a[i]! });
|
|
i++;
|
|
} else {
|
|
lines.push({ type: 'add', newLine: j + 1, text: b[j]! });
|
|
j++;
|
|
}
|
|
}
|
|
while (i < m) {
|
|
lines.push({ type: 'del', oldLine: i + 1, text: a[i]! });
|
|
i++;
|
|
}
|
|
while (j < n) {
|
|
lines.push({ type: 'add', newLine: j + 1, text: b[j]! });
|
|
j++;
|
|
}
|
|
} else {
|
|
// Fallback linear diff for unexpectedly massive inputs
|
|
lines = [
|
|
...a.map((text, idx) => ({ type: 'del' as const, oldLine: idx + 1, text })),
|
|
...b.map((text, idx) => ({ type: 'add' as const, newLine: idx + 1, text })),
|
|
];
|
|
}
|
|
|
|
let additions = 0;
|
|
let deletions = 0;
|
|
const body: string[] = [`--- ${oldLabel}`, `+++ ${newLabel}`];
|
|
for (const line of lines) {
|
|
if (line.type === 'add') {
|
|
additions++;
|
|
body.push(`+${line.text}`);
|
|
} else if (line.type === 'del') {
|
|
deletions++;
|
|
body.push(`-${line.text}`);
|
|
} else {
|
|
body.push(` ${line.text}`);
|
|
}
|
|
}
|
|
|
|
return {
|
|
lines,
|
|
unified: body.join('\n'),
|
|
additions,
|
|
deletions,
|
|
};
|
|
}
|