line-diff.test.ts
This file
Path
packages/git/test/line-diff.test.ts
89 lines · 2.5 KiB · TypeScript
Last changed by
Merge build/comments-packages-rest into mainoscabrielbefore adoption38cd503
History of this fileTake it
Merge branch 'build/912-why-per-line'oscabrielbefore adoption635c3c7
lines 1–89why, one step back1import { describe, expect, it } from "@effect/vitest";23import { Edit, lineDiff } from "../src/line-diff.ts";45const lines = (text: string) => (text === "" ? [] : text.split(" "));67const apply = (8 before: readonly string[],9 after: readonly string[],10 edits: readonly Edit[]11) => {12 const out: string[] = [];13 let old = 0;1415 for (const edit of edits) {16 expect(edit.oldStart).toBe(old);17 expect(edit.newStart).toBe(out.length);1819 if (Edit.$is("Insert")(edit)) {20 out.push(...after.slice(edit.newStart, edit.newStart + edit.count));21 } else {22 if (Edit.$is("Equal")(edit)) {23 out.push(...before.slice(old, old + edit.count));24 }2526 old += edit.count;27 }28 }2930 expect(old).toBe(before.length);3132 return out;33};3435const runs = (edits: readonly Edit[]) =>36 edits.map(({ _tag, count }) => [_tag, count] as const);3738describe("the line diff", () => {39 it("turns `a b c` into `a x c` as equal, delete, insert, equal", () => {40 expect(lineDiff(lines("a b c"), lines("a x c"))).toStrictEqual([41 Edit.Equal({ count: 1, newStart: 0, oldStart: 0 }),42 Edit.Delete({ count: 1, newStart: 1, oldStart: 1 }),43 Edit.Insert({ count: 1, newStart: 1, oldStart: 2 }),44 Edit.Equal({ count: 1, newStart: 2, oldStart: 2 }),45 ]);46 });4748 it("rebuilds the new lines when its script is applied to the old", () => {49 const pairs = [50 ["a b c", "a x c"],51 ["", "a b"],52 ["a b", ""],53 ["a b c d e f", "x a c d y f z"],54 ["one two three four", "one between two three FOUR five"],55 ["a a a b", "b a a a"],56 ] as const;5758 for (const [from, to] of pairs) {59 const before = lines(from);60 const after = lines(to);6162 expect(apply(before, after, lineDiff(before, after))).toStrictEqual(63 after64 );65 }66 });6768 it("is one equal run for the same lines, and none for two empty files", () => {69 expect(runs(lineDiff(lines("a b"), lines("a b")))).toStrictEqual([70 ["Equal", 2],71 ]);72 expect(lineDiff([], [])).toStrictEqual([]);73 });7475 it("keeps the lines a rewrite past the shortest search shares, in order", () => {76 const before = Array.from({ length: 3000 }, (_, at) => `old ${at}`);7778 const after = Array.from({ length: 3000 }, (_, at) =>79 at % 100 === 0 ? `old ${at}` : `new ${at}`80 );8182 const edits = lineDiff(before, after);8384 expect(apply(before, after, edits)).toStrictEqual(after);85 expect(86 edits.filter(Edit.$is("Equal")).reduce((sum, { count }) => sum + count, 0)87 ).toBe(30);88 });89});