Skip to content
Myr

line-diff.ts

This file

Path

packages/git/src/line-diff.ts

281 lines · 6.3 KiB · TypeScript

Last changed by

Merge build/comments-packages-rest into mainoscabrielbefore adoption38cd503

History of this file

Take it

Merge branch 'build/912-why-per-line'oscabrielbefore adoption635c3c7

line 1why, one step back
1/**

Merge build/comments-packages-rest into mainoscabrielbefore adoption38cd503

lines 2–5why, one step back
2 * Myers' O(ND) diff over the lines left once the shared head and tail are set
3 * aside; past `MAX_EDITS` edits it keeps only the lines found once in each4 * file, in order (git's patience anchors, matched greedily). Positions are5 * 0-based, and in a run of changes the deletions come first.

Merge branch 'build/912-why-per-line'oscabrielbefore adoption635c3c7

lines 6–281why, one step back
6 */
7import { Data, Option } from "effect";89interface Span {10 readonly oldStart: number;11 readonly newStart: number;12 readonly count: number;13}1415export type Edit = Data.TaggedEnum<{16 Delete: Span;17 Equal: Span;18 Insert: Span;19}>;2021export const Edit = Data.taggedEnum<Edit>();2223type Step = Edit["_tag"];2425const MAX_EDITS = 1024;2627const at = (values: Int32Array, index: number) => values[index] ?? 0;2829/**30 * The steps of the script ending at `(n, m)`, read back from `trace`, where31 * `trace[d]` holds diagonals `-d..d` after `d` edits.32 */33const stepsFrom = (34 trace: readonly Int32Array[],35 ends: { readonly n: number; readonly m: number }36) => {37 const steps: Step[] = [];38 let x = ends.n;39 let y = ends.m;4041 for (let edits = trace.length - 1; edits > 0; edits -= 1) {42 const previous = trace[edits - 1] ?? new Int32Array();43 const diagonal = x - y;4445 const reached = (k: number) => at(previous, k + edits - 1);4647 const down =48 diagonal === -edits ||49 (diagonal !== edits && reached(diagonal - 1) < reached(diagonal + 1));5051 const from = down ? diagonal + 1 : diagonal - 1;52 const fromX = reached(from);53 const snakeX = down ? fromX : fromX + 1;5455 for (; x > snakeX; x -= 1) {56 steps.push("Equal");57 }5859 steps.push(down ? "Insert" : "Delete");60 x = fromX;61 y = fromX - from;62 }6364 for (; x > 0; x -= 1) {65 steps.push("Equal");66 }6768 return steps.toReversed();69};7071const myers = (72 previous: readonly string[],73 next: readonly string[]74): Option.Option<readonly Step[]> => {75 const n = previous.length;76 const m = next.length;77 const limit = Math.min(n + m, MAX_EDITS);78 const offset = limit + 1;79 const reach = new Int32Array(2 * limit + 3);80 const trace: Int32Array[] = [];8182 for (let edits = 0; edits <= limit; edits += 1) {83 for (let diagonal = -edits; diagonal <= edits; diagonal += 2) {84 let x =85 diagonal === -edits ||86 (diagonal !== edits &&87 at(reach, offset + diagonal - 1) < at(reach, offset + diagonal + 1))88 ? at(reach, offset + diagonal + 1)89 : at(reach, offset + diagonal - 1) + 1;9091 let y = x - diagonal;9293 while (x < n && y < m && previous[x] === next[y]) {94 x += 1;95 y += 1;96 }9798 reach[offset + diagonal] = x;99100 if (x >= n && y >= m) {101 trace.push(reach.slice(offset - edits, offset + edits + 1));102103 return Option.some(stepsFrom(trace, { m, n }));104 }105 }106107 trace.push(reach.slice(offset - edits, offset + edits + 1));108 }109110 return Option.none();111};112113const countsOf = (lines: readonly string[]) => {114 const counts = new Map<string, number>();115116 for (const line of lines) {117 counts.set(line, (counts.get(line) ?? 0) + 1);118 }119120 return counts;121};122123const anchored = (124 previous: readonly string[],125 next: readonly string[]126): readonly Step[] => {127 const before = countsOf(previous);128 const after = countsOf(next);129130 const unique = (line: string) =>131 before.get(line) === 1 && after.get(line) === 1;132133 const where = new Map<string, number>(134 previous.flatMap((line, index) =>135 unique(line) ? [[line, index] as const] : []136 )137 );138139 const steps: Step[] = [];140 let cursor = 0;141142 for (const line of next) {143 const found = where.get(line) ?? -1;144145 if (found < cursor) {146 steps.push("Insert");147 } else {148 for (; cursor < found; cursor += 1) {149 steps.push("Delete");150 }151152 steps.push("Equal");153 cursor += 1;154 }155 }156157 for (; cursor < previous.length; cursor += 1) {158 steps.push("Delete");159 }160161 return steps;162};163164const runsOf = (steps: readonly Step[]): readonly Edit[] => {165 const edits: Edit[] = [];166 let oldStart = 0;167 let newStart = 0;168 let index = 0;169170 while (index < steps.length) {171 let count = 0;172173 if (steps[index] === "Equal") {174 for (; steps[index] === "Equal"; index += 1) {175 count += 1;176 }177178 edits.push(Edit.Equal({ count, newStart, oldStart }));179 oldStart += count;180 newStart += count;181 } else {182 let deleted = 0;183 let inserted = 0;184185 for (186 let step = steps[index];187 step !== undefined && step !== "Equal";188 step = steps[index]189 ) {190 if (step === "Delete") {191 deleted += 1;192 } else {193 inserted += 1;194 }195196 index += 1;197 }198199 if (deleted > 0) {200 edits.push(Edit.Delete({ count: deleted, newStart, oldStart }));201 oldStart += deleted;202 }203204 if (inserted > 0) {205 edits.push(Edit.Insert({ count: inserted, newStart, oldStart }));206 newStart += inserted;207 }208 }209 }210211 return edits;212};213214export const sharedEnds = (215 previous: readonly string[],216 next: readonly string[]217) => {218 let head = 0;219220 while (221 head < previous.length &&222 head < next.length &&223 previous[head] === next[head]224 ) {225 head += 1;226 }227228 let tail = 0;229230 while (231 tail < previous.length - head &&232 tail < next.length - head &&233 previous[previous.length - 1 - tail] === next[next.length - 1 - tail]234 ) {235 tail += 1;236 }237238 return { head, tail };239};240241const framed = (242 ends: { readonly head: number; readonly tail: number },243 middle: readonly Step[]244): readonly Step[] => [245 ...Array.from({ length: ends.head }, (): Step => "Equal"),246 ...middle,247 ...Array.from({ length: ends.tail }, (): Step => "Equal"),248];249250export const shortestDiff = (251 before: readonly string[],252 after: readonly string[]253): Option.Option<readonly Edit[]> => {254 const ends = sharedEnds(before, after);255256 return Option.map(257 myers(258 before.slice(ends.head, before.length - ends.tail),259 after.slice(ends.head, after.length - ends.tail)260 ),261 (middle) => runsOf(framed(ends, middle))262 );263};264265export const lineDiff = (266 before: readonly string[],267 after: readonly string[]268): readonly Edit[] =>269 Option.getOrElse(shortestDiff(before, after), () => {270 const ends = sharedEnds(before, after);271272 return runsOf(273 framed(274 ends,275 anchored(276 before.slice(ends.head, before.length - ends.tail),277 after.slice(ends.head, after.length - ends.tail)278 )279 )280 );281 });