-
Notifications
You must be signed in to change notification settings - Fork 10
/
diff.go
71 lines (61 loc) · 1.54 KB
/
diff.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
// Package diff provides utilities for comparing strings and slices
// to produce a readable diff output for tests.
package diff
import (
"fmt"
"strconv"
"strings"
)
// Lines returns a diff of two strings, line-by-line.
func Lines(want, got string) string {
return Diff(strings.Split(want, "\n"), strings.Split(got, "\n"))
}
// Diff is a silly diff implementation
// that compares the provided slices and returns a diff of them.
func Diff[T comparable](want, got []T) string {
// We want to pad diff output with line number in the format:
//
// - 1 | line 1
// + 2 | line 2
//
// To do that, we need to know the longest line number.
longest := max(len(want), len(got))
lineFormat := fmt.Sprintf("%%s %%-%dd | %%v\n", len(strconv.Itoa(longest))) // e.g. "%-2d | %s%v\n"
const (
minus = "-"
plus = "+"
equal = " "
)
var buf strings.Builder
writeLine := func(idx int, kind string, v T) {
fmt.Fprintf(&buf, lineFormat, kind, idx+1, v)
}
var lastEqs []T
for i := 0; i < len(want) || i < len(got); i++ {
if i < len(want) && i < len(got) && want[i] == got[i] {
lastEqs = append(lastEqs, want[i])
continue
}
// If there are any equal lines before this, show up to 3 of them.
if len(lastEqs) > 0 {
start := max(len(lastEqs)-3, 0)
for j, eq := range lastEqs[start:] {
writeLine(i-3+j, equal, eq)
}
}
if i < len(want) {
writeLine(i, minus, want[i])
}
if i < len(got) {
writeLine(i, plus, got[i])
}
lastEqs = nil
}
return buf.String()
}
func max(a, b int) int {
if a > b {
return a
}
return b
}