Skip to content
Myr

line-diff.ts

This file

Path

packages/git/src/line-diff.ts

308 lines · 7.7 KiB · TypeScript

Last changed by

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

History of this file

Take it

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

lines 1–308why, one step back
1/**
2 * A line diff with no dependency: the whole edit script from one file's3 * lines to another's, as runs of equal, deleted and inserted lines. The4 * shortest script is Myers' O(ND) diff over the lines left once the shared5 * head and tail are set aside; past `MAX_EDITS` edits it stops looking for6 * the shortest, and the script keeps only the lines found once in each7 * file, in order (git's patience anchors, matched greedily).8 *9 * Positions are 0-based: an edit starts at `oldStart` in the old lines and10 * `newStart` in the new, and in a run of changes the deletions come first.11 */12import { Data, Option } from "effect";1314/** `count` lines from `oldStart` in the old lines and `newStart` in the new. */15interface Span {16 readonly oldStart: number;17 readonly newStart: number;18 readonly count: number;19}2021/** One run of an edit script: lines both files share, or lines one alone holds. */22export type Edit = Data.TaggedEnum<{23 Delete: Span;24 Equal: Span;25 Insert: Span;26}>;2728export const Edit = Data.taggedEnum<Edit>();2930/** One line's step through the script. */31type Step = Edit["_tag"];3233// Past this many edits the diff stops looking for the shortest script.34const MAX_EDITS = 1024;3536const at = (values: Int32Array, index: number) => values[index] ?? 0;3738/**39 * The steps of the script ending at `(n, m)`, read back from `trace`, where40 * `trace[d]` holds diagonals `-d..d` after `d` edits.41 */42const stepsFrom = (43 trace: readonly Int32Array[],44 ends: { readonly n: number; readonly m: number }45) => {46 const steps: Step[] = [];47 let x = ends.n;48 let y = ends.m;4950 for (let edits = trace.length - 1; edits > 0; edits -= 1) {51 const previous = trace[edits - 1] ?? new Int32Array();52 const diagonal = x - y;5354 const reached = (k: number) => at(previous, k + edits - 1);5556 const down =57 diagonal === -edits ||58 (diagonal !== edits && reached(diagonal - 1) < reached(diagonal + 1));5960 const from = down ? diagonal + 1 : diagonal - 1;61 const fromX = reached(from);62 const snakeX = down ? fromX : fromX + 1;6364 for (; x > snakeX; x -= 1) {65 steps.push("Equal");66 }6768 steps.push(down ? "Insert" : "Delete");69 x = fromX;70 y = fromX - from;71 }7273 for (; x > 0; x -= 1) {74 steps.push("Equal");75 }7677 return steps.toReversed();78};7980/** A shortest edit script from `previous` to `next`, or none past `MAX_EDITS`. */81const myers = (82 previous: readonly string[],83 next: readonly string[]84): Option.Option<readonly Step[]> => {85 const n = previous.length;86 const m = next.length;87 const limit = Math.min(n + m, MAX_EDITS);88 const offset = limit + 1;89 const reach = new Int32Array(2 * limit + 3);90 const trace: Int32Array[] = [];9192 for (let edits = 0; edits <= limit; edits += 1) {93 for (let diagonal = -edits; diagonal <= edits; diagonal += 2) {94 let x =95 diagonal === -edits ||96 (diagonal !== edits &&97 at(reach, offset + diagonal - 1) < at(reach, offset + diagonal + 1))98 ? at(reach, offset + diagonal + 1)99 : at(reach, offset + diagonal - 1) + 1;100101 let y = x - diagonal;102103 while (x < n && y < m && previous[x] === next[y]) {104 x += 1;105 y += 1;106 }107108 reach[offset + diagonal] = x;109110 if (x >= n && y >= m) {111 trace.push(reach.slice(offset - edits, offset + edits + 1));112113 return Option.some(stepsFrom(trace, { m, n }));114 }115 }116117 trace.push(reach.slice(offset - edits, offset + edits + 1));118 }119120 return Option.none();121};122123/** How many times each line occurs in `lines`. */124const countsOf = (lines: readonly string[]) => {125 const counts = new Map<string, number>();126127 for (const line of lines) {128 counts.set(line, (counts.get(line) ?? 0) + 1);129 }130131 return counts;132};133134/**135 * A script for a rewrite too large for the shortest: the lines found once136 * in each file are kept, in order, each matched after the last; every other137 * line is deleted or inserted.138 */139const anchored = (140 previous: readonly string[],141 next: readonly string[]142): readonly Step[] => {143 const before = countsOf(previous);144 const after = countsOf(next);145146 const unique = (line: string) =>147 before.get(line) === 1 && after.get(line) === 1;148149 const where = new Map<string, number>(150 previous.flatMap((line, index) =>151 unique(line) ? [[line, index] as const] : []152 )153 );154155 const steps: Step[] = [];156 let cursor = 0;157158 for (const line of next) {159 const found = where.get(line) ?? -1;160161 if (found < cursor) {162 steps.push("Insert");163 } else {164 for (; cursor < found; cursor += 1) {165 steps.push("Delete");166 }167168 steps.push("Equal");169 cursor += 1;170 }171 }172173 for (; cursor < previous.length; cursor += 1) {174 steps.push("Delete");175 }176177 return steps;178};179180/** The steps of a script, as runs: in each run of changes, deletions first. */181const runsOf = (steps: readonly Step[]): readonly Edit[] => {182 const edits: Edit[] = [];183 let oldStart = 0;184 let newStart = 0;185 let index = 0;186187 while (index < steps.length) {188 let count = 0;189190 if (steps[index] === "Equal") {191 for (; steps[index] === "Equal"; index += 1) {192 count += 1;193 }194195 edits.push(Edit.Equal({ count, newStart, oldStart }));196 oldStart += count;197 newStart += count;198 } else {199 let deleted = 0;200 let inserted = 0;201202 for (203 let step = steps[index];204 step !== undefined && step !== "Equal";205 step = steps[index]206 ) {207 if (step === "Delete") {208 deleted += 1;209 } else {210 inserted += 1;211 }212213 index += 1;214 }215216 if (deleted > 0) {217 edits.push(Edit.Delete({ count: deleted, newStart, oldStart }));218 oldStart += deleted;219 }220221 if (inserted > 0) {222 edits.push(Edit.Insert({ count: inserted, newStart, oldStart }));223 newStart += inserted;224 }225 }226 }227228 return edits;229};230231/** How many lines from each end `previous` and `next` share. */232export const sharedEnds = (233 previous: readonly string[],234 next: readonly string[]235) => {236 let head = 0;237238 while (239 head < previous.length &&240 head < next.length &&241 previous[head] === next[head]242 ) {243 head += 1;244 }245246 let tail = 0;247248 while (249 tail < previous.length - head &&250 tail < next.length - head &&251 previous[previous.length - 1 - tail] === next[next.length - 1 - tail]252 ) {253 tail += 1;254 }255256 return { head, tail };257};258259/** `middle` with the shared head and tail around it. */260const framed = (261 ends: { readonly head: number; readonly tail: number },262 middle: readonly Step[]263): readonly Step[] => [264 ...Array.from({ length: ends.head }, (): Step => "Equal"),265 ...middle,266 ...Array.from({ length: ends.tail }, (): Step => "Equal"),267];268269/**270 * A shortest edit script from `before` to `after`, or none when it takes271 * more than `MAX_EDITS` edits past the shared head and tail.272 */273export const shortestDiff = (274 before: readonly string[],275 after: readonly string[]276): Option.Option<readonly Edit[]> => {277 const ends = sharedEnds(before, after);278279 return Option.map(280 myers(281 before.slice(ends.head, before.length - ends.tail),282 after.slice(ends.head, after.length - ends.tail)283 ),284 (middle) => runsOf(framed(ends, middle))285 );286};287288/**289 * The edit script from `before` to `after`: the shortest, or, for a rewrite290 * past `MAX_EDITS` edits, one that keeps the lines found once in each file.291 */292export const lineDiff = (293 before: readonly string[],294 after: readonly string[]295): readonly Edit[] =>296 Option.getOrElse(shortestDiff(before, after), () => {297 const ends = sharedEnds(before, after);298299 return runsOf(300 framed(301 ends,302 anchored(303 before.slice(ends.head, before.length - ends.tail),304 after.slice(ends.head, after.length - ends.tail)305 )306 )307 );308 });