39 lines
1.4 KiB
JavaScript
39 lines
1.4 KiB
JavaScript
// Hunk diffs for the DSH diff card ({path, oldText, newText} per hunk, 3 lines of context).
|
|
import { lineMap } from './store.js'
|
|
import { splitLines } from './text.js'
|
|
|
|
export function hunkDiffs(path, before, after, context = 3) {
|
|
const a = splitLines(before).lines
|
|
const b = splitLines(after).lines
|
|
const map = lineMap(a, b)
|
|
// Walk both sides, emitting ops: '=' common, '-' removed, '+' added.
|
|
const ops = []
|
|
let i = 1; let j = 1
|
|
const pairs = [...map.entries()].sort((x, y) => x[0] - y[0])
|
|
for (const [ai, bj] of pairs) {
|
|
while (i < ai) ops.push(['-', a[i++ - 1]])
|
|
while (j < bj) ops.push(['+', b[j++ - 1]])
|
|
ops.push(['=', a[i - 1]]); i++; j++
|
|
}
|
|
while (i <= a.length) ops.push(['-', a[i++ - 1]])
|
|
while (j <= b.length) ops.push(['+', b[j++ - 1]])
|
|
const changed = ops.map((o, k) => (o[0] !== '=' ? k : -1)).filter((k) => k >= 0)
|
|
if (!changed.length) return []
|
|
const spans = []
|
|
for (const k of changed) {
|
|
const s = Math.max(0, k - context); const e = Math.min(ops.length - 1, k + context)
|
|
const last = spans.at(-1)
|
|
if (last && s <= last[1] + 1) last[1] = Math.max(last[1], e)
|
|
else spans.push([s, e])
|
|
}
|
|
return spans.map(([s, e]) => {
|
|
const oldL = []; const newL = []
|
|
for (let k = s; k <= e; k++) {
|
|
const [op, text] = ops[k]
|
|
if (op !== '+') oldL.push(text)
|
|
if (op !== '-') newL.push(text)
|
|
}
|
|
return { path, oldText: oldL.length ? oldL.join('\n') : null, newText: newL.join('\n') }
|
|
})
|
|
}
|