File: diff.go

package info (click to toggle)
golang-github-alecthomas-assert 0.0~git20170929.405dbfe-1.1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, bullseye, sid
  • size: 176 kB
  • sloc: makefile: 2
file content (56 lines) | stat: -rw-r--r-- 1,345 bytes parent folder | download | duplicates (2)
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
package assert

import (
	"bytes"
	"fmt"

	"github.com/alecthomas/colour"
	"github.com/alecthomas/repr"
	"github.com/sergi/go-diff/diffmatchpatch"
)

func DiffValues(a, b interface{}) string {
	printer := colour.String()
	diff := diffmatchpatch.New()
	at := repr.String(a, repr.OmitEmpty(true))
	bt := repr.String(b, repr.OmitEmpty(true))
	diffs := diff.DiffMain(at, bt, true)
	for _, d := range diffs {
		switch d.Type {
		case diffmatchpatch.DiffEqual:
			if len(d.Text) <= 40 {
				printer.Print(d.Text)
			} else {
				printer.Printf("%s^B...^R%s", d.Text[:15], d.Text[len(d.Text)-15:])
			}
		case diffmatchpatch.DiffDelete:
			printer.Printf("^9%s^R", d.Text)
		case diffmatchpatch.DiffInsert:
			printer.Printf("^a%s^R", d.Text)
		}
	}
	return printer.String()
}

func DiffValuesDefault(a, b interface{}) string {
	diff := diffmatchpatch.New()
	at := repr.String(a)
	bt := repr.String(b)
	diffs := diff.DiffMain(at, bt, true)
	w := bytes.NewBuffer(nil)
	for _, d := range diffs {
		switch d.Type {
		case diffmatchpatch.DiffEqual:
			if len(d.Text) <= 40 {
				w.WriteString(d.Text)
			} else {
				fmt.Fprintf(w, "%s...%s", d.Text[:15], d.Text[len(d.Text)-15:])
			}
		case diffmatchpatch.DiffDelete:
			fmt.Fprintf(w, "-{{%s}}", d.Text)
		case diffmatchpatch.DiffInsert:
			fmt.Fprintf(w, "+{{%s}}", d.Text)
		}
	}
	return w.String()
}