import { structuredPatch, type StructuredPatchHunk } from 'diff' /** * The size of a whole diff. `coarse` is true when part of it ran out of time and shows as one block that replaces those lines. */ export type DiffStats = { additions: number; deletions: number; hunks: number; lines: number; coarse: boolean } export type DiffResult = { hunks: Array; stats: DiffStats } const CONTEXT_LINES = 3 // Past this, each remaining segment shows as one replace block. const DIFF_TIMEOUT_MS = 1_000 // Lines keep their `\n`, so a last line without one differs from the same line with one. const splitLines = (text: string) => (text === '' ? [] : text.split(/(?<=\n)/)) // Longest increasing subsequence of `values`, as indexes into it. function longestIncreasing(values: Array): Array { const tails: Array = [] const prev: Array = [] for (const [index, value] of values.entries()) { let low = 0 let high = tails.length while (low < high) { const mid = (low + high) >> 1 if (values[tails[mid]!]! < value) low = mid + 1 else high = mid } prev[index] = low > 0 ? tails[low - 1]! : -1 tails[low] = index } const result: Array = [] for (let index = tails.at(-1) ?? -1; index !== -1; index = prev[index]!) result.push(index) return result.reverse() } // The lines that occur once in each file, in the same order in both, as [index in before, index in after]. function findAnchors(before: Array, after: Array): Array { const counts = new Map() for (const [index, line] of before.entries()) { const count = counts.get(line) if (count) count.before++ else counts.set(line, { before: 1, after: 0, index }) } const afterIndex = new Map() for (const [index, line] of after.entries()) { const count = counts.get(line) if (!count) continue count.after++ afterIndex.set(line, index) } // Map order is insertion order, so these are sorted by their index in `before`. const unique = [...counts] .filter(([, count]) => count.before === 1 && count.after === 1) .map(([line, count]) => [count.index, afterIndex.get(line)!] as const) return longestIncreasing(unique.map(([, index]) => index)).map((index) => unique[index]!) } // Where to cut both files so each segment diffs on its own: inside each unchanged stretch that keeps a full // context on both sides, so no hunk crosses a cut. The anchors find those stretches. function cutPoints(before: Array, after: Array): Array<[number, number]> { const cuts: Array<[number, number]> = [[0, 0]] let run = { before: 0, after: 0, length: 0 } const closeRun = () => { if (run.length > 2 * CONTEXT_LINES) cuts.push([run.before + CONTEXT_LINES, run.after + CONTEXT_LINES]) } let i = 0 let j = 0 for (const [anchorBefore, anchorAfter] of findAnchors(before, after)) { // The lines between two anchors are unchanged when both sides hold the same lines. const unchanged = anchorBefore - i === anchorAfter - j && before.slice(i, anchorBefore).every((line, offset) => line === after[j + offset]) if (unchanged && run.length && run.before + run.length === i) { run.length += anchorBefore - i + 1 } else { closeRun() run = unchanged ? { before: i, after: j, length: anchorBefore - i + 1 } : { before: anchorBefore, after: anchorAfter, length: 1 } } i = anchorBefore + 1 j = anchorAfter + 1 } closeRun() cuts.push([before.length, after.length]) return cuts } // A segment with no time left to diff shows as one block that replaces everything between its shared first and last lines. function replaceHunk(before: Array, after: Array): Array { let start = 0 while (start < before.length && start < after.length && before[start] === after[start]) start++ let end = 0 while (end < before.length - start && end < after.length - start && before[before.length - 1 - end] === after[after.length - 1 - end]) end++ const removed = before.slice(start, before.length - end) const added = after.slice(start, after.length - end) if (!removed.length && !added.length) return [] const lines = (prefix: string, rows: Array) => rows.flatMap((row) => (row.endsWith('\n') ? [`${prefix}${row.slice(0, -1)}`] : [`${prefix}${row}`, '\\ No newline at end of file'])) // Same numbering as `structuredPatch`, which starts an empty side at line 1 too. return [{ oldStart: start + 1, oldLines: removed.length, newStart: start + 1, newLines: added.length, lines: [...lines('-', removed), ...lines('+', added)] }] } /** * The line hunks that turn `before` into `after`, with three lines of context, plus their totals. * Kubb Studio's diff view and `kubb generate --diff` both read them. * * One Myers diff over a whole file grows with lines times changes and stalls on large specs, so each * segment between cuts is diffed on its own. */ export function diffHunks(before: string, after: string, timeout = DIFF_TIMEOUT_MS): DiffResult { const beforeLines = splitLines(before) const afterLines = splitLines(after) const cuts = cutPoints(beforeLines, afterLines) const deadline = Date.now() + timeout const hunks: Array = [] let coarse = false for (const [index, [beforeStart, afterStart]] of cuts.slice(0, -1).entries()) { const [beforeEnd, afterEnd] = cuts[index + 1]! const segmentBefore = beforeLines.slice(beforeStart, beforeEnd) const segmentAfter = afterLines.slice(afterStart, afterEnd) const patch = structuredPatch('', '', segmentBefore.join(''), segmentAfter.join(''), undefined, undefined, { context: CONTEXT_LINES, timeout: Math.max(0, deadline - Date.now()), }) if (!patch) coarse = true for (const hunk of patch?.hunks ?? replaceHunk(segmentBefore, segmentAfter)) { hunks.push({ ...hunk, oldStart: hunk.oldStart + beforeStart, newStart: hunk.newStart + afterStart }) } } const lines = hunks.flatMap((hunk) => hunk.lines) const stats: DiffStats = { additions: lines.filter((line) => line[0] === '+').length, deletions: lines.filter((line) => line[0] === '-').length, hunks: hunks.length, lines: lines.length, coarse, } return { hunks, stats } }