diff --git a/chardiff_test.go b/chardiff_test.go deleted file mode 100644 index a4fa5ab..0000000 --- a/chardiff_test.go +++ /dev/null @@ -1,487 +0,0 @@ -package diff_test - -import ( - "bytes" - "strings" - "testing" - - "go.followtheprocess.codes/diff" -) - -func TestCharDiff(t *testing.T) { - tests := []struct { - name string - removed []byte - added []byte - wantAllUnchanged bool // if true, expect all segments Changed:false (identical inputs) - wantHasChanged bool // if true, expect at least one Changed:true segment on either side - }{ - { - name: "identical lines - all segments unchanged", - removed: []byte("hello world\n"), - added: []byte("hello world\n"), - wantAllUnchanged: true, - }, - { - name: "completely different", - removed: []byte("abc\n"), - added: []byte("xyz\n"), - wantHasChanged: true, - }, - { - name: "prefix change", - removed: []byte("foobar\n"), - added: []byte("bazbar\n"), - wantHasChanged: true, - }, - { - name: "suffix change", - removed: []byte("hello world\n"), - added: []byte("hello earth\n"), - wantHasChanged: true, - }, - { - name: "middle change", - removed: []byte("hello world bye\n"), - added: []byte("hello earth bye\n"), - wantHasChanged: true, - }, - { - name: "unicode", - removed: []byte("héllo wörld\n"), - added: []byte("héllo earth\n"), - wantHasChanged: true, - }, - { - name: "empty removed", - removed: []byte(""), - added: []byte("new content\n"), - wantHasChanged: true, - }, - { - name: "empty added", - removed: []byte("old content\n"), - added: []byte(""), - wantHasChanged: true, - }, - { - name: "both empty", - removed: []byte(""), - added: []byte(""), - wantAllUnchanged: true, - }, - { - name: "trailing newline preserved", - removed: []byte("line\n"), - added: []byte("changed\n"), - wantHasChanged: true, - }, - { - // Regression: invalid UTF-8 on the added side must not corrupt the join invariant. - // \xe2 is the start of a 3-byte sequence with no continuation bytes. - name: "invalid UTF-8 in added side", - removed: []byte("0"), - added: []byte("\xe2"), - wantHasChanged: true, - }, - { - // Regression: invalid UTF-8 on the removed side. - name: "invalid UTF-8 in removed side", - removed: []byte("\xe2"), - added: []byte("0"), - wantHasChanged: true, - }, - { - // Regression: identical invalid UTF-8 bytes must produce all-unchanged segments. - // \x80 is a bare continuation byte — invalid UTF-8 on its own. - name: "identical invalid UTF-8", - removed: []byte("\x80"), - added: []byte("\x80"), - wantAllUnchanged: true, - }, - } - - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - result := diff.CharDiff(tt.removed, tt.added) - - assertJoinInvariant(t, result, tt.removed, tt.added) - - if tt.wantAllUnchanged { - assertNoneChanged(t, result.Removed, "removed") - assertNoneChanged(t, result.Added, "added") - } - - if tt.wantHasChanged { - if !anyChanged(result.Removed) && !anyChanged(result.Added) { - t.Error("CharDiff on differing inputs should produce at least one Changed segment") - } - } - }) - } -} - -// TestCharDiffCapTriggers verifies the >500 rune safety cap produces a single-segment fallback. -func TestCharDiffCapTriggers(t *testing.T) { - long := []byte(strings.Repeat("a", 501) + "\n") - other := []byte(strings.Repeat("b", 501) + "\n") - - result := diff.CharDiff(long, other) - - if len(result.Removed) != 1 { - t.Errorf("expected 1 removed segment for >500 rune input, got %d", len(result.Removed)) - } - - if len(result.Added) != 1 { - t.Errorf("expected 1 added segment for >500 rune input, got %d", len(result.Added)) - } - - if !result.Removed[0].Changed { - t.Error("expected removed fallback segment to be Changed:true") - } - - if !result.Added[0].Changed { - t.Error("expected added fallback segment to be Changed:true") - } -} - -// TestCharDiffNewlineNotHighlighted asserts that the trailing newline is never included in a -// Changed segment. A highlighted \n causes the ANSI background colour to bleed onto the next -// terminal line when rendered. -func TestCharDiffNewlineNotHighlighted(t *testing.T) { - tests := []struct { - name string - removed []byte - added []byte - }{ - { - name: "suffix added", - removed: []byte("hello\n"), - added: []byte("hello world\n"), - }, - { - name: "inline change with trailing newline", - removed: []byte("\treturn \"Hello, \" + name\n"), - added: []byte("\treturn \"Hello, \" + name + \"!\"\n"), - }, - { - name: "completely different lines", - removed: []byte("abc\n"), - added: []byte("xyz\n"), - }, - } - - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - result := diff.CharDiff(tt.removed, tt.added) - - for i, seg := range result.Removed { - if seg.Changed && len(seg.Text) > 0 && seg.Text[len(seg.Text)-1] == '\n' { - t.Errorf( - "removed segment[%d] is Changed=true but ends with \\n; highlight would bleed onto next terminal line", - i, - ) - } - } - - for i, seg := range result.Added { - if seg.Changed && len(seg.Text) > 0 && seg.Text[len(seg.Text)-1] == '\n' { - t.Errorf( - "added segment[%d] is Changed=true but ends with \\n; highlight would bleed onto next terminal line", - i, - ) - } - } - }) - } -} - -// TestCharDiffNotSameForDifferent verifies that differing inputs produce at least one Changed segment. -func TestCharDiffNotSameForDifferent(t *testing.T) { - result := diff.CharDiff([]byte("hello\n"), []byte("world\n")) - - hasChanged := false - - for _, seg := range result.Removed { - if seg.Changed { - hasChanged = true - break - } - } - - if !hasChanged { - for _, seg := range result.Added { - if seg.Changed { - hasChanged = true - break - } - } - } - - if !hasChanged { - t.Error("CharDiff on different inputs should produce at least one Changed segment") - } -} - -// TestCharDiffSimilarityGate verifies that WithSimilarityThreshold suppresses -// intraline highlighting when the ratio of equal runes is below the threshold. -func TestCharDiffSimilarityGate(t *testing.T) { - tests := []struct { - name string - removed []byte - added []byte - threshold float64 - wantAllChanged bool // true = expect single whole-line Changed segment (fallback) - wantHasUnchanged bool // true = expect at least one unchanged (intraline) segment - }{ - { - // "func Foo() {" vs "type Bar struct {" share almost nothing. - // Default threshold 0.5 should suppress highlighting. - name: "dissimilar lines suppressed at default threshold", - removed: []byte("func Foo() {\n"), - added: []byte("type Bar struct {\n"), - threshold: 0.5, - wantAllChanged: true, - }, - { - // Same pair, but threshold=0 means always highlight. - name: "dissimilar lines highlighted at threshold=0", - removed: []byte("func Foo() {\n"), - added: []byte("type Bar struct {\n"), - threshold: 0.0, - wantHasUnchanged: true, // " {" is common - }, - { - // Highly similar lines should always produce intraline highlights. - name: "similar lines produce intraline highlighting", - removed: []byte("return fmt.Errorf(\"could not open file: %w\", err)\n"), - added: []byte("return fmt.Errorf(\"failed to read config: %w\", err)\n"), - threshold: 0.5, - wantHasUnchanged: true, - }, - } - - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - result := diff.CharDiff(tt.removed, tt.added, diff.WithSimilarityThreshold(tt.threshold)) - - assertJoinInvariant(t, result, tt.removed, tt.added) - - if tt.wantAllChanged { - assertAllChangedExceptNL(t, result.Removed, "removed") - assertAllChangedExceptNL(t, result.Added, "added") - } - - if tt.wantHasUnchanged { - assertHasUnchanged(t, result.Removed) - } - }) - } -} - -// BenchmarkCharDiff benchmarks the CharDiff function. -func BenchmarkCharDiff(b *testing.B) { - removed := []byte("the quick brown fox jumps over the lazy dog\n") - added := []byte("the quick brown cat jumps over the lazy frog\n") - - b.ResetTimer() - - for b.Loop() { - diff.CharDiff(removed, added) - } -} - -// FuzzCharDiff verifies CharDiff never panics, terminates, and produces segments -// whose concatenation equals the original input on each side. -func FuzzCharDiff(f *testing.F) { - f.Add([]byte("hello\n"), []byte("hello\n")) - f.Add([]byte("a\n"), []byte("b\n")) - f.Add([]byte("the quick brown fox\n"), []byte("the quick brown cat\n")) - f.Add([]byte(strings.Repeat("a", 10)+"\n"), []byte(strings.Repeat("b", 10)+"\n")) - f.Add([]byte("héllo\n"), []byte("wörld\n")) - f.Add([]byte(""), []byte("content\n")) - f.Add([]byte("content\n"), []byte("")) - - f.Fuzz(func(t *testing.T, removed, added []byte) { - result := diff.CharDiff(removed, added) - - if joinSegments(result.Removed) != string(removed) { - t.Fatalf("removed segments join = %q, want %q", joinSegments(result.Removed), string(removed)) - } - - if joinSegments(result.Added) != string(added) { - t.Fatalf("added segments join = %q, want %q", joinSegments(result.Added), string(added)) - } - - if string(removed) == string(added) { - for i, seg := range result.Removed { - if seg.Changed { - t.Fatalf("removed segment[%d] Changed=true for identical inputs", i) - } - } - - for i, seg := range result.Added { - if seg.Changed { - t.Fatalf("added segment[%d] Changed=true for identical inputs", i) - } - } - } - }) -} - -func assertJoinInvariant(t *testing.T, result diff.InlineChange, removed, added []byte) { - t.Helper() - - if got := joinSegments(result.Removed); got != string(removed) { - t.Errorf("removed segments join = %q, want %q", got, string(removed)) - } - - if got := joinSegments(result.Added); got != string(added) { - t.Errorf("added segments join = %q, want %q", got, string(added)) - } -} - -func assertNoneChanged(t *testing.T, segs []diff.Segment, side string) { - t.Helper() - - for i, seg := range segs { - if seg.Changed { - t.Errorf("%s segment[%d] Changed=true, want false for identical inputs", side, i) - } - } -} - -func anyChanged(segs []diff.Segment) bool { - for _, s := range segs { - if s.Changed { - return true - } - } - - return false -} - -// assertAllChangedExceptNL asserts that all segments are Changed=true, except for a -// trailing standalone newline segment which is always Changed=false (to prevent ANSI -// background colours from bleeding onto the next terminal line). -func assertAllChangedExceptNL(t *testing.T, segs []diff.Segment, side string) { - t.Helper() - - for i, seg := range segs { - isTrailingNL := len(seg.Text) == 1 && seg.Text[0] == '\n' - if !seg.Changed && !isTrailingNL { - t.Errorf("%s segment[%d] Changed=false, want whole-line fallback", side, i) - } - } -} - -// assertHasUnchanged asserts that at least one segment in segs has Changed=false, -// meaning intraline highlighting found common content. -func assertHasUnchanged(t *testing.T, segs []diff.Segment) { - t.Helper() - - for _, seg := range segs { - if !seg.Changed { - return - } - } - - t.Error("expected at least one unchanged segment for similar lines") -} - -func joinSegments(segs []diff.Segment) string { - var sb strings.Builder - for _, s := range segs { - sb.Write(s.Text) - } - - return sb.String() -} - -func TestWordDiff(t *testing.T) { - tests := []struct { - name string - removed []byte - added []byte - wantAllUnchanged bool - wantHasChanged bool - }{ - { - name: "identical lines - all segments unchanged", - removed: []byte("return foo\n"), - added: []byte("return foo\n"), - wantAllUnchanged: true, - }, - { - name: "changed word - only the word is highlighted", - removed: []byte("return foo\n"), - added: []byte("return bar\n"), - wantHasChanged: true, - }, - { - name: "completely different lines", - removed: []byte("abc def\n"), - added: []byte("xyz qrs\n"), - wantHasChanged: true, - }, - { - name: "empty removed", - removed: []byte(""), - added: []byte("new content\n"), - wantHasChanged: true, - }, - { - name: "invalid UTF-8 falls back to whole-line", - removed: []byte("\xff\xfe old\n"), - added: []byte("new content\n"), - wantHasChanged: true, - }, - } - - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - result := diff.WordDiff(tt.removed, tt.added) - - assertJoinInvariant(t, result, tt.removed, tt.added) - - if tt.wantAllUnchanged { - assertNoneChanged(t, result.Removed, "removed") - assertNoneChanged(t, result.Added, "added") - } - - if tt.wantHasChanged { - if !anyChanged(result.Removed) && !anyChanged(result.Added) { - t.Error("WordDiff on differing inputs should produce at least one Changed segment") - } - } - }) - } -} - -func FuzzWordDiff(f *testing.F) { - f.Add([]byte("return foo\n"), []byte("return bar\n")) - f.Add([]byte("hello world\n"), []byte("hello earth\n")) - f.Add([]byte(""), []byte("")) - - f.Fuzz(func(t *testing.T, removed, added []byte) { - got := diff.WordDiff(removed, added) - - var rConcat []byte - for _, s := range got.Removed { - rConcat = append(rConcat, s.Text...) - } - - if !bytes.Equal(rConcat, removed) { - t.Fatalf("Removed concat %q != input %q", rConcat, removed) - } - - var aConcat []byte - for _, s := range got.Added { - aConcat = append(aConcat, s.Text...) - } - - if !bytes.Equal(aConcat, added) { - t.Fatalf("Added concat %q != input %q", aConcat, added) - } - }) -} diff --git a/chars.go b/chars.go deleted file mode 100644 index b4798dd..0000000 --- a/chars.go +++ /dev/null @@ -1,576 +0,0 @@ -package diff - -import ( - "bytes" - "unicode" - "unicode/utf8" -) - -// Segment is a contiguous run of text from a line, tagged as equal or changed -// relative to the other side of the diff. -type Segment struct { - Text []byte // the raw bytes of this segment - Changed bool // true if this segment differs from the corresponding side -} - -// InlineChange holds the character-level diff breakdown for a removed/added line pair. -// -// Removed and Added are parallel segment lists whose concatenated Text fields -// reconstruct the original removed and added lines respectively. -type InlineChange struct { - Removed []Segment - Added []Segment -} - -// CharDiff computes character-level diff segments for a removed/added line pair. -// It uses an O(mn) LCS algorithm on runes — acceptable since individual diff lines are short. -// -// Behaviour: -// - Identical inputs return all-unchanged segments (Changed: false throughout). -// - Trailing newlines are stripped before diffing and reattached afterwards. -// A trailing newline is never placed inside a Changed segment to prevent ANSI -// background colours bleeding onto the next terminal line when rendered. -// - If either side contains invalid UTF-8, a single whole-line Changed segment -// is returned as a fallback. -// - If either side exceeds 500 runes, a single whole-line Changed segment is -// returned to avoid O(mn) cost on minified or generated content. -// - If the similarity ratio (2*equalRunes / totalRunes) is below the threshold -// set by [WithSimilarityThreshold] (default 0.5), a whole-line Changed segment -// is returned — intraline highlighting of very different lines is noisy. -// -// The concatenation of segment Text fields on each side always equals the -// original input byte-for-byte. -func CharDiff(removed, added []byte, opts ...Option) InlineChange { - cfg := applyOptions(opts) - - // Identical inputs: short-circuit before any UTF-8 handling. This also - // covers identical invalid UTF-8, where fallback would wrongly return - // Changed:true segments. - if bytes.Equal(removed, added) { - seg := Segment{Text: bytes.Clone(removed), Changed: false} - - return InlineChange{ - Removed: []Segment{seg}, - Added: []Segment{{Text: bytes.Clone(added), Changed: false}}, - } - } - - // Strip trailing newline, remember whether each side had one. - removedNL := len(removed) > 0 && removed[len(removed)-1] == '\n' - addedNL := len(added) > 0 && added[len(added)-1] == '\n' - - removedCore := removed - if removedNL { - removedCore = removed[:len(removed)-1] - } - - addedCore := added - if addedNL { - addedCore = added[:len(added)-1] - } - - // Fall back to whole-line diff for invalid UTF-8: converting invalid bytes - // to runes replaces them with U+FFFD, making it impossible to reconstruct - // the original bytes from the segments. - if !utf8.Valid(removedCore) || !utf8.Valid(addedCore) { - return fallback(removed, added) - } - - oldRunes := []rune(string(removedCore)) - newRunes := []rune(string(addedCore)) - - // Safety cap: avoid O(mn) on large inputs (minified/generated content). - if len(oldRunes) > 500 || len(newRunes) > 500 { - return fallback(removed, added) - } - - segs := lcsSegments(oldRunes, newRunes, len(removedCore), len(addedCore)) - - // Similarity ratio gate: if the ratio of equal runes to total runes is below - // the threshold, intraline highlighting would be more noise than signal. - // Build the whole-line fallback using the stripped core slices so that - // reattachNL can place the trailing newline outside the Changed segment — - // a highlighted \n bleeds ANSI background colour onto the next terminal line. - totalRunes := len(oldRunes) + len(newRunes) - if totalRunes > 0 { - equalRunes := 0 - - for _, seg := range segs.removed { - if !seg.Changed { - equalRunes += utf8.RuneCount(seg.Text) - } - } - - ratio := float64(similarityRatioScale*equalRunes) / float64(totalRunes) - if ratio < cfg.similarityThreshold { - var rSegs []Segment - if len(removedCore) > 0 { - rSegs = []Segment{{Text: bytes.Clone(removedCore), Changed: true}} - } - - var aSegs []Segment - if len(addedCore) > 0 { - aSegs = []Segment{{Text: bytes.Clone(addedCore), Changed: true}} - } - - return InlineChange{ - Removed: reattachNL(rSegs, removedNL), - Added: reattachNL(aSegs, addedNL), - } - } - } - - removedSegs := reattachNL(segs.removed, removedNL) - addedSegs := reattachNL(segs.added, addedNL) - - return InlineChange{Removed: removedSegs, Added: addedSegs} -} - -// tokenize splits b into word and delimiter tokens. -// Words are maximal runs of Unicode letters, digits, and underscores. -// Every other rune is an individual delimiter token. -// Tokens are subslices of b — no allocation beyond the slice header list. -func tokenize(b []byte) [][]byte { - var tokens [][]byte - - i := 0 - for i < len(b) { - r, sz := utf8.DecodeRune(b[i:]) - if unicode.IsLetter(r) || unicode.IsDigit(r) || r == '_' { - start := i - for i < len(b) { - r, sz = utf8.DecodeRune(b[i:]) - if !unicode.IsLetter(r) && !unicode.IsDigit(r) && r != '_' { - break - } - - i += sz - } - - tokens = append(tokens, b[start:i]) - } else { - tokens = append(tokens, b[i:i+sz]) - i += sz - } - } - - return tokens -} - -// tokenOp is a single edit operation produced during word-token LCS backtracking. -type tokenOp struct { - tok []byte - kind byte // 'e' equal, 'd' delete, 'i' insert -} - -// wordLCSSegments builds the LCS table for token slices and returns Segment-based sides. -// It is the word-token analogue of lcsSegments: tokens replace runes, bytes.Equal -// replaces rune equality, and each token's bytes are appended to the backing buffers. -// rCap and aCap must equal the byte lengths of the removed and added core inputs so -// the backing buffers never reallocate. -func wordLCSSegments(old, newToks [][]byte, rCap, aCap int) sides { - m, n := len(old), len(newToks) - - dp := make([]int, (m+1)*(n+1)) - - stride := n + 1 - for i := 1; i <= m; i++ { - for j := 1; j <= n; j++ { - if bytes.Equal(old[i-1], newToks[j-1]) { - dp[i*stride+j] = dp[(i-1)*stride+(j-1)] + 1 - } else { - dp[i*stride+j] = max(dp[(i-1)*stride+j], dp[i*stride+(j-1)]) - } - } - } - - ops := make([]tokenOp, 0, m+n) - - i, j := m, n - for i > 0 || j > 0 { - switch { - case i > 0 && j > 0 && bytes.Equal(old[i-1], newToks[j-1]): - ops = append(ops, tokenOp{tok: old[i-1], kind: 'e'}) - i-- - j-- - case j > 0 && (i == 0 || dp[i*stride+(j-1)] >= dp[(i-1)*stride+j]): - ops = append(ops, tokenOp{tok: newToks[j-1], kind: 'i'}) - j-- - default: - ops = append(ops, tokenOp{tok: old[i-1], kind: 'd'}) - i-- - } - } - - for l, r := 0, len(ops)-1; l < r; l, r = l+1, r-1 { - ops[l], ops[r] = ops[r], ops[l] - } - - return mergeTokenSegments(ops, rCap, aCap) -} - -// mergeTokenSegments merges consecutive same-kind token ops into Segment runs. -// rCap and aCap are the byte capacities for the removed and added backing buffers; -// they must equal the byte lengths of the respective core inputs so the buffers -// never reallocate, keeping all segment Text subslices valid. -func mergeTokenSegments(ops []tokenOp, rCap, aCap int) sides { - removedBacking := make([]byte, 0, rCap) - addedBacking := make([]byte, 0, aCap) - removedSegs := make([]Segment, 0, segmentInitCap) - addedSegs := make([]Segment, 0, segmentInitCap) - - for _, o := range ops { - nb := len(o.tok) - - switch o.kind { - case 'e': - removedBacking = append(removedBacking, o.tok...) - - if len(removedSegs) > 0 && !removedSegs[len(removedSegs)-1].Changed { - last := &removedSegs[len(removedSegs)-1] - last.Text = last.Text[:len(last.Text)+nb] - } else { - removedSegs = append( - removedSegs, - Segment{Text: removedBacking[len(removedBacking)-nb:], Changed: false}, - ) - } - - addedBacking = append(addedBacking, o.tok...) - - if len(addedSegs) > 0 && !addedSegs[len(addedSegs)-1].Changed { - last := &addedSegs[len(addedSegs)-1] - last.Text = last.Text[:len(last.Text)+nb] - } else { - addedSegs = append(addedSegs, Segment{Text: addedBacking[len(addedBacking)-nb:], Changed: false}) - } - - case 'd': - removedBacking = append(removedBacking, o.tok...) - - if len(removedSegs) > 0 && removedSegs[len(removedSegs)-1].Changed { - last := &removedSegs[len(removedSegs)-1] - last.Text = last.Text[:len(last.Text)+nb] - } else { - removedSegs = append(removedSegs, Segment{Text: removedBacking[len(removedBacking)-nb:], Changed: true}) - } - - case 'i': - addedBacking = append(addedBacking, o.tok...) - - if len(addedSegs) > 0 && addedSegs[len(addedSegs)-1].Changed { - last := &addedSegs[len(addedSegs)-1] - last.Text = last.Text[:len(last.Text)+nb] - } else { - addedSegs = append(addedSegs, Segment{Text: addedBacking[len(addedBacking)-nb:], Changed: true}) - } - - default: - // op.kind is always 'e', 'd', or 'i' — wordLCSSegments is the only producer. - } - } - - if len(removedSegs) == 0 { - removedSegs = append(removedSegs, Segment{Text: []byte{}, Changed: false}) - } - - if len(addedSegs) == 0 { - addedSegs = append(addedSegs, Segment{Text: []byte{}, Changed: false}) - } - - return sides{removed: removedSegs, added: addedSegs} -} - -// WordDiff computes word-level diff segments for a removed/added line pair. -// It tokenises each line into words (maximal runs of Unicode letters, digits, -// and underscores) and delimiters (all other runes, individually), then runs -// an LCS on the token slices. Changed segments cover whole words or delimiter -// sequences, producing wider, cleaner highlights than [CharDiff] for prose or -// code identifiers. -// -// The same guards as [CharDiff] apply: -// - Identical inputs return all-unchanged segments. -// - Trailing newlines are stripped before diffing and reattached afterwards; -// a trailing newline is never placed inside a Changed segment. -// - Invalid UTF-8 returns a whole-line Changed segment. -// - Either side exceeding 500 tokens returns a whole-line Changed segment. -// - If the similarity ratio (2*equalBytes / totalBytes) is below the threshold -// set by [WithSimilarityThreshold] (default 0.5), a whole-line Changed -// segment is returned. -// -// The concatenation of segment Text fields on each side always equals the -// original input byte-for-byte. -func WordDiff(removed, added []byte, opts ...Option) InlineChange { - cfg := applyOptions(opts) - - if bytes.Equal(removed, added) { - return InlineChange{ - Removed: []Segment{{Text: bytes.Clone(removed), Changed: false}}, - Added: []Segment{{Text: bytes.Clone(added), Changed: false}}, - } - } - - removedNL := len(removed) > 0 && removed[len(removed)-1] == '\n' - addedNL := len(added) > 0 && added[len(added)-1] == '\n' - - removedCore := removed - if removedNL { - removedCore = removed[:len(removed)-1] - } - - addedCore := added - if addedNL { - addedCore = added[:len(added)-1] - } - - if !utf8.Valid(removedCore) || !utf8.Valid(addedCore) { - return fallback(removed, added) - } - - oldToks := tokenize(removedCore) - newToks := tokenize(addedCore) - - if len(oldToks) > 500 || len(newToks) > 500 { - return fallback(removed, added) - } - - segs := wordLCSSegments(oldToks, newToks, len(removedCore), len(addedCore)) - - // Similarity ratio gate using byte counts for consistency with CharDiff. - totalBytes := len(removedCore) + len(addedCore) - if totalBytes > 0 { - equalBytes := 0 - - for _, seg := range segs.removed { - if !seg.Changed { - equalBytes += len(seg.Text) - } - } - - ratio := float64(similarityRatioScale*equalBytes) / float64(totalBytes) - if ratio < cfg.similarityThreshold { - var rSegs []Segment - if len(removedCore) > 0 { - rSegs = []Segment{{Text: bytes.Clone(removedCore), Changed: true}} - } - - var aSegs []Segment - if len(addedCore) > 0 { - aSegs = []Segment{{Text: bytes.Clone(addedCore), Changed: true}} - } - - return InlineChange{ - Removed: reattachNL(rSegs, removedNL), - Added: reattachNL(aSegs, addedNL), - } - } - } - - return InlineChange{ - Removed: reattachNL(segs.removed, removedNL), - Added: reattachNL(segs.added, addedNL), - } -} - -// fallback returns a single Changed segment per side (whole-line fallback). -// Copies the input slices to avoid aliasing the caller's memory. -func fallback(removed, added []byte) InlineChange { - result := InlineChange{} - - if len(removed) > 0 { - cp := make([]byte, len(removed)) - copy(cp, removed) - result.Removed = []Segment{{Text: cp, Changed: true}} - } - - if len(added) > 0 { - cp := make([]byte, len(added)) - copy(cp, added) - result.Added = []Segment{{Text: cp, Changed: true}} - } - - return result -} - -// reattachNL returns a new segment slice with a newline reattached after the -// last segment. The input slice is not modified. -// -// If the last segment is Changed, the newline is appended as a separate -// unchanged segment rather than being included in the highlight span — a -// highlighted \n causes the ANSI background colour to bleed onto the next -// terminal line. -func reattachNL(segs []Segment, hadNL bool) []Segment { - if !hadNL { - return segs - } - - if len(segs) == 0 { - return []Segment{{Text: []byte{'\n'}, Changed: false}} - } - - last := segs[len(segs)-1] - - if last.Changed { - result := make([]Segment, 0, len(segs)+1) - result = append(result, segs...) - - return append(result, Segment{Text: []byte{'\n'}, Changed: false}) - } - - result := make([]Segment, len(segs)) - copy(result, segs) - - last.Text = append(bytes.Clone(last.Text), '\n') - result[len(result)-1] = last - - return result -} - -// sides holds parallel removed/added segment lists built during backtracking. -type sides struct { - removed []Segment - added []Segment -} - -// op is a single edit operation produced during LCS backtracking. -type op struct { - r rune - kind byte // 'e' equal, 'd' delete, 'i' insert -} - -// lcsSegments builds the LCS table and backtracks to produce Equal/Delete/Insert -// edit operations, then merges consecutive same-kind ops into Segment runs. -// rCap and aCap are the byte lengths of the removed and added inputs (without -// their trailing newlines) and are used to pre-allocate segment backing buffers. -func lcsSegments(old, newText []rune, rCap, aCap int) sides { - m, n := len(old), len(newText) - - // Build LCS DP table using a flat slice to avoid m+1 separate allocations. - dp := make([]int, (m+1)*(n+1)) - - stride := n + 1 - for i := 1; i <= m; i++ { - for j := 1; j <= n; j++ { - if old[i-1] == newText[j-1] { - dp[i*stride+j] = dp[(i-1)*stride+(j-1)] + 1 - } else { - dp[i*stride+j] = max(dp[(i-1)*stride+j], dp[i*stride+(j-1)]) - } - } - } - - // Backtrack to build edit ops, then reverse. - ops := make([]op, 0, m+n) - - i, j := m, n - for i > 0 || j > 0 { - switch { - case i > 0 && j > 0 && old[i-1] == newText[j-1]: - ops = append(ops, op{r: old[i-1], kind: 'e'}) - i-- - j-- - case j > 0 && (i == 0 || dp[i*stride+(j-1)] >= dp[(i-1)*stride+j]): - ops = append(ops, op{r: newText[j-1], kind: 'i'}) - j-- - default: - ops = append(ops, op{r: old[i-1], kind: 'd'}) - i-- - } - } - - // Reverse ops (they were built backwards). - for l, r := 0, len(ops)-1; l < r; l, r = l+1, r-1 { - ops[l], ops[r] = ops[r], ops[l] - } - - return mergeSegments(ops, rCap, aCap) -} - -// similarityRatioScale is the multiplier used in the similarity ratio formula: -// ratio = 2*equalRunes / totalRunes. The factor of 2 ensures that two identical -// lines score 1.0 (each equal rune is counted once on each side). -const similarityRatioScale = 2 - -// segmentInitCap is the initial capacity for segment slices in mergeSegments. -// Most diff lines produce far fewer than 8 segments; this avoids the first -// few re-allocations on typical input. -const segmentInitCap = 8 - -// mergeSegments merges consecutive same-kind ops into Segment runs. -// rCap and aCap are the byte capacities for the removed and added backing -// buffers; they must equal the byte lengths of the respective core inputs so -// that the buffers never reallocate, keeping all segment Text subslices valid. -func mergeSegments(ops []op, rCap, aCap int) sides { - removedSegs := make([]Segment, 0, segmentInitCap) - addedSegs := make([]Segment, 0, segmentInitCap) - - // Pre-allocated backing buffers. Sized to the exact input byte lengths so - // no reallocation occurs and existing Text subslices are never invalidated. - removedBacking := make([]byte, 0, rCap) - addedBacking := make([]byte, 0, aCap) - - var buf [utf8.UTFMax]byte - for _, o := range ops { - nb := utf8.EncodeRune(buf[:], o.r) - r := buf[:nb] - - switch o.kind { - case 'e': - removedBacking = append(removedBacking, r...) - - if len(removedSegs) > 0 && !removedSegs[len(removedSegs)-1].Changed { - last := &removedSegs[len(removedSegs)-1] - last.Text = last.Text[:len(last.Text)+nb] - } else { - removedSegs = append( - removedSegs, - Segment{Text: removedBacking[len(removedBacking)-nb:], Changed: false}, - ) - } - - addedBacking = append(addedBacking, r...) - - if len(addedSegs) > 0 && !addedSegs[len(addedSegs)-1].Changed { - last := &addedSegs[len(addedSegs)-1] - last.Text = last.Text[:len(last.Text)+nb] - } else { - addedSegs = append(addedSegs, Segment{Text: addedBacking[len(addedBacking)-nb:], Changed: false}) - } - - case 'd': - removedBacking = append(removedBacking, r...) - - if len(removedSegs) > 0 && removedSegs[len(removedSegs)-1].Changed { - last := &removedSegs[len(removedSegs)-1] - last.Text = last.Text[:len(last.Text)+nb] - } else { - removedSegs = append(removedSegs, Segment{Text: removedBacking[len(removedBacking)-nb:], Changed: true}) - } - - case 'i': - addedBacking = append(addedBacking, r...) - - if len(addedSegs) > 0 && addedSegs[len(addedSegs)-1].Changed { - last := &addedSegs[len(addedSegs)-1] - last.Text = last.Text[:len(last.Text)+nb] - } else { - addedSegs = append(addedSegs, Segment{Text: addedBacking[len(addedBacking)-nb:], Changed: true}) - } - - default: - // op.kind is always 'e', 'd', or 'i' — lcsSegments is the only producer. - } - } - - // Handle empty inputs: produce a single unchanged empty segment so callers - // always have at least one segment to work with. - if len(removedSegs) == 0 { - removedSegs = append(removedSegs, Segment{Text: []byte{}, Changed: false}) - } - - if len(addedSegs) == 0 { - addedSegs = append(addedSegs, Segment{Text: []byte{}, Changed: false}) - } - - return sides{removed: removedSegs, added: addedSegs} -} diff --git a/diff.go b/diff.go index 4a0d394..e291f31 100644 --- a/diff.go +++ b/diff.go @@ -1,5 +1,5 @@ -// Package diff provides an anchored diff algorithm with structured line output, -// character-level inline diff, and a plain unified-diff formatter. +// Package diff provides an anchored diff algorithm with structured line output +// and a plain unified-diff formatter. // // The core algorithm is derived from the Go standard library's internal/diff package // (https://github.com/golang/go/tree/master/src/internal/diff). @@ -52,134 +52,86 @@ func (k LineKind) String() string { // For KindHeader lines, Content holds the full raw line including its newline. // For all other kinds, Content holds the line text as it appeared in the source, // including its trailing newline if present. Content aliases the original input -// passed to [Lines] or [Diff]; callers must not modify it. +// passed to [New]; callers must not modify it. type Line struct { Content []byte Kind LineKind } -// LinePair groups a contiguous block of removed lines with the immediately -// following block of added lines. Either field may be nil if the change is -// a pure insertion or pure deletion. -// -// LinePair is produced by [Pairs] and is intended for downstream consumers -// (e.g. custom renderers) that need to perform per-pair operations such as -// intraline diff highlighting. -type LinePair struct { - Removed []Line - Added []Line -} - -// Pairs groups the KindRemoved and KindAdded lines from a structured diff into -// LinePair values. Each LinePair holds one contiguous block of removed lines -// and/or the immediately following block of added lines. KindContext and -// KindHeader lines are skipped. -// -// The input is typically the slice returned by [Lines]. Pairs returns nil if -// lines contains no KindRemoved or KindAdded lines. -// -// The Removed and Added slices in each LinePair are subslices of the input; -// callers must not modify the input slice or the Line values within it after -// calling Pairs. -func Pairs(lines []Line) []LinePair { - var result []LinePair - - i := 0 - for i < len(lines) { - kind := lines[i].Kind - if kind != KindRemoved && kind != KindAdded { - i++ - continue - } +const ( + // defaultContextLines is the default number of unchanged context lines shown around each change. + defaultContextLines = 3 +) - // Collect contiguous removed block. - start := i - for i < len(lines) && lines[i].Kind == KindRemoved { - i++ - } +// config holds resolved options for a diff operation. +type config struct { + contextLines int +} - removed := lines[start:i] - if len(removed) == 0 { - removed = nil - } +// defaultConfig returns a config with package defaults. +func defaultConfig() config { + return config{contextLines: defaultContextLines} +} - // Collect immediately following added block. - start = i - for i < len(lines) && lines[i].Kind == KindAdded { - i++ - } +// Option is a functional option that configures a diff operation. +type Option func(*config) - added := lines[start:i] - if len(added) == 0 { - added = nil - } +// WithContext sets the number of unchanged context lines shown around each change. +// The default is 3. Pass 0 to suppress context entirely. +func WithContext(n int) Option { + return func(c *config) { c.contextLines = n } +} - result = append(result, LinePair{Removed: removed, Added: added}) +// applyOptions builds a config from defaults and the provided options. +func applyOptions(opts []Option) config { + cfg := defaultConfig() + for _, o := range opts { + o(&cfg) } - return result + return cfg } -// pair is a pair of line indexes, one for each side of the diff. -type pair struct{ x, y int } +// Diff is the result of comparing two texts. The zero value represents no changes +// (identical inputs). Use [New] to compute a diff. +type Diff struct { + lines []Line // nil when inputs are equal +} -// Lines returns the structured diff lines for old and newText. -// Returns nil if old and newText are identical. -// -// The returned slice contains KindHeader lines for the diff/---/+++/@@ metadata, -// followed by KindContext, KindRemoved, and KindAdded lines for the diff body. -// Content on each Line holds the raw line text without any diff prefix. -// -// The structured form is useful for custom rendering; for plain unified-diff -// text output use [Diff]. -func Lines(oldName string, old []byte, newName string, newText []byte, opts ...Option) []Line { +// New computes an anchored diff between old and new and returns a Diff. +// Call [Diff.Equal] to test whether the inputs were identical. +func New(oldName string, old []byte, newName string, newText []byte, opts ...Option) Diff { if bytes.Equal(old, newText) { - return nil + return Diff{} } - return computeLines(oldName, old, newName, newText, applyOptions(opts)) + return Diff{lines: computeLines(oldName, old, newName, newText, applyOptions(opts))} } -// Diff returns an anchored unified diff of old and newText as raw bytes. -// Returns nil if old and newText are identical. -// -// Unix diff implementations typically look for a diff with the smallest number -// of lines inserted and removed, which can in the worst case take time quadratic -// in the number of lines. As a result, many implementations either can be made to -// run for a long time or cut off the search after a predetermined amount of work. -// -// In contrast, this implementation looks for a diff with the smallest number of -// "unique" lines inserted and removed, where unique means a line that appears just -// once in both old and new. We call this an "anchored diff" because the unique -// lines anchor the chosen matching regions. An anchored diff is usually clearer -// than a standard diff, because the algorithm does not try to reuse unrelated blank -// lines or closing braces. The algorithm also guarantees to run in O(n log n) time -// instead of the standard O(n²) time. -// -// Some systems call this approach a "patience diff," named for the "patience -// sorting" algorithm, itself named for a solitaire card game. We avoid that name -// for two reasons. First, the name has been used for a few different variants of -// the algorithm, so it is imprecise. Second, the name is frequently interpreted as -// meaning that you have to wait longer (to be patient) for the diff, meaning that -// it is a slower algorithm, when in fact the algorithm is faster than the standard one. +// Equal reports whether the two inputs were identical (no changes). +func (d Diff) Equal() bool { + return len(d.lines) == 0 +} + +// Lines returns the structured diff lines, or nil if the inputs were equal. // -// For structured line-by-line output use [Lines]. -func Diff( - oldName string, - old []byte, - newName string, - newText []byte, - opts ...Option, -) []byte { - if bytes.Equal(old, newText) { - return nil - } +// The returned slice contains [KindHeader] lines for the diff/---/+++/@@ metadata, +// followed by [KindContext], [KindRemoved], and [KindAdded] lines for the diff body. +// Content on each [Line] holds the raw line text without any diff prefix. +func (d Diff) Lines() []Line { + return d.lines +} - structured := computeLines(oldName, old, newName, newText, applyOptions(opts)) +// String implements [fmt.Stringer], returning the diff as a plain unified-diff string. +// Returns an empty string when the inputs were equal. +func (d Diff) String() string { + if d.Equal() { + return "" + } var out bytes.Buffer - for _, line := range structured { + for _, line := range d.lines { switch line.Kind { case KindHeader: out.Write(line.Content) @@ -197,9 +149,12 @@ func Diff( } } - return out.Bytes() + return out.String() } +// pair is a pair of line indexes, one for each side of the diff. +type pair struct{ x, y int } + // groupIntoHunks groups the unique-line match pairs returned by [tgs] into // context-annotated diff Lines. // pairs is the output of [tgs] (including sentinels). x and y are the full line @@ -514,54 +469,6 @@ func splitLines(x []byte) [][]byte { return lines } -const ( - // defaultContextLines is the default number of unchanged context lines shown around each change. - defaultContextLines = 3 - - // defaultSimilarityThreshold is the default minimum similarity ratio for intraline highlighting. - defaultSimilarityThreshold = 0.5 -) - -// config holds resolved options for a diff operation. -type config struct { - contextLines int - similarityThreshold float64 -} - -// defaultConfig returns a config with package defaults. -func defaultConfig() config { - return config{ - contextLines: defaultContextLines, - similarityThreshold: defaultSimilarityThreshold, - } -} - -// Option is a functional option that configures a diff operation. -type Option func(*config) - -// WithContext sets the number of unchanged context lines shown around each change. -// The default is 3. Pass 0 to suppress context entirely. -func WithContext(n int) Option { - return func(c *config) { c.contextLines = n } -} - -// WithSimilarityThreshold sets the minimum similarity ratio for intraline highlighting. -// ratio = 2*equalRunes / (len(removedRunes) + len(addedRunes)). -// Default is 0.5. Use 0.0 to always highlight; 1.0 to never highlight. -func WithSimilarityThreshold(t float64) Option { - return func(c *config) { c.similarityThreshold = t } -} - -// applyOptions builds a config from defaults and the provided options. -func applyOptions(opts []Option) config { - cfg := defaultConfig() - for _, o := range opts { - o(&cfg) - } - - return cfg -} - // tgsYStep is the per-occurrence decrement applied to y-side entries in the // tgs occurrence map. It is 4× the x-side step (1) so that x and y counts // occupy separate bit ranges, allowing a unique line to be identified by the diff --git a/diff_test.go b/diff_test.go index 7c4e2de..c0e7446 100644 --- a/diff_test.go +++ b/diff_test.go @@ -12,7 +12,7 @@ import ( "golang.org/x/tools/txtar" ) -// TestLines verifies the Lines function returns structured diff lines. +// TestLines verifies the Lines method returns structured diff lines. func TestLines(t *testing.T) { tests := []struct { name string @@ -118,7 +118,7 @@ func TestLines(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - got := diff.Lines(tt.oldName, tt.old, tt.newName, tt.newText) + got := diff.New(tt.oldName, tt.old, tt.newName, tt.newText).Lines() if tt.want == nil { if got != nil { t.Fatalf("Lines() = %v, want nil", got) @@ -150,8 +150,8 @@ func TestLines(t *testing.T) { } } -// TestDiffNilOnEqual verifies Diff returns nil when old and newText are identical. -func TestDiffNilOnEqual(t *testing.T) { +// TestEqual verifies Equal returns true when old and new are identical. +func TestEqual(t *testing.T) { tests := []struct { name string old []byte @@ -171,14 +171,62 @@ func TestDiffNilOnEqual(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - if got := diff.Diff("a", tt.old, "b", tt.new); got != nil { - t.Fatalf("Diff() = %q, want nil for equal inputs", got) + if got := diff.New("a", tt.old, "b", tt.new); !got.Equal() { + t.Fatal("Equal() = false, want true for identical inputs") } }) } } -// Test drives Diff against the *.txtar files in testdata/. +// TestString verifies String returns an empty string for equal inputs and a +// non-empty unified diff for differing inputs. +func TestString(t *testing.T) { + tests := []struct { + name string + wantContain string + old []byte + new []byte + wantEmpty bool + }{ + { + name: "equal inputs produce empty string", + old: []byte("same\n"), + new: []byte("same\n"), + wantEmpty: true, + }, + { + name: "both empty inputs produce empty string", + old: []byte(""), + new: []byte(""), + wantEmpty: true, + }, + { + name: "differing inputs produce non-empty unified diff", + old: []byte("hello\nworld\n"), + new: []byte("hello\nearth\n"), + wantContain: "- world", + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + got := diff.New("a", tt.old, "b", tt.new).String() + if tt.wantEmpty { + if got != "" { + t.Fatalf("String() = %q, want empty string for equal inputs", got) + } + + return + } + + if !strings.Contains(got, tt.wantContain) { + t.Fatalf("String() = %q, want it to contain %q", got, tt.wantContain) + } + }) + } +} + +// Test drives New against the *.txtar files in testdata/. func Test(t *testing.T) { files, err := filepath.Glob(filepath.Join("testdata", "*.txtar")) if err != nil { @@ -203,17 +251,17 @@ func Test(t *testing.T) { t.Fatalf("%s: want three files, third named \"diff\", got: %v", file, archive.Files) } - diffs := diff.Diff( + got := diff.New( archive.Files[0].Name, clean(archive.Files[0].Data), archive.Files[1].Name, clean(archive.Files[1].Data), - ) - want := clean(archive.Files[2].Data) + ).String() + want := string(clean(archive.Files[2].Data)) - if !bytes.Equal(diffs, want) { + if got != want { t.Fatalf("%s: have:\n%s\nwant:\n%s\n%s", file, - diffs, want, diff.Diff("have", diffs, "want", want)) + got, want, diff.New("have", []byte(got), "want", []byte(want))) } }) } @@ -230,20 +278,28 @@ func FuzzLines(f *testing.F) { f.Add([]byte(" \n\t\n"), []byte(" \n\t\n")) f.Fuzz(func(t *testing.T, old, newContent []byte) { - result := diff.Lines("a", old, "b", newContent) + d := diff.New("a", old, "b", newContent) if bytes.Equal(old, newContent) { - if result != nil { + if !d.Equal() { + t.Fatal("Equal() = false for equal inputs") + } + + if d.Lines() != nil { t.Fatal("Lines() = non-nil for equal inputs") } } else { - if result == nil { + if d.Equal() { + t.Fatal("Equal() = true for non-equal inputs") + } + + if d.Lines() == nil { t.Fatal("Lines() = nil for non-equal inputs") } } }) } -// BenchmarkLines benchmarks the Lines function using long.txtar as realistic input. +// BenchmarkLines benchmarks the Lines method using long.txtar as realistic input. func BenchmarkLines(b *testing.B) { contents, err := os.ReadFile(filepath.Join("testdata", "long.txtar")) if err != nil { @@ -257,12 +313,12 @@ func BenchmarkLines(b *testing.B) { b.ResetTimer() for b.Loop() { - diff.Lines(archive.Files[0].Name, old, archive.Files[1].Name, newContent) + diff.New(archive.Files[0].Name, old, archive.Files[1].Name, newContent).Lines() } } -// BenchmarkDiff benchmarks the Diff function using long.txtar as realistic input. -func BenchmarkDiff(b *testing.B) { +// BenchmarkString benchmarks String using long.txtar as realistic input. +func BenchmarkString(b *testing.B) { contents, err := os.ReadFile(filepath.Join("testdata", "long.txtar")) if err != nil { b.Fatalf("could not read long.txtar: %v", err) @@ -275,7 +331,7 @@ func BenchmarkDiff(b *testing.B) { b.ResetTimer() for b.Loop() { - diff.Diff(archive.Files[0].Name, old, archive.Files[1].Name, newContent) + _ = diff.New(archive.Files[0].Name, old, archive.Files[1].Name, newContent).String() } } @@ -308,7 +364,7 @@ func TestWithContextOption(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - got := diff.Lines("old", tt.old, "new", tt.newText, tt.opts...) + got := diff.New("old", tt.old, "new", tt.newText, tt.opts...).Lines() if len(got) != tt.wantLen { t.Fatalf("Lines() returned %d lines, want %d\n%#v", len(got), tt.wantLen, got) } @@ -351,7 +407,7 @@ func TestGroupIntoHunksViaWithContext(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - lines := diff.Lines("old", tt.old, "new", tt.new, tt.opt) + lines := diff.New("old", tt.old, "new", tt.new, tt.opt).Lines() contextCount := 0 @@ -408,7 +464,7 @@ func TestLargeCommonRegionsProduceCorrectLineNumbers(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - lines := diff.Lines("old", []byte(tt.old), "new", []byte(tt.new)) + lines := diff.New("old", []byte(tt.old), "new", []byte(tt.new)).Lines() contextCount := 0 @@ -448,7 +504,12 @@ func TestDisjointFastPath(t *testing.T) { old := []byte(oldLines.String()) newText := []byte(newLines.String()) - lines := diff.Lines("old", old, "new", newText) + d := diff.New("old", old, "new", newText) + if d.Equal() { + t.Fatal("Equal() = true for non-equal inputs") + } + + lines := d.Lines() if lines == nil { t.Fatal("Lines() returned nil for non-equal inputs") } @@ -476,170 +537,6 @@ func TestDisjointFastPath(t *testing.T) { } } -// TestPairs verifies that Pairs groups consecutive removed/added blocks correctly. -func TestPairs(t *testing.T) { - tests := []struct { - name string - lines []diff.Line - want []diff.LinePair - }{ - { - name: "nil input returns nil", - lines: nil, - want: nil, - }, - { - name: "only context lines returns nil", - lines: []diff.Line{ - {Kind: diff.KindContext, Content: []byte("unchanged\n")}, - }, - want: nil, - }, - { - name: "removed followed by added forms one pair", - lines: []diff.Line{ - {Kind: diff.KindContext, Content: []byte("ctx\n")}, - {Kind: diff.KindRemoved, Content: []byte("old\n")}, - {Kind: diff.KindAdded, Content: []byte("new\n")}, - {Kind: diff.KindContext, Content: []byte("ctx2\n")}, - }, - want: []diff.LinePair{ - { - Removed: []diff.Line{{Kind: diff.KindRemoved, Content: []byte("old\n")}}, - Added: []diff.Line{{Kind: diff.KindAdded, Content: []byte("new\n")}}, - }, - }, - }, - { - name: "removed-only block has nil Added", - lines: []diff.Line{ - {Kind: diff.KindRemoved, Content: []byte("gone\n")}, - {Kind: diff.KindContext, Content: []byte("ctx\n")}, - }, - want: []diff.LinePair{ - { - Removed: []diff.Line{{Kind: diff.KindRemoved, Content: []byte("gone\n")}}, - Added: nil, - }, - }, - }, - { - name: "added-only block has nil Removed", - lines: []diff.Line{ - {Kind: diff.KindContext, Content: []byte("ctx\n")}, - {Kind: diff.KindAdded, Content: []byte("new\n")}, - }, - want: []diff.LinePair{ - { - Removed: nil, - Added: []diff.Line{{Kind: diff.KindAdded, Content: []byte("new\n")}}, - }, - }, - }, - { - name: "two separate change blocks produce two pairs", - lines: []diff.Line{ - {Kind: diff.KindRemoved, Content: []byte("a\n")}, - {Kind: diff.KindAdded, Content: []byte("b\n")}, - {Kind: diff.KindContext, Content: []byte("ctx\n")}, - {Kind: diff.KindRemoved, Content: []byte("c\n")}, - {Kind: diff.KindAdded, Content: []byte("d\n")}, - }, - want: []diff.LinePair{ - { - Removed: []diff.Line{{Kind: diff.KindRemoved, Content: []byte("a\n")}}, - Added: []diff.Line{{Kind: diff.KindAdded, Content: []byte("b\n")}}, - }, - { - Removed: []diff.Line{{Kind: diff.KindRemoved, Content: []byte("c\n")}}, - Added: []diff.Line{{Kind: diff.KindAdded, Content: []byte("d\n")}}, - }, - }, - }, - { - name: "header lines are skipped", - lines: []diff.Line{ - {Kind: diff.KindHeader, Content: []byte("@@ -1,1 +1,1 @@\n")}, - {Kind: diff.KindRemoved, Content: []byte("x\n")}, - {Kind: diff.KindAdded, Content: []byte("y\n")}, - }, - want: []diff.LinePair{ - { - Removed: []diff.Line{{Kind: diff.KindRemoved, Content: []byte("x\n")}}, - Added: []diff.Line{{Kind: diff.KindAdded, Content: []byte("y\n")}}, - }, - }, - }, - { - name: "added block before removed block produces two pairs", - lines: []diff.Line{ - {Kind: diff.KindAdded, Content: []byte("new\n")}, - {Kind: diff.KindContext, Content: []byte("ctx\n")}, - {Kind: diff.KindRemoved, Content: []byte("old\n")}, - }, - want: []diff.LinePair{ - { - Removed: nil, - Added: []diff.Line{{Kind: diff.KindAdded, Content: []byte("new\n")}}, - }, - { - Removed: []diff.Line{{Kind: diff.KindRemoved, Content: []byte("old\n")}}, - Added: nil, - }, - }, - }, - } - - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - got := diff.Pairs(tt.lines) - if len(got) != len(tt.want) { - t.Fatalf("Pairs() returned %d pairs, want %d\ngot: %#v\nwant: %#v", - len(got), len(tt.want), got, tt.want) - } - - for i, p := range got { - assertLinePair(t, i, p, tt.want[i]) - } - }) - } -} - -// assertLinePair verifies that a single LinePair matches the expected pair. -func assertLinePair(t *testing.T, i int, got, want diff.LinePair) { - t.Helper() - - if len(got.Removed) != len(want.Removed) { - t.Errorf("pair[%d].Removed len = %d, want %d", i, len(got.Removed), len(want.Removed)) - return - } - - if len(got.Added) != len(want.Added) { - t.Errorf("pair[%d].Added len = %d, want %d", i, len(got.Added), len(want.Added)) - return - } - - for j, line := range got.Removed { - if line.Kind != want.Removed[j].Kind { - t.Errorf("pair[%d].Removed[%d].Kind = %v, want %v", i, j, line.Kind, want.Removed[j].Kind) - } - - if !bytes.Equal(line.Content, want.Removed[j].Content) { - t.Errorf("pair[%d].Removed[%d].Content = %q, want %q", i, j, line.Content, want.Removed[j].Content) - } - } - - for j, line := range got.Added { - if line.Kind != want.Added[j].Kind { - t.Errorf("pair[%d].Added[%d].Kind = %v, want %v", i, j, line.Kind, want.Added[j].Kind) - } - - if !bytes.Equal(line.Content, want.Added[j].Content) { - t.Errorf("pair[%d].Added[%d].Content = %q, want %q", i, j, line.Content, want.Added[j].Content) - } - } -} - func clean(text []byte) []byte { text = bytes.ReplaceAll(text, []byte("$\n"), []byte("\n")) text = bytes.TrimSuffix(text, []byte("^D\n")) diff --git a/render/chars.go b/render/chars.go new file mode 100644 index 0000000..2ee58f6 --- /dev/null +++ b/render/chars.go @@ -0,0 +1,327 @@ +package render + +import ( + "bytes" + "unicode/utf8" +) + +// segment is a contiguous run of text from a line, tagged as equal or changed +// relative to the other side of the diff. +type segment struct { + text []byte // the raw bytes of this segment + changed bool // true if this segment differs from the corresponding side +} + +// inlineChange holds the character-level diff breakdown for a removed/added line pair. +// +// removed and added are parallel segment lists whose concatenated text fields +// reconstruct the original removed and added lines respectively. +type inlineChange struct { + removed []segment + added []segment +} + +// charDiff computes character-level diff segments for a removed/added line pair. +// It uses an O(mn) LCS algorithm on runes — acceptable since individual diff lines are short. +// +// Behaviour: +// - Identical inputs return all-unchanged segments (changed: false throughout). +// - Trailing newlines are stripped before diffing and reattached afterwards. +// A trailing newline is never placed inside a changed segment to prevent ANSI +// background colours bleeding onto the next terminal line when rendered. +// - If either side contains invalid UTF-8, a single whole-line changed segment +// is returned as a fallback. +// - If either side exceeds 500 runes, a single whole-line changed segment is +// returned to avoid O(mn) cost on minified or generated content. +// - If the similarity ratio (2*equalRunes / totalRunes) is below the threshold +// set by [WithSimilarityThreshold] (default 0.5), a whole-line changed segment +// is returned — intraline highlighting of very different lines is noisy. +// +// The concatenation of segment text fields on each side always equals the +// original input byte-for-byte. +func charDiff(removed, added []byte, cfg config) inlineChange { + // Identical inputs: short-circuit before any UTF-8 handling. This also + // covers identical invalid UTF-8, where fallback would wrongly return + // changed:true segments. + if bytes.Equal(removed, added) { + seg := segment{text: bytes.Clone(removed), changed: false} + + return inlineChange{ + removed: []segment{seg}, + added: []segment{{text: bytes.Clone(added), changed: false}}, + } + } + + // Strip trailing newline, remember whether each side had one. + removedNL := len(removed) > 0 && removed[len(removed)-1] == '\n' + addedNL := len(added) > 0 && added[len(added)-1] == '\n' + + removedCore := removed + if removedNL { + removedCore = removed[:len(removed)-1] + } + + addedCore := added + if addedNL { + addedCore = added[:len(added)-1] + } + + // Fall back to whole-line diff for invalid UTF-8: converting invalid bytes + // to runes replaces them with U+FFFD, making it impossible to reconstruct + // the original bytes from the segments. + if !utf8.Valid(removedCore) || !utf8.Valid(addedCore) { + return fallback(removed, added) + } + + oldRunes := []rune(string(removedCore)) + newRunes := []rune(string(addedCore)) + + // Safety cap: avoid O(mn) on large inputs (minified/generated content). + if len(oldRunes) > 500 || len(newRunes) > 500 { + return fallback(removed, added) + } + + segs := lcsSegments(oldRunes, newRunes, len(removedCore), len(addedCore)) + + // Similarity ratio gate: if the ratio of equal runes to total runes is below + // the threshold, intraline highlighting would be more noise than signal. + // Build the whole-line fallback using the stripped core slices so that + // reattachNL can place the trailing newline outside the changed segment — + // a highlighted \n bleeds ANSI background colour onto the next terminal line. + totalRunes := len(oldRunes) + len(newRunes) + if totalRunes > 0 { + equalRunes := 0 + + for _, seg := range segs.removed { + if !seg.changed { + equalRunes += utf8.RuneCount(seg.text) + } + } + + ratio := float64(similarityRatioScale*equalRunes) / float64(totalRunes) + if ratio < cfg.similarityThreshold { + var rSegs []segment + if len(removedCore) > 0 { + rSegs = []segment{{text: bytes.Clone(removedCore), changed: true}} + } + + var aSegs []segment + if len(addedCore) > 0 { + aSegs = []segment{{text: bytes.Clone(addedCore), changed: true}} + } + + return inlineChange{ + removed: reattachNL(rSegs, removedNL), + added: reattachNL(aSegs, addedNL), + } + } + } + + removedSegs := reattachNL(segs.removed, removedNL) + addedSegs := reattachNL(segs.added, addedNL) + + return inlineChange{removed: removedSegs, added: addedSegs} +} + +// fallback returns a single changed segment per side (whole-line fallback). +// Copies the input slices to avoid aliasing the caller's memory. +func fallback(removed, added []byte) inlineChange { + result := inlineChange{} + + if len(removed) > 0 { + cp := make([]byte, len(removed)) + copy(cp, removed) + result.removed = []segment{{text: cp, changed: true}} + } + + if len(added) > 0 { + cp := make([]byte, len(added)) + copy(cp, added) + result.added = []segment{{text: cp, changed: true}} + } + + return result +} + +// reattachNL returns a new segment slice with a newline reattached after the +// last segment. The input slice is not modified. +// +// If the last segment is changed, the newline is appended as a separate +// unchanged segment rather than being included in the highlight span — a +// highlighted \n causes the ANSI background colour to bleed onto the next +// terminal line. +func reattachNL(segs []segment, hadNL bool) []segment { + if !hadNL { + return segs + } + + if len(segs) == 0 { + return []segment{{text: []byte{'\n'}, changed: false}} + } + + last := segs[len(segs)-1] + + if last.changed { + result := make([]segment, 0, len(segs)+1) + result = append(result, segs...) + + return append(result, segment{text: []byte{'\n'}, changed: false}) + } + + result := make([]segment, len(segs)) + copy(result, segs) + + last.text = append(bytes.Clone(last.text), '\n') + result[len(result)-1] = last + + return result +} + +// sides holds parallel removed/added segment lists built during backtracking. +type sides struct { + removed []segment + added []segment +} + +// op is a single edit operation produced during LCS backtracking. +type op struct { + r rune + kind byte // 'e' equal, 'd' delete, 'i' insert +} + +// lcsSegments builds the LCS table and backtracks to produce Equal/Delete/Insert +// edit operations, then merges consecutive same-kind ops into segment runs. +// rCap and aCap are the byte lengths of the removed and added inputs (without +// their trailing newlines) and are used to pre-allocate segment backing buffers. +func lcsSegments(old, newText []rune, rCap, aCap int) sides { + m, n := len(old), len(newText) + + // Build LCS DP table using a flat slice to avoid m+1 separate allocations. + dp := make([]int, (m+1)*(n+1)) + + stride := n + 1 + for i := 1; i <= m; i++ { + for j := 1; j <= n; j++ { + if old[i-1] == newText[j-1] { + dp[i*stride+j] = dp[(i-1)*stride+(j-1)] + 1 + } else { + dp[i*stride+j] = max(dp[(i-1)*stride+j], dp[i*stride+(j-1)]) + } + } + } + + // Backtrack to build edit ops, then reverse. + ops := make([]op, 0, m+n) + + i, j := m, n + for i > 0 || j > 0 { + switch { + case i > 0 && j > 0 && old[i-1] == newText[j-1]: + ops = append(ops, op{r: old[i-1], kind: 'e'}) + i-- + j-- + case j > 0 && (i == 0 || dp[i*stride+(j-1)] >= dp[(i-1)*stride+j]): + ops = append(ops, op{r: newText[j-1], kind: 'i'}) + j-- + default: + ops = append(ops, op{r: old[i-1], kind: 'd'}) + i-- + } + } + + // Reverse ops (they were built backwards). + for l, r := 0, len(ops)-1; l < r; l, r = l+1, r-1 { + ops[l], ops[r] = ops[r], ops[l] + } + + return mergeSegments(ops, rCap, aCap) +} + +// similarityRatioScale is the multiplier used in the similarity ratio formula: +// ratio = 2*equalRunes / totalRunes. The factor of 2 ensures that two identical +// lines score 1.0 (each equal rune is counted once on each side). +const similarityRatioScale = 2 + +// segmentInitCap is the initial capacity for segment slices in mergeSegments. +// Most diff lines produce far fewer than 8 segments; this avoids the first +// few re-allocations on typical input. +const segmentInitCap = 8 + +// mergeSegments merges consecutive same-kind ops into segment runs. +// rCap and aCap are the byte capacities for the removed and added backing +// buffers; they must equal the byte lengths of the respective core inputs so +// that the buffers never reallocate, keeping all segment text subslices valid. +func mergeSegments(ops []op, rCap, aCap int) sides { + removedSegs := make([]segment, 0, segmentInitCap) + addedSegs := make([]segment, 0, segmentInitCap) + + // Pre-allocated backing buffers. Sized to the exact input byte lengths so + // no reallocation occurs and existing text subslices are never invalidated. + removedBacking := make([]byte, 0, rCap) + addedBacking := make([]byte, 0, aCap) + + var buf [utf8.UTFMax]byte + for _, o := range ops { + nb := utf8.EncodeRune(buf[:], o.r) + r := buf[:nb] + + switch o.kind { + case 'e': + removedBacking = append(removedBacking, r...) + + if len(removedSegs) > 0 && !removedSegs[len(removedSegs)-1].changed { + last := &removedSegs[len(removedSegs)-1] + last.text = last.text[:len(last.text)+nb] + } else { + removedSegs = append( + removedSegs, + segment{text: removedBacking[len(removedBacking)-nb:], changed: false}, + ) + } + + addedBacking = append(addedBacking, r...) + + if len(addedSegs) > 0 && !addedSegs[len(addedSegs)-1].changed { + last := &addedSegs[len(addedSegs)-1] + last.text = last.text[:len(last.text)+nb] + } else { + addedSegs = append(addedSegs, segment{text: addedBacking[len(addedBacking)-nb:], changed: false}) + } + + case 'd': + removedBacking = append(removedBacking, r...) + + if len(removedSegs) > 0 && removedSegs[len(removedSegs)-1].changed { + last := &removedSegs[len(removedSegs)-1] + last.text = last.text[:len(last.text)+nb] + } else { + removedSegs = append(removedSegs, segment{text: removedBacking[len(removedBacking)-nb:], changed: true}) + } + + case 'i': + addedBacking = append(addedBacking, r...) + + if len(addedSegs) > 0 && addedSegs[len(addedSegs)-1].changed { + last := &addedSegs[len(addedSegs)-1] + last.text = last.text[:len(last.text)+nb] + } else { + addedSegs = append(addedSegs, segment{text: addedBacking[len(addedBacking)-nb:], changed: true}) + } + + default: + // op.kind is always 'e', 'd', or 'i' — lcsSegments is the only producer. + } + } + + // Handle empty inputs: produce a single unchanged empty segment so callers + // always have at least one segment to work with. + if len(removedSegs) == 0 { + removedSegs = append(removedSegs, segment{text: []byte{}, changed: false}) + } + + if len(addedSegs) == 0 { + addedSegs = append(addedSegs, segment{text: []byte{}, changed: false}) + } + + return sides{removed: removedSegs, added: addedSegs} +} diff --git a/render/render.go b/render/render.go index 091fe14..7473d3e 100644 --- a/render/render.go +++ b/render/render.go @@ -25,23 +25,58 @@ var ( prefixAdded = []byte("+ ") ) -// Render formats a []diff.Line as a colourised byte slice suitable for terminal output. -// Returns nil if lines is nil or empty. Options are forwarded to [diff.CharDiff] and -// control intraline highlighting behaviour (e.g. [diff.WithSimilarityThreshold]). +const defaultSimilarityThreshold = 0.5 + +// config holds resolved options for a render operation. +type config struct { + similarityThreshold float64 +} + +// defaultConfig returns a config with package defaults. +func defaultConfig() config { + return config{similarityThreshold: defaultSimilarityThreshold} +} + +// Option is a functional option that configures a render operation. +type Option func(*config) + +// WithSimilarityThreshold sets the minimum similarity ratio for intraline highlighting. +// ratio = 2*equalRunes / (len(removedRunes) + len(addedRunes)). +// Default is 0.5. Use 0.0 to always highlight; 1.0 to never highlight. +func WithSimilarityThreshold(t float64) Option { + return func(c *config) { c.similarityThreshold = t } +} + +// applyOptions builds a config from defaults and the provided options. +func applyOptions(opts []Option) config { + cfg := defaultConfig() + for _, o := range opts { + o(&cfg) + } + + return cfg +} + +// Render formats a diff.Diff as a colourised byte slice suitable for terminal output. +// Returns nil if d is the zero value (equal inputs). Options control intraline +// highlighting behaviour (e.g. [WithSimilarityThreshold]). // // Colour scheme: // - "diff …" and "@@ … @@" header lines are bold with no colour. // - "--- …" header lines are red; "+++ …" header lines are green. // - Context lines are unstyled with a double-space prefix. // - When a run of removed lines is immediately followed by an equal-length run -// of added lines, each pair is diffed at the character level via [diff.CharDiff] -// and changed characters are highlighted with a coloured background. +// of added lines, each pair is diffed at the character level and changed +// characters are highlighted with a coloured background. // - Otherwise whole-line colour is applied with no character-level highlighting. -func Render(lines []diff.Line, opts ...diff.Option) []byte { +func Render(d diff.Diff, opts ...Option) []byte { + lines := d.Lines() if len(lines) == 0 { return nil } + cfg := applyOptions(opts) + var buf []byte i := 0 @@ -58,7 +93,7 @@ func Render(lines []diff.Line, opts ...diff.Option) []byte { i++ case diff.KindRemoved: - buf, i = appendRemovedBlock(buf, lines, i, opts) + buf, i = appendRemovedBlock(buf, lines, i, cfg) case diff.KindAdded: buf, i = appendAddedBlock(buf, lines, i) @@ -94,7 +129,7 @@ func appendContext(buf []byte, line diff.Line) []byte { // appendRemovedBlock collects a consecutive run of removed lines and any immediately // following added lines starting at index i, renders them, and returns the updated buf and index. -func appendRemovedBlock(buf []byte, lines []diff.Line, i int, opts []diff.Option) ([]byte, int) { +func appendRemovedBlock(buf []byte, lines []diff.Line, i int, cfg config) ([]byte, int) { start := i for i < len(lines) && lines[i].Kind == diff.KindRemoved { i++ @@ -109,7 +144,7 @@ func appendRemovedBlock(buf []byte, lines []diff.Line, i int, opts []diff.Option added := lines[removedEnd:i] if len(removed) == len(added) { - return renderInlinePairs(buf, removed, added, opts), i + return renderInlinePairs(buf, removed, added, cfg), i } return renderWholeLine(buf, removed, added), i @@ -127,27 +162,27 @@ func appendAddedBlock(buf []byte, lines []diff.Line, i int) ([]byte, int) { } // renderInlinePairs renders 1:1 paired removed/added lines with character-level inline diff. -func renderInlinePairs(buf []byte, removed, added []diff.Line, opts []diff.Option) []byte { +func renderInlinePairs(buf []byte, removed, added []diff.Line, cfg config) []byte { for k := range removed { - ic := diff.CharDiff(removed[k].Content, added[k].Content, opts...) + ic := charDiff(removed[k].Content, added[k].Content, cfg) buf = styleRemovedLine.AppendText(buf, prefixRemoved) - for _, seg := range ic.Removed { - if seg.Changed { - buf = styleRemovedHighlight.AppendText(buf, seg.Text) + for _, seg := range ic.removed { + if seg.changed { + buf = styleRemovedHighlight.AppendText(buf, seg.text) } else { - buf = styleRemovedLine.AppendText(buf, seg.Text) + buf = styleRemovedLine.AppendText(buf, seg.text) } } buf = styleAddedLine.AppendText(buf, prefixAdded) - for _, seg := range ic.Added { - if seg.Changed { - buf = styleAddedHighlight.AppendText(buf, seg.Text) + for _, seg := range ic.added { + if seg.changed { + buf = styleAddedHighlight.AppendText(buf, seg.text) } else { - buf = styleAddedLine.AppendText(buf, seg.Text) + buf = styleAddedLine.AppendText(buf, seg.text) } } } diff --git a/render/render_test.go b/render/render_test.go index 36e680f..492bcda 100644 --- a/render/render_test.go +++ b/render/render_test.go @@ -23,81 +23,58 @@ func TestMain(m *testing.M) { func TestRender(t *testing.T) { tests := []struct { - name string - lines []diff.Line + name string + old string + new string }{ { - name: "nil input returns empty string", - lines: nil, - }, - { - name: "empty slice returns empty string", - lines: []diff.Line{}, - }, - { - name: "context line has no colour and double-space prefix", - lines: []diff.Line{ - {Kind: diff.KindContext, Content: []byte("unchanged\n")}, - }, + // Equal inputs should produce nil output — nothing to render. + name: "equal inputs returns nil", + old: "same\n", + new: "same\n", }, { - name: "diff header line is bold no colour", - lines: []diff.Line{ - {Kind: diff.KindHeader, Content: []byte("diff want got\n")}, - }, + // Single line change: char-level inline highlighting shows changed characters. + name: "single line change uses inline char diff", + old: "hello world\n", + new: "hello earth\n", }, { - name: "removed header line is red", - lines: []diff.Line{ - {Kind: diff.KindHeader, Content: []byte("--- want\n")}, - }, - }, - { - name: "added header line is green", - lines: []diff.Line{ - {Kind: diff.KindHeader, Content: []byte("+++ got\n")}, - }, - }, - { - name: "hunk header is bold no colour", - lines: []diff.Line{ - {Kind: diff.KindHeader, Content: []byte("@@ -1,1 +1,1 @@\n")}, - }, + // Two changed lines paired 1:1: each pair gets its own inline diff. + name: "two paired lines use inline char diff", + old: "foo bar\nbaz qux\n", + new: "foo baz\nbaz quux\n", }, { - name: "standalone removed line has red prefix and content", - lines: []diff.Line{ - {Kind: diff.KindRemoved, Content: []byte("old line\n")}, - }, + // Pure deletion: all lines removed, none added. + name: "pure deletion uses whole-line colour", + old: "old line\n", + new: "", }, { - name: "standalone added line has green prefix and content", - lines: []diff.Line{ - {Kind: diff.KindAdded, Content: []byte("new line\n")}, - }, + // Pure insertion: all lines added, none removed. + name: "pure insertion uses whole-line colour", + old: "", + new: "new line\n", }, { - // "old" and "new" share no characters, so CharDiff produces a single - // Changed segment per side with the \n reattached as a separate unchanged segment. - name: "matched removed added pair uses inline char diff with coloured prefixes", - lines: []diff.Line{ - {Kind: diff.KindRemoved, Content: []byte("old\n")}, - {Kind: diff.KindAdded, Content: []byte("new\n")}, - }, + // More removed than added: mismatched counts fall back to whole-line colour. + name: "mismatched count uses whole-line colour", + old: "line one\nline two\n", + new: "replacement\n", }, { - name: "mismatched count uses whole-line colour with coloured prefixes", - lines: []diff.Line{ - {Kind: diff.KindRemoved, Content: []byte("line one\n")}, - {Kind: diff.KindRemoved, Content: []byte("line two\n")}, - {Kind: diff.KindAdded, Content: []byte("replacement\n")}, - }, + // Unicode content: char diff should handle multi-byte runes correctly. + name: "unicode content", + old: "Héllo, wörld!\n", + new: "Héllo, wörld! Ünïcödé.\n", }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - got := render.Render(tt.lines) + d := diff.New("want", []byte(tt.old), "got", []byte(tt.new)) + got := render.Render(d) golden := filepath.Join("testdata", filepath.FromSlash(t.Name())+".txt") if *update { @@ -183,8 +160,8 @@ func TestVisualDiff(t *testing.T) { for _, sc := range scenarios { t.Run(sc.name, func(t *testing.T) { - lines := diff.Lines("want", []byte(sc.old), "got", []byte(sc.new)) - t.Logf("\n=== %s ===\n%s\n", sc.name, render.Render(lines)) + d := diff.New("want", []byte(sc.old), "got", []byte(sc.new)) + t.Logf("\n=== %s ===\n%s\n", sc.name, render.Render(d)) }) } } @@ -193,11 +170,11 @@ func TestVisualDiff(t *testing.T) { func BenchmarkRender(b *testing.B) { old := []byte("the quick brown fox\njumps over the lazy dog\nsome context\nmore context\n") newContent := []byte("the quick brown cat\njumps over the lazy frog\nsome context\nmore context\n") - lines := diff.Lines("want", old, "got", newContent) + d := diff.New("want", old, "got", newContent) b.ResetTimer() for b.Loop() { - render.Render(lines) + render.Render(d) } } diff --git a/render/testdata/TestRender/equal_inputs_returns_nil.txt b/render/testdata/TestRender/equal_inputs_returns_nil.txt new file mode 100644 index 0000000..e69de29 diff --git a/render/testdata/TestRender/mismatched_count_uses_whole-line_colour.txt b/render/testdata/TestRender/mismatched_count_uses_whole-line_colour.txt new file mode 100644 index 0000000..d9c87fa --- /dev/null +++ b/render/testdata/TestRender/mismatched_count_uses_whole-line_colour.txt @@ -0,0 +1,8 @@ +diff want got +--- want ++++ got +@@ -1,2 +1,1 @@ +- line one +- line two ++ replacement + \ No newline at end of file diff --git a/render/testdata/TestRender/pure_deletion_uses_whole-line_colour.txt b/render/testdata/TestRender/pure_deletion_uses_whole-line_colour.txt new file mode 100644 index 0000000..2e7eabd --- /dev/null +++ b/render/testdata/TestRender/pure_deletion_uses_whole-line_colour.txt @@ -0,0 +1,6 @@ +diff want got +--- want ++++ got +@@ -1,1 +0,0 @@ +- old line + \ No newline at end of file diff --git a/render/testdata/TestRender/pure_insertion_uses_whole-line_colour.txt b/render/testdata/TestRender/pure_insertion_uses_whole-line_colour.txt new file mode 100644 index 0000000..94e58cd --- /dev/null +++ b/render/testdata/TestRender/pure_insertion_uses_whole-line_colour.txt @@ -0,0 +1,6 @@ +diff want got +--- want ++++ got +@@ -0,0 +1,1 @@ ++ new line + \ No newline at end of file diff --git a/render/testdata/TestRender/single_line_change_uses_inline_char_diff.txt b/render/testdata/TestRender/single_line_change_uses_inline_char_diff.txt new file mode 100644 index 0000000..ea675ec --- /dev/null +++ b/render/testdata/TestRender/single_line_change_uses_inline_char_diff.txt @@ -0,0 +1,7 @@ +diff want got +--- want ++++ got +@@ -1,1 +1,1 @@ +- hello world ++ hello earth + \ No newline at end of file diff --git a/render/testdata/TestRender/two_paired_lines_use_inline_char_diff.txt b/render/testdata/TestRender/two_paired_lines_use_inline_char_diff.txt new file mode 100644 index 0000000..e490426 --- /dev/null +++ b/render/testdata/TestRender/two_paired_lines_use_inline_char_diff.txt @@ -0,0 +1,9 @@ +diff want got +--- want ++++ got +@@ -1,2 +1,2 @@ +- foo bar ++ foo baz +- baz qux ++ baz quux + \ No newline at end of file diff --git a/render/testdata/TestRender/unicode_content.txt b/render/testdata/TestRender/unicode_content.txt new file mode 100644 index 0000000..dcb9c1e --- /dev/null +++ b/render/testdata/TestRender/unicode_content.txt @@ -0,0 +1,7 @@ +diff want got +--- want ++++ got +@@ -1,1 +1,1 @@ +- Héllo, wörld! ++ Héllo, wörld! Ünïcödé. + \ No newline at end of file