Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions diff.go
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,11 @@ type Printfer interface {
Printf(format string, a ...interface{})
}

// Diffable is the interface that gives a chance to return custom value for diff
type Diffable interface {
DiffValue() interface{}
}

// Pdiff prints to p a description of the differences between a and b.
// It calls Printf once for each difference, with no trailing newline.
// The standard library log.Logger is a Printfer.
Expand Down Expand Up @@ -77,6 +82,17 @@ func (w diffPrinter) printf(f string, a ...interface{}) {
}

func (w diffPrinter) diff(av, bv reflect.Value) {
if av.IsValid() && av.CanInterface() {
if diffable, ok := av.Interface().(Diffable); ok {
av = reflect.ValueOf(diffable.DiffValue())
}
}
if bv.IsValid() && bv.CanInterface() {
if diffable, ok := bv.Interface().(Diffable); ok {
bv = reflect.ValueOf(diffable.DiffValue())
}
}

if !av.IsValid() && bv.IsValid() {
w.printf("nil != %# v", formatter{v: bv, quote: true})
return
Expand Down
7 changes: 7 additions & 0 deletions diff_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,8 +31,13 @@ type S struct {
type (
N struct{ N int }
E interface{}
D struct{ a string }
)

func (d D) DiffValue() interface{} {
return d.a
}

var (
c0 = make(chan int)
c1 = make(chan int)
Expand All @@ -59,6 +64,8 @@ var diffs = []difftest{
{S{C: []int{}}, S{C: []int{1}}, []string{`C: []int[0] != []int[1]`}},
{S{C: []int{1, 2, 3}}, S{C: []int{1, 2, 4}}, []string{`C[2]: 3 != 4`}},
{S{}, S{A: 1, S: new(S)}, []string{`A: 0 != 1`, `S: nil != &pretty.S{}`}},
{D{a: "a"}, D{a: "b"}, []string{`"a" != "b"`}},
{struct{ D D }{D{"a"}}, struct{ D D }{D{"b"}}, []string{`D: "a" != "b"`}},

// unexported fields of every reflect.Kind (both equal and unequal)
{struct{ x bool }{false}, struct{ x bool }{false}, nil},
Expand Down