From faab577281fd6ab4ee47b0cbe284ae1b55cc7349 Mon Sep 17 00:00:00 2001 From: Tom Fleet Date: Sun, 12 Apr 2026 07:28:14 +0100 Subject: [PATCH] Port diff from go.followtheprocess.codes/test/internal/diff (#2) * Initial port * Performance improvements * Fix EOL on windows --- .gitattributes | 2 +- .gitignore | 1 + .typos.toml | 6 +- NOTICE | 5 + README.md | 118 +++++- chardiff_test.go | 314 ++++++++++++++ chars.go | 285 +++++++++++++ diff.go | 390 +++++++++++++++++- diff_test.go | 235 ++++++++++- go.mod | 10 + go.sum | 8 + render/render.go | 170 ++++++++ render/render_test.go | 203 +++++++++ .../TestRender/added_header_line_is_green.txt | 2 + ..._has_no_colour_and_double-space_prefix.txt | 1 + .../diff_header_line_is_bold_no_colour.txt | 2 + .../empty_slice_returns_empty_string.txt | 0 .../hunk_header_is_bold_no_colour.txt | 2 + ...nline_char_diff_with_coloured_prefixes.txt | 3 + ...ole-line_colour_with_coloured_prefixes.txt | 4 + .../nil_input_returns_empty_string.txt | 0 .../TestRender/removed_header_line_is_red.txt | 2 + ...dded_line_has_green_prefix_and_content.txt | 2 + ...emoved_line_has_red_prefix_and_content.txt | 2 + testdata/allnew.txtar | 13 + testdata/allold.txtar | 13 + testdata/basic.txtar | 35 ++ testdata/dups.txtar | 40 ++ testdata/end.txtar | 38 ++ testdata/eof.txtar | 9 + testdata/eof1.txtar | 18 + testdata/eof2.txtar | 18 + testdata/fuzz/FuzzCharDiff/10ab2b7964808a78 | 3 + testdata/fuzz/FuzzCharDiff/959c728e1ba9028d | 3 + testdata/long.txtar | 62 +++ testdata/same.txtar | 5 + testdata/start.txtar | 34 ++ testdata/triv.txtar | 40 ++ 38 files changed, 2081 insertions(+), 17 deletions(-) create mode 100644 NOTICE create mode 100644 chardiff_test.go create mode 100644 chars.go create mode 100644 go.sum create mode 100644 render/render.go create mode 100644 render/render_test.go create mode 100644 render/testdata/TestRender/added_header_line_is_green.txt create mode 100644 render/testdata/TestRender/context_line_has_no_colour_and_double-space_prefix.txt create mode 100644 render/testdata/TestRender/diff_header_line_is_bold_no_colour.txt create mode 100644 render/testdata/TestRender/empty_slice_returns_empty_string.txt create mode 100644 render/testdata/TestRender/hunk_header_is_bold_no_colour.txt create mode 100644 render/testdata/TestRender/matched_removed_added_pair_uses_inline_char_diff_with_coloured_prefixes.txt create mode 100644 render/testdata/TestRender/mismatched_count_uses_whole-line_colour_with_coloured_prefixes.txt create mode 100644 render/testdata/TestRender/nil_input_returns_empty_string.txt create mode 100644 render/testdata/TestRender/removed_header_line_is_red.txt create mode 100644 render/testdata/TestRender/standalone_added_line_has_green_prefix_and_content.txt create mode 100644 render/testdata/TestRender/standalone_removed_line_has_red_prefix_and_content.txt create mode 100644 testdata/allnew.txtar create mode 100644 testdata/allold.txtar create mode 100644 testdata/basic.txtar create mode 100644 testdata/dups.txtar create mode 100644 testdata/end.txtar create mode 100644 testdata/eof.txtar create mode 100644 testdata/eof1.txtar create mode 100644 testdata/eof2.txtar create mode 100644 testdata/fuzz/FuzzCharDiff/10ab2b7964808a78 create mode 100644 testdata/fuzz/FuzzCharDiff/959c728e1ba9028d create mode 100644 testdata/long.txtar create mode 100644 testdata/same.txtar create mode 100644 testdata/start.txtar create mode 100644 testdata/triv.txtar diff --git a/.gitattributes b/.gitattributes index 4ffa512..70e49ed 100644 --- a/.gitattributes +++ b/.gitattributes @@ -3,7 +3,7 @@ # Force LF even on windows for testdata, means comparisons don't fail just # because of line endings -**/testdata/* text eol=lf +**/testdata/** text eol=lf # Txtar requires lf *.txtar text eol=lf diff --git a/.gitignore b/.gitignore index 9d1937f..a4c22bc 100755 --- a/.gitignore +++ b/.gitignore @@ -37,6 +37,7 @@ !docs/img/*.webp !README.md !LICENSE +!NOTICE # Docker !Dockerfile diff --git a/.typos.toml b/.typos.toml index 4c14857..bd3e1f7 100644 --- a/.typos.toml +++ b/.typos.toml @@ -4,4 +4,8 @@ byt = "byt" # Useful name as byte is a keyword in go decorder = "decorder" # Name of a Go linter [files] -extend-exclude = ["go.mod", "go.sum"] +extend-exclude = [ + "go.mod", + "go.sum", + "**/testdata/**" +] diff --git a/NOTICE b/NOTICE new file mode 100644 index 0000000..cb04ee5 --- /dev/null +++ b/NOTICE @@ -0,0 +1,5 @@ +This software contains code derived from the Go standard library's internal/diff package +(https://github.com/golang/go/tree/master/src/internal/diff). + +Copyright 2022 The Go Authors. All rights reserved. +Used under a BSD-style license (https://github.com/golang/go/blob/master/LICENSE). diff --git a/README.md b/README.md index a0427e6..ba5a638 100644 --- a/README.md +++ b/README.md @@ -7,14 +7,25 @@ [![CI](https://github.com/FollowTheProcess/diff/workflows/CI/badge.svg)](https://github.com/FollowTheProcess/diff/actions?query=workflow%3ACI) [![codecov](https://codecov.io/gh/FollowTheProcess/diff/branch/main/graph/badge.svg)](https://codecov.io/gh/FollowTheProcess/diff) -A pure Go text diff library +A pure Go text diff library providing an anchored diff algorithm, character-level +inline diff, and colourised terminal rendering. It started life as `internal/diff` in [`test`] until +I needed it in a few places so here it is 🎉 -> [!WARNING] -> **diff is in early development and is not yet ready for use** +## Project Description -![caution](./docs/img/caution.png) +`diff` computes the difference between two texts using an *anchored diff* algorithm. +Unlike standard diff, which finds the smallest edit by line count, the anchored +algorithm matches on lines that appear exactly once in both old and new — unique +lines act as anchors, preventing unrelated blank lines or closing braces from being +reused as false matches. The result is typically cleaner and more readable output, +and the algorithm runs in O(n log n) rather than O(n²). -## Project Description +The library is split into two packages: + +- **`go.followtheprocess.codes/diff`** — the diff algorithm and all types. No + external dependencies. +- **`go.followtheprocess.codes/diff/render`** — colourised terminal rendering + using ANSI escape codes via [`hue`]. Import only when you need colour output. ## Installation @@ -22,11 +33,108 @@ A pure Go text diff library go get go.followtheprocess.codes/diff@latest ``` +For colourised rendering also get the render subpackage (its `hue` dependency is +pulled in automatically): + +```shell +go get go.followtheprocess.codes/diff/render@latest +``` + ## Quickstart +### Plain unified diff + +```go +package main + +import ( + "os" + + "go.followtheprocess.codes/diff" +) + +func main() { + old := []byte("hello\nworld\n") + new := []byte("hello\nearth\n") + + // Returns nil when inputs are equal. + out := diff.Diff("old.txt", old, "new.txt", new) + os.Stdout.Write(out) +} +``` + +Output: + +``` +diff old.txt new.txt +--- old.txt ++++ new.txt +@@ -1,2 +1,2 @@ + hello +- world ++ earth +``` + +### Colourised terminal rendering + +```go +package main + +import ( + "os" + + "go.followtheprocess.codes/diff" + "go.followtheprocess.codes/diff/render" +) + +func main() { + old := []byte("hello\nworld\n") + new := []byte("hello\nearth\n") + + lines := diff.Lines("old.txt", old, "new.txt", new) + os.Stdout.Write(render.Render(lines)) +} +``` + +`render.Render` applies ANSI colour: red for removed lines, green for added lines, +bold for headers. When a removed and added line appear as a 1:1 pair, changed +*characters* are highlighted with a coloured background for precise inline diffing. + +### Character-level diff + +```go +ic := diff.CharDiff([]byte("hello world\n"), []byte("hello earth\n")) + +for _, seg := range ic.Removed { + fmt.Printf("removed segment changed=%v: %q\n", seg.Changed, seg.Text) +} +for _, seg := range ic.Added { + fmt.Printf("added segment changed=%v: %q\n", seg.Changed, seg.Text) +} +``` + +## API Overview + +| Symbol | Package | Description | +|--------|---------|-------------| +| `Lines` | `diff` | Structured `[]Line` output; nil if inputs are equal | +| `Diff` | `diff` | Raw unified-diff `[]byte`; nil if inputs are equal | +| `CharDiff` | `diff` | Character-level segment diff for a removed/added line pair | +| `Render` | `diff/render` | Colourised `[]byte` for terminal output | + +## Acknowledgements + +The core diff algorithm (`diff.go`) is derived from the Go standard library's +[`internal/diff`](https://github.com/golang/go/tree/master/src/internal/diff) package. + +Copyright 2022 The Go Authors. All rights reserved. Used under a +[BSD-style license](https://github.com/golang/go/blob/master/LICENSE). + ### Credits This package was created with [copier] and the [FollowTheProcess/go-template] project template. [copier]: https://copier.readthedocs.io/en/stable/ [FollowTheProcess/go-template]: https://github.com/FollowTheProcess/go-template +[`hue`]: https://go.followtheprocess.codes/hue +[`test`]: https://go.followtheprocess.codes/test diff --git a/chardiff_test.go b/chardiff_test.go new file mode 100644 index 0000000..9fbd03b --- /dev/null +++ b/chardiff_test.go @@ -0,0 +1,314 @@ +package diff_test + +import ( + "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") + } +} + +// 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 +} + +func joinSegments(segs []diff.Segment) string { + var sb strings.Builder + for _, s := range segs { + sb.Write(s.Text) + } + + return sb.String() +} diff --git a/chars.go b/chars.go new file mode 100644 index 0000000..4227390 --- /dev/null +++ b/chars.go @@ -0,0 +1,285 @@ +package diff + +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. +// +// The concatenation of segment Text fields on each side always equals the +// original input byte-for-byte. +func CharDiff(removed, added []byte) 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)) + + 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) +} + +// 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 95d3c68..3405d84 100644 --- a/diff.go +++ b/diff.go @@ -1,7 +1,387 @@ -// Package diff is a A pure Go text diff library. -package diff // import "go.followtheprocess.codes/diff" +// Package diff provides an anchored diff algorithm with structured line output, +// character-level inline diff, 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). +// Copyright 2022 The Go Authors. All rights reserved. Used under a BSD-style licence. +// +// An anchored diff finds the diff with the smallest number of "unique" lines +// inserted and removed, where unique means a line appears exactly once in both old +// and new. Unique lines anchor the matching regions, producing cleaner output than +// standard diff — blank lines and closing braces are not reused as false anchors. +// The algorithm runs in O(n log n) rather than the standard O(n²). +package diff -// Hello returns a welcome message for the project. -func Hello() string { - return "Hello diff" +import ( + "bytes" + "fmt" + "sort" + "unsafe" +) + +// LineKind identifies the role of a line in a diff output. +type LineKind int + +// LineKind values that categorise each line of a diff. +const ( + KindContext LineKind = iota // an unchanged context line shown for surrounding context + KindRemoved // a line present only in the old (left) side + KindAdded // a line present only in the new (right) side + KindHeader // a diff metadata line: "diff …", "--- …", "+++ …", or "@@ … @@" +) + +// String implements fmt.Stringer, returning the name of the constant (e.g. "KindAdded"). +func (k LineKind) String() string { + switch k { + case KindContext: + return "KindContext" + case KindRemoved: + return "KindRemoved" + case KindAdded: + return "KindAdded" + case KindHeader: + return "KindHeader" + default: + return fmt.Sprintf("LineKind(%d)", int(k)) + } +} + +// Line is a single structured line from a diff. +// +// Content holds the line text without the leading diff prefix ("- "/"+ "/" "). +// 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. +type Line struct { + Content []byte + Kind LineKind +} + +// pair is a pair of line indexes, one for each side of the diff. +type pair struct{ x, y int } + +// 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) []Line { + if bytes.Equal(old, newText) { + return nil + } + + return computeLines(oldName, old, newName, newText) +} + +// 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. +// +// For structured line-by-line output use [Lines]. +func Diff( + oldName string, + old []byte, + newName string, + newText []byte, +) []byte { + if bytes.Equal(old, newText) { + return nil + } + + structured := computeLines(oldName, old, newName, newText) + + var out bytes.Buffer + + for _, line := range structured { + switch line.Kind { + case KindHeader: + out.Write(line.Content) + case KindRemoved: + out.WriteString("- ") + out.Write(line.Content) + case KindAdded: + out.WriteString("+ ") + out.Write(line.Content) + case KindContext: + out.WriteString(" ") + out.Write(line.Content) + default: + // no action for unknown line kinds + } + } + + return out.Bytes() +} + +// computeLines computes structured diff lines for old and newText (assumed non-equal). +func computeLines(oldName string, old []byte, newName string, newText []byte) []Line { + x := splitLines(old) + y := splitLines(newText) + + var result []Line + + result = append(result, + Line{Kind: KindHeader, Content: fmt.Appendf(nil, "diff %s %s\n", oldName, newName)}, + Line{Kind: KindHeader, Content: fmt.Appendf(nil, "--- %s\n", oldName)}, + Line{Kind: KindHeader, Content: fmt.Appendf(nil, "+++ %s\n", newName)}, + ) + + var ( + done pair + chunk pair + count pair + ctext []Line + ) + + const contextLines = 3 + + for _, m := range tgs(x, y) { + if m.x < done.x { + continue + } + + start, end := expandMatch(m, done, x, y) + + for _, s := range x[done.x:start.x] { + ctext = append(ctext, Line{Kind: KindRemoved, Content: s}) + count.x++ + } + + for _, s := range y[done.y:start.y] { + ctext = append(ctext, Line{Kind: KindAdded, Content: s}) + count.y++ + } + + if (end.x < len(x) || end.y < len(y)) && + (end.x-start.x < contextLines || (len(ctext) > 0 && end.x-start.x < 2*contextLines)) { + for _, s := range x[start.x:end.x] { + ctext = append(ctext, Line{Kind: KindContext, Content: s}) + count.x++ + count.y++ + } + + done = end + + continue + } + + if len(ctext) > 0 { + n := min(end.x-start.x, contextLines) + + for _, s := range x[start.x : start.x+n] { + ctext = append(ctext, Line{Kind: KindContext, Content: s}) + count.x++ + count.y++ + } + + done = pair{start.x + n, start.y + n} + + result = append(result, chunkHeader(chunk, count)) + result = append(result, ctext...) + + count.x = 0 + count.y = 0 + ctext = ctext[:0] + } + + if end.x >= len(x) && end.y >= len(y) { + break + } + + chunk = pair{end.x - contextLines, end.y - contextLines} + for _, s := range x[chunk.x:end.x] { + ctext = append(ctext, Line{Kind: KindContext, Content: s}) + count.x++ + count.y++ + } + + done = end + } + + return result +} + +// expandMatch expands a match region backward to start and forward to end +// while adjacent lines in x and y also match. +func expandMatch(m, done pair, x, y [][]byte) (start, end pair) { + start = m + for start.x > done.x && start.y > done.y && bytes.Equal(x[start.x-1], y[start.y-1]) { + start.x-- + start.y-- + } + + end = m + for end.x < len(x) && end.y < len(y) && bytes.Equal(x[end.x], y[end.y]) { + end.x++ + end.y++ + } + + return start, end +} + +// chunkHeader formats the @@ header line for a diff chunk. +func chunkHeader(chunk, count pair) Line { + x, y := chunk.x, chunk.y + if count.x > 0 { + x++ + } + + if count.y > 0 { + y++ + } + + return Line{ + Kind: KindHeader, + Content: fmt.Appendf(nil, "@@ -%d,%d +%d,%d @@\n", x, count.x, y, count.y), + } +} + +// splitLines returns the lines in x as subslices of x, including newlines. +// If the file does not end in a newline, a new slice is allocated for the final +// line with the standard "no newline" warning appended. +func splitLines(x []byte) [][]byte { + var lines [][]byte + + for len(x) > 0 { + i := bytes.IndexByte(x, '\n') + if i < 0 { + // No trailing newline — must allocate to append the warning suffix. + const suffix = "\n\\ No newline at end of file\n" + + line := make([]byte, len(x)+len(suffix)) + copy(line, x) + copy(line[len(x):], suffix) + + lines = append(lines, line) + + break + } + + lines = append(lines, x[:i+1]) + x = x[i+1:] + } + + return lines +} + +// 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 +// combined value -1 + -tgsYStep. +const tgsYStep = 4 + +// tgsYMany is the magnitude at which y-side occurrence counting is clamped +// (i.e. the line appears "many" times). Equivalent to two tgsYStep decrements. +const tgsYMany = tgsYStep * 2 + +// tgsSentinels is the number of sentinel pairs added to the result of tgs: +// one at the start {0,0} and one at the end {len(x),len(y)}. +const tgsSentinels = 2 + +// tgs returns the pairs of indexes of the longest common subsequence +// of unique lines in x and y, with sentinel pairs {0,0} and {len(x),len(y)}. +// +// Algorithm: Thomas G. Szymanski, "A Special Case of the Maximal Common +// Subsequence Problem," Princeton TR #170 (January 1975). +func tgs(x, y [][]byte) []pair { + // unsafe.String converts a []byte to string without allocating. This is safe + // because the strings are only stored in m, which is local to this function. + // The backing []byte data (subslices of the original inputs) outlives this call. + m := make(map[string]int) + + for _, s := range x { + k := unsafe.String(unsafe.SliceData(s), len(s)) + if c := m[k]; c > -2 { + m[k] = c - 1 + } + } + + for _, s := range y { + k := unsafe.String(unsafe.SliceData(s), len(s)) + if c := m[k]; c > -tgsYMany { + m[k] = c - tgsYStep + } + } + + var xi, yi, inv []int + + for i, s := range y { + k := unsafe.String(unsafe.SliceData(s), len(s)) + if m[k] == -1+-tgsYStep { + m[k] = len(yi) + yi = append(yi, i) + } + } + + for i, s := range x { + k := unsafe.String(unsafe.SliceData(s), len(s)) + if j, ok := m[k]; ok && j >= 0 { + xi = append(xi, i) + inv = append(inv, j) + } + } + + j := inv + n := len(xi) + tails := make([]int, n) + lengths := make([]int, n) + + for i := range tails { + tails[i] = n + 1 + } + + for i := range n { + k := sort.Search(n, func(k int) bool { + return tails[k] >= j[i] + }) + tails[k] = j[i] + lengths[i] = k + 1 + } + + k := 0 + for _, v := range lengths { + if k < v { + k = v + } + } + + seq := make([]pair, tgsSentinels+k) + seq[1+k] = pair{len(x), len(y)} + + lastj := n + for i := n - 1; i >= 0; i-- { + if lengths[i] == k && j[i] < lastj { + seq[k] = pair{xi[i], yi[j[i]]} + k-- + lastj = j[i] + } + } + + seq[0] = pair{0, 0} + + return seq } diff --git a/diff_test.go b/diff_test.go index 66ab257..3f53df7 100644 --- a/diff_test.go +++ b/diff_test.go @@ -1,16 +1,241 @@ package diff_test import ( + "bytes" + "os" + "path/filepath" "testing" "go.followtheprocess.codes/diff" + "golang.org/x/tools/txtar" ) -func TestHello(t *testing.T) { - got := diff.Hello() - want := "Hello diff" +// TestLines verifies the Lines function returns structured diff lines. +func TestLines(t *testing.T) { + tests := []struct { + name string + old []byte + newText []byte + oldName string + newName string + want []diff.Line // nil means we expect nil (inputs equal) + }{ + { + name: "nil on equal inputs", + oldName: "a", newName: "b", + old: []byte("same\n"), + newText: []byte("same\n"), + want: nil, + }, + { + name: "basic add and remove", + oldName: "want", newName: "got", + old: []byte("hello\nworld\n"), + newText: []byte("hello\nearth\n"), + want: []diff.Line{ + {Kind: diff.KindHeader, Content: []byte("diff want got\n")}, + {Kind: diff.KindHeader, Content: []byte("--- want\n")}, + {Kind: diff.KindHeader, Content: []byte("+++ got\n")}, + {Kind: diff.KindHeader, Content: []byte("@@ -1,2 +1,2 @@\n")}, + {Kind: diff.KindContext, Content: []byte("hello\n")}, + {Kind: diff.KindRemoved, Content: []byte("world\n")}, + {Kind: diff.KindAdded, Content: []byte("earth\n")}, + }, + }, + { + name: "all added", + oldName: "want", newName: "got", + old: []byte(""), + newText: []byte("new line\n"), + want: []diff.Line{ + {Kind: diff.KindHeader, Content: []byte("diff want got\n")}, + {Kind: diff.KindHeader, Content: []byte("--- want\n")}, + {Kind: diff.KindHeader, Content: []byte("+++ got\n")}, + {Kind: diff.KindHeader, Content: []byte("@@ -0,0 +1,1 @@\n")}, + {Kind: diff.KindAdded, Content: []byte("new line\n")}, + }, + }, + { + name: "all removed", + oldName: "want", newName: "got", + old: []byte("old line\n"), + newText: []byte(""), + want: []diff.Line{ + {Kind: diff.KindHeader, Content: []byte("diff want got\n")}, + {Kind: diff.KindHeader, Content: []byte("--- want\n")}, + {Kind: diff.KindHeader, Content: []byte("+++ got\n")}, + {Kind: diff.KindHeader, Content: []byte("@@ -1,1 +0,0 @@\n")}, + {Kind: diff.KindRemoved, Content: []byte("old line\n")}, + }, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + got := diff.Lines(tt.oldName, tt.old, tt.newName, tt.newText) + if tt.want == nil { + if got != nil { + t.Fatalf("Lines() = %v, want nil", got) + } + + return + } + + if len(got) != len(tt.want) { + t.Fatalf( + "Lines() returned %d lines, want %d\ngot: %#v\nwant: %#v", + len(got), + len(tt.want), + got, + tt.want, + ) + } + + for i, line := range got { + if line.Kind != tt.want[i].Kind { + t.Errorf("line[%d].Kind = %v, want %v", i, line.Kind, tt.want[i].Kind) + } + + if !bytes.Equal(line.Content, tt.want[i].Content) { + t.Errorf("line[%d].Content = %q, want %q", i, line.Content, tt.want[i].Content) + } + } + }) + } +} + +// TestDiffNilOnEqual verifies Diff returns nil when old and newText are identical. +func TestDiffNilOnEqual(t *testing.T) { + tests := []struct { + name string + old []byte + new []byte + }{ + { + name: "identical byte slices", + old: []byte("same\n"), + new: []byte("same\n"), + }, + { + name: "both empty", + old: []byte(""), + new: []byte(""), + }, + } + + 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) + } + }) + } +} + +// Test drives Diff against the *.txtar files in testdata/. +func Test(t *testing.T) { + files, err := filepath.Glob(filepath.Join("testdata", "*.txtar")) + if err != nil { + t.Fatalf("could not glob txtar files: %v", err) + } + + if len(files) == 0 { + t.Fatal("no testdata") + } + + for _, file := range files { + t.Run(filepath.Base(file), func(t *testing.T) { + contents, err := os.ReadFile(file) + if err != nil { + t.Fatalf("could not read %s: %v", file, err) + } + + contents = bytes.ReplaceAll(contents, []byte("\r\n"), []byte("\n")) + + archive := txtar.Parse(contents) + if len(archive.Files) != 3 || archive.Files[2].Name != "diff" { + t.Fatalf("%s: want three files, third named \"diff\", got: %v", file, archive.Files) + } + + diffs := diff.Diff( + archive.Files[0].Name, + clean(archive.Files[0].Data), + archive.Files[1].Name, + clean(archive.Files[1].Data), + ) + want := clean(archive.Files[2].Data) - if got != want { - t.Errorf("got %s, wanted %s", got, want) + if !bytes.Equal(diffs, want) { + t.Fatalf("%s: have:\n%s\nwant:\n%s\n%s", file, + diffs, want, diff.Diff("have", diffs, "want", want)) + } + }) } } + +// FuzzLines verifies Lines never panics and returns nil iff inputs are equal. +func FuzzLines(f *testing.F) { + f.Add([]byte(""), []byte("")) + f.Add([]byte("same\n"), []byte("same\n")) + f.Add([]byte("hello\nworld\n"), []byte("hello\nearth\n")) + f.Add([]byte("completely different\n"), []byte("nothing in common\n")) + f.Add([]byte("a\nb\nc\n"), []byte("a\nd\nc\n")) + f.Add([]byte("unicode: héllo\n"), []byte("unicode: wörld\n")) + 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) + if bytes.Equal(old, newContent) { + if result != nil { + t.Fatal("Lines() = non-nil for equal inputs") + } + } else { + if result == nil { + t.Fatal("Lines() = nil for non-equal inputs") + } + } + }) +} + +// BenchmarkLines benchmarks the Lines function using long.txtar as realistic input. +func BenchmarkLines(b *testing.B) { + contents, err := os.ReadFile(filepath.Join("testdata", "long.txtar")) + if err != nil { + b.Fatalf("could not read long.txtar: %v", err) + } + + archive := txtar.Parse(contents) + old := clean(archive.Files[0].Data) + newContent := clean(archive.Files[1].Data) + + b.ResetTimer() + + for b.Loop() { + diff.Lines(archive.Files[0].Name, old, archive.Files[1].Name, newContent) + } +} + +// BenchmarkDiff benchmarks the Diff function using long.txtar as realistic input. +func BenchmarkDiff(b *testing.B) { + contents, err := os.ReadFile(filepath.Join("testdata", "long.txtar")) + if err != nil { + b.Fatalf("could not read long.txtar: %v", err) + } + + archive := txtar.Parse(contents) + old := clean(archive.Files[0].Data) + newContent := clean(archive.Files[1].Data) + + b.ResetTimer() + + for b.Loop() { + diff.Diff(archive.Files[0].Name, old, archive.Files[1].Name, newContent) + } +} + +func clean(text []byte) []byte { + text = bytes.ReplaceAll(text, []byte("$\n"), []byte("\n")) + text = bytes.TrimSuffix(text, []byte("^D\n")) + + return text +} diff --git a/go.mod b/go.mod index a1bfc35..205ea1f 100644 --- a/go.mod +++ b/go.mod @@ -1,3 +1,13 @@ module go.followtheprocess.codes/diff go 1.26 + +require ( + go.followtheprocess.codes/hue v1.1.0 + golang.org/x/tools v0.44.0 +) + +require ( + golang.org/x/sys v0.43.0 // indirect + golang.org/x/term v0.42.0 // indirect +) diff --git a/go.sum b/go.sum new file mode 100644 index 0000000..c965b4b --- /dev/null +++ b/go.sum @@ -0,0 +1,8 @@ +go.followtheprocess.codes/hue v1.1.0 h1:bPq21YLdWxQ0ki4lIvXCYtgutaGaDUYaSIENDdrrlNQ= +go.followtheprocess.codes/hue v1.1.0/go.mod h1:VnCeVmYESGmX7fZJSFs59u8G+5zseCwGdFiJGHCFg4o= +golang.org/x/sys v0.43.0 h1:Rlag2XtaFTxp19wS8MXlJwTvoh8ArU6ezoyFsMyCTNI= +golang.org/x/sys v0.43.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw= +golang.org/x/term v0.42.0 h1:UiKe+zDFmJobeJ5ggPwOshJIVt6/Ft0rcfrXZDLWAWY= +golang.org/x/term v0.42.0/go.mod h1:Dq/D+snpsbazcBG5+F9Q1n2rXV8Ma+71xEjTRufARgY= +golang.org/x/tools v0.44.0 h1:UP4ajHPIcuMjT1GqzDWRlalUEoY+uzoZKnhOjbIPD2c= +golang.org/x/tools v0.44.0/go.mod h1:KA0AfVErSdxRZIsOVipbv3rQhVXTnlU6UhKxHd1seDI= diff --git a/render/render.go b/render/render.go new file mode 100644 index 0000000..d37c0fe --- /dev/null +++ b/render/render.go @@ -0,0 +1,170 @@ +// Package render provides colourised terminal rendering of diff output. +// +// It depends on go.followtheprocess.codes/hue for ANSI colour formatting and is +// provided as a separate subpackage so consumers who only need raw diff output do +// not pull in the colour dependency. +package render + +import ( + "go.followtheprocess.codes/diff" + "go.followtheprocess.codes/hue" +) + +const ( + styleHeaderBold = hue.Bold + styleRemovedHeader = hue.Red + styleAddedHeader = hue.Green + styleRemovedLine = hue.Red + styleAddedLine = hue.Green + styleRemovedHighlight = hue.Black | hue.Bold | hue.RedBackground + styleAddedHighlight = hue.Black | hue.Bold | hue.GreenBackground +) + +var ( + prefixRemoved = []byte("- ") + prefixAdded = []byte("+ ") +) + +// Render formats a []diff.Line as a colourised byte slice suitable for terminal output. +// Returns nil if lines is nil or empty. +// +// 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. +// - Otherwise whole-line colour is applied with no character-level highlighting. +func Render(lines []diff.Line) []byte { + if len(lines) == 0 { + return nil + } + + var buf []byte + + i := 0 + for i < len(lines) { + line := lines[i] + + switch line.Kind { + case diff.KindHeader: + buf = appendHeader(buf, line) + i++ + + case diff.KindContext: + buf = appendContext(buf, line) + i++ + + case diff.KindRemoved: + buf, i = appendRemovedBlock(buf, lines, i) + + case diff.KindAdded: + buf, i = appendAddedBlock(buf, lines, i) + + default: + // no action for unknown line kinds + i++ + } + } + + return buf +} + +// appendHeader appends a styled header line to buf and returns the result. +func appendHeader(buf []byte, line diff.Line) []byte { + if len(line.Content) >= 3 && line.Content[0] == '-' && line.Content[1] == '-' && line.Content[2] == '-' { + return styleRemovedHeader.AppendText(buf, line.Content) + } + + if len(line.Content) >= 3 && line.Content[0] == '+' && line.Content[1] == '+' && line.Content[2] == '+' { + return styleAddedHeader.AppendText(buf, line.Content) + } + + return styleHeaderBold.AppendText(buf, line.Content) +} + +// appendContext appends an unstyled context line with a double-space prefix to buf. +func appendContext(buf []byte, line diff.Line) []byte { + buf = append(buf, ' ', ' ') + + return append(buf, line.Content...) +} + +// 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) ([]byte, int) { + start := i + for i < len(lines) && lines[i].Kind == diff.KindRemoved { + i++ + } + + removedEnd := i + for i < len(lines) && lines[i].Kind == diff.KindAdded { + i++ + } + + removed := lines[start:removedEnd] + added := lines[removedEnd:i] + + if len(removed) == len(added) { + return renderInlinePairs(buf, removed, added), i + } + + return renderWholeLine(buf, removed, added), i +} + +// appendAddedBlock collects a consecutive run of standalone added lines starting at index i, +// renders them with whole-line colour, and returns the updated buf and index. +func appendAddedBlock(buf []byte, lines []diff.Line, i int) ([]byte, int) { + start := i + for i < len(lines) && lines[i].Kind == diff.KindAdded { + i++ + } + + return renderWholeLine(buf, nil, lines[start:i]), i +} + +// renderInlinePairs renders 1:1 paired removed/added lines with character-level inline diff. +func renderInlinePairs(buf []byte, removed, added []diff.Line) []byte { + for k := range removed { + ic := diff.CharDiff(removed[k].Content, added[k].Content) + + buf = styleRemovedLine.AppendText(buf, prefixRemoved) + + for _, seg := range ic.Removed { + if seg.Changed { + buf = styleRemovedHighlight.AppendText(buf, seg.Text) + } else { + 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) + } else { + buf = styleAddedLine.AppendText(buf, seg.Text) + } + } + } + + return buf +} + +// renderWholeLine renders removed/added lines with whole-line colour (no inline diff). +func renderWholeLine(buf []byte, removed, added []diff.Line) []byte { + for _, r := range removed { + buf = styleRemovedLine.AppendText(buf, prefixRemoved) + buf = styleRemovedLine.AppendText(buf, r.Content) + } + + for _, a := range added { + buf = styleAddedLine.AppendText(buf, prefixAdded) + buf = styleAddedLine.AppendText(buf, a.Content) + } + + return buf +} diff --git a/render/render_test.go b/render/render_test.go new file mode 100644 index 0000000..36e680f --- /dev/null +++ b/render/render_test.go @@ -0,0 +1,203 @@ +package render_test + +import ( + "bytes" + "flag" + "os" + "path/filepath" + "testing" + + "go.followtheprocess.codes/diff" + "go.followtheprocess.codes/diff/render" + "go.followtheprocess.codes/hue" +) + +var update = flag.Bool("update", false, "update golden files") + +func TestMain(m *testing.M) { + // Force colour on so rendered output is predictable in tests regardless of + // whether the test runner is attached to a terminal. + hue.Enabled(true) + m.Run() +} + +func TestRender(t *testing.T) { + tests := []struct { + name string + lines []diff.Line + }{ + { + 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")}, + }, + }, + { + name: "diff header line is bold no colour", + lines: []diff.Line{ + {Kind: diff.KindHeader, Content: []byte("diff want got\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")}, + }, + }, + { + name: "standalone removed line has red prefix and content", + lines: []diff.Line{ + {Kind: diff.KindRemoved, Content: []byte("old line\n")}, + }, + }, + { + name: "standalone added line has green prefix and content", + lines: []diff.Line{ + {Kind: diff.KindAdded, Content: []byte("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")}, + }, + }, + { + 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")}, + }, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + got := render.Render(tt.lines) + golden := filepath.Join("testdata", filepath.FromSlash(t.Name())+".txt") + + if *update { + err := os.MkdirAll(filepath.Dir(golden), 0o755) + if err != nil { + t.Fatalf("create golden dir: %v", err) + } + + err = os.WriteFile(golden, got, 0o644) + if err != nil { + t.Fatalf("update golden: %v", err) + } + + return + } + + want, err := os.ReadFile(golden) + if err != nil { + t.Fatalf("read golden: %v", err) + } + + if !bytes.Equal(got, want) { + t.Errorf("Render() =\n%q\nwant\n%q", got, want) + } + }) + } +} + +// TestVisualDiff is a manual smoke-check for the diff renderer. +// Run with go test -v to see the colourised output in your terminal. +func TestVisualDiff(t *testing.T) { + scenarios := []struct { + name string + old string + new string + }{ + { + // Single changed line: char-level inline highlighting should show + // exactly which characters differ. + name: "single line change (inline char diff)", + old: `func greet(name string) string { + return "Hello, " + name +} +`, + new: `func greet(name string) string { + return "Hello, " + name + "!" +} +`, + }, + { + // Two changed lines paired 1:1: each pair gets its own inline diff. + name: "multi-line paired change", + old: `func (s *Server) Start(port int) error { + addr := fmt.Sprintf("0.0.0.0:%d", port) + return http.ListenAndServe(addr, s.mux) +} +`, + new: `func (s *Server) Start(ctx context.Context, port int) error { + addr := fmt.Sprintf(":%d", port) + return s.httpServer.ListenAndServeContext(ctx, addr) +} +`, + }, + { + // More removed than added: mismatched counts fall back to whole-line colour. + name: "mismatched counts (whole-line fallback)", + old: `case "json": + enc := json.NewEncoder(w) + enc.SetIndent("", " ") + return enc.Encode(v) +`, + new: `case "json": + return json.NewEncoder(w).Encode(v) +`, + }, + { + // Unicode content: char diff should handle multi-byte runes correctly. + name: "unicode content", + old: "Héllo, wörld! Ünïcödé is fün.\n", + new: "Héllo, wörld! Ünïcödé is grëat.\n", + }, + } + + 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)) + }) + } +} + +// BenchmarkRender benchmarks Render using a realistic diff. +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) + + b.ResetTimer() + + for b.Loop() { + render.Render(lines) + } +} diff --git a/render/testdata/TestRender/added_header_line_is_green.txt b/render/testdata/TestRender/added_header_line_is_green.txt new file mode 100644 index 0000000..ab3cdde --- /dev/null +++ b/render/testdata/TestRender/added_header_line_is_green.txt @@ -0,0 +1,2 @@ ++++ got + \ No newline at end of file diff --git a/render/testdata/TestRender/context_line_has_no_colour_and_double-space_prefix.txt b/render/testdata/TestRender/context_line_has_no_colour_and_double-space_prefix.txt new file mode 100644 index 0000000..bf47b77 --- /dev/null +++ b/render/testdata/TestRender/context_line_has_no_colour_and_double-space_prefix.txt @@ -0,0 +1 @@ + unchanged diff --git a/render/testdata/TestRender/diff_header_line_is_bold_no_colour.txt b/render/testdata/TestRender/diff_header_line_is_bold_no_colour.txt new file mode 100644 index 0000000..c03a4d1 --- /dev/null +++ b/render/testdata/TestRender/diff_header_line_is_bold_no_colour.txt @@ -0,0 +1,2 @@ +diff want got + \ No newline at end of file diff --git a/render/testdata/TestRender/empty_slice_returns_empty_string.txt b/render/testdata/TestRender/empty_slice_returns_empty_string.txt new file mode 100644 index 0000000..e69de29 diff --git a/render/testdata/TestRender/hunk_header_is_bold_no_colour.txt b/render/testdata/TestRender/hunk_header_is_bold_no_colour.txt new file mode 100644 index 0000000..02d9dab --- /dev/null +++ b/render/testdata/TestRender/hunk_header_is_bold_no_colour.txt @@ -0,0 +1,2 @@ +@@ -1,1 +1,1 @@ + \ No newline at end of file diff --git a/render/testdata/TestRender/matched_removed_added_pair_uses_inline_char_diff_with_coloured_prefixes.txt b/render/testdata/TestRender/matched_removed_added_pair_uses_inline_char_diff_with_coloured_prefixes.txt new file mode 100644 index 0000000..79759f3 --- /dev/null +++ b/render/testdata/TestRender/matched_removed_added_pair_uses_inline_char_diff_with_coloured_prefixes.txt @@ -0,0 +1,3 @@ +- old ++ new + \ No newline at end of file diff --git a/render/testdata/TestRender/mismatched_count_uses_whole-line_colour_with_coloured_prefixes.txt b/render/testdata/TestRender/mismatched_count_uses_whole-line_colour_with_coloured_prefixes.txt new file mode 100644 index 0000000..ecbdf6f --- /dev/null +++ b/render/testdata/TestRender/mismatched_count_uses_whole-line_colour_with_coloured_prefixes.txt @@ -0,0 +1,4 @@ +- line one +- line two ++ replacement + \ No newline at end of file diff --git a/render/testdata/TestRender/nil_input_returns_empty_string.txt b/render/testdata/TestRender/nil_input_returns_empty_string.txt new file mode 100644 index 0000000..e69de29 diff --git a/render/testdata/TestRender/removed_header_line_is_red.txt b/render/testdata/TestRender/removed_header_line_is_red.txt new file mode 100644 index 0000000..c5c3732 --- /dev/null +++ b/render/testdata/TestRender/removed_header_line_is_red.txt @@ -0,0 +1,2 @@ +--- want + \ No newline at end of file diff --git a/render/testdata/TestRender/standalone_added_line_has_green_prefix_and_content.txt b/render/testdata/TestRender/standalone_added_line_has_green_prefix_and_content.txt new file mode 100644 index 0000000..751f4d7 --- /dev/null +++ b/render/testdata/TestRender/standalone_added_line_has_green_prefix_and_content.txt @@ -0,0 +1,2 @@ ++ new line + \ No newline at end of file diff --git a/render/testdata/TestRender/standalone_removed_line_has_red_prefix_and_content.txt b/render/testdata/TestRender/standalone_removed_line_has_red_prefix_and_content.txt new file mode 100644 index 0000000..395e3de --- /dev/null +++ b/render/testdata/TestRender/standalone_removed_line_has_red_prefix_and_content.txt @@ -0,0 +1,2 @@ +- old line + \ No newline at end of file diff --git a/testdata/allnew.txtar b/testdata/allnew.txtar new file mode 100644 index 0000000..0828b55 --- /dev/null +++ b/testdata/allnew.txtar @@ -0,0 +1,13 @@ +-- old -- +-- new -- +a +b +c +-- diff -- +diff old new +--- old ++++ new +@@ -0,0 +1,3 @@ ++ a ++ b ++ c diff --git a/testdata/allold.txtar b/testdata/allold.txtar new file mode 100644 index 0000000..020cedf --- /dev/null +++ b/testdata/allold.txtar @@ -0,0 +1,13 @@ +-- old -- +a +b +c +-- new -- +-- diff -- +diff old new +--- old ++++ new +@@ -1,3 +0,0 @@ +- a +- b +- c diff --git a/testdata/basic.txtar b/testdata/basic.txtar new file mode 100644 index 0000000..f12c77d --- /dev/null +++ b/testdata/basic.txtar @@ -0,0 +1,35 @@ +# Example from Hunt and McIlroy, “An Algorithm for Differential File Comparison.” +# https://www.cs.dartmouth.edu/~doug/diff.pdf + +-- old -- +a +b +c +d +e +f +g +-- new -- +w +a +b +x +y +z +e +-- diff -- +diff old new +--- old ++++ new +@@ -1,7 +1,7 @@ ++ w + a + b +- c +- d ++ x ++ y ++ z + e +- f +- g diff --git a/testdata/dups.txtar b/testdata/dups.txtar new file mode 100644 index 0000000..f69f6ac --- /dev/null +++ b/testdata/dups.txtar @@ -0,0 +1,40 @@ +-- old -- +a + +b + +c + +d + +e + +f +-- new -- +a + +B + +C + +d + +e + +f +-- diff -- +diff old new +--- old ++++ new +@@ -1,8 +1,8 @@ + a + $ +- b +- +- c ++ B ++ ++ C + $ + d + $ diff --git a/testdata/end.txtar b/testdata/end.txtar new file mode 100644 index 0000000..1c1ef5f --- /dev/null +++ b/testdata/end.txtar @@ -0,0 +1,38 @@ +-- old -- +1 +2 +3 +4 +5 +6 +7 +eight +nine +ten +eleven +-- new -- +1 +2 +3 +4 +5 +6 +7 +8 +9 +10 +-- diff -- +diff old new +--- old ++++ new +@@ -5,7 +5,6 @@ + 5 + 6 + 7 +- eight +- nine +- ten +- eleven ++ 8 ++ 9 ++ 10 diff --git a/testdata/eof.txtar b/testdata/eof.txtar new file mode 100644 index 0000000..5dc145c --- /dev/null +++ b/testdata/eof.txtar @@ -0,0 +1,9 @@ +-- old -- +a +b +c^D +-- new -- +a +b +c^D +-- diff -- diff --git a/testdata/eof1.txtar b/testdata/eof1.txtar new file mode 100644 index 0000000..fa9e11f --- /dev/null +++ b/testdata/eof1.txtar @@ -0,0 +1,18 @@ +-- old -- +a +b +c +-- new -- +a +b +c^D +-- diff -- +diff old new +--- old ++++ new +@@ -1,3 +1,3 @@ + a + b +- c ++ c +\ No newline at end of file diff --git a/testdata/eof2.txtar b/testdata/eof2.txtar new file mode 100644 index 0000000..2a3e2d6 --- /dev/null +++ b/testdata/eof2.txtar @@ -0,0 +1,18 @@ +-- old -- +a +b +c^D +-- new -- +a +b +c +-- diff -- +diff old new +--- old ++++ new +@@ -1,3 +1,3 @@ + a + b +- c +\ No newline at end of file ++ c diff --git a/testdata/fuzz/FuzzCharDiff/10ab2b7964808a78 b/testdata/fuzz/FuzzCharDiff/10ab2b7964808a78 new file mode 100644 index 0000000..7207ac5 --- /dev/null +++ b/testdata/fuzz/FuzzCharDiff/10ab2b7964808a78 @@ -0,0 +1,3 @@ +go test fuzz v1 +[]byte("\x80") +[]byte("\x80") diff --git a/testdata/fuzz/FuzzCharDiff/959c728e1ba9028d b/testdata/fuzz/FuzzCharDiff/959c728e1ba9028d new file mode 100644 index 0000000..acd79d4 --- /dev/null +++ b/testdata/fuzz/FuzzCharDiff/959c728e1ba9028d @@ -0,0 +1,3 @@ +go test fuzz v1 +[]byte("0") +[]byte("\xe2") diff --git a/testdata/long.txtar b/testdata/long.txtar new file mode 100644 index 0000000..1ab33fb --- /dev/null +++ b/testdata/long.txtar @@ -0,0 +1,62 @@ +-- old -- +1 +2 +3 +4 +5 +6 +7 +8 +9 +10 +11 +12 +13 +14 +14½ +15 +16 +17 +18 +19 +20 +-- new -- +1 +2 +3 +4 +5 +6 +8 +9 +10 +11 +12 +13 +14 +17 +18 +19 +20 +-- diff -- +diff old new +--- old ++++ new +@@ -4,7 +4,6 @@ + 4 + 5 + 6 +- 7 + 8 + 9 + 10 +@@ -12,9 +11,6 @@ + 12 + 13 + 14 +- 14½ +- 15 +- 16 + 17 + 18 + 19 diff --git a/testdata/same.txtar b/testdata/same.txtar new file mode 100644 index 0000000..86b1100 --- /dev/null +++ b/testdata/same.txtar @@ -0,0 +1,5 @@ +-- old -- +hello world +-- new -- +hello world +-- diff -- diff --git a/testdata/start.txtar b/testdata/start.txtar new file mode 100644 index 0000000..3842583 --- /dev/null +++ b/testdata/start.txtar @@ -0,0 +1,34 @@ +-- old -- +e +pi +4 +5 +6 +7 +8 +9 +10 +-- new -- +1 +2 +3 +4 +5 +6 +7 +8 +9 +10 +-- diff -- +diff old new +--- old ++++ new +@@ -1,5 +1,6 @@ +- e +- pi ++ 1 ++ 2 ++ 3 + 4 + 5 + 6 diff --git a/testdata/triv.txtar b/testdata/triv.txtar new file mode 100644 index 0000000..a1fea60 --- /dev/null +++ b/testdata/triv.txtar @@ -0,0 +1,40 @@ +# Another example from Hunt and McIlroy, +# “An Algorithm for Differential File Comparison.” +# https://www.cs.dartmouth.edu/~doug/diff.pdf + +# Anchored diff gives up on finding anything, +# since there are no unique lines. + +-- old -- +a +b +c +a +b +b +a +-- new -- +c +a +b +a +b +c +-- diff -- +diff old new +--- old ++++ new +@@ -1,7 +1,6 @@ +- a +- b +- c +- a +- b +- b +- a ++ c ++ a ++ b ++ a ++ b ++ c -- knotmirror 0.0.1