github.com/deso-protocol/core@v1.2.9/lib/diff.go (about) 1 package lib 2 3 import ( 4 "reflect" 5 6 "github.com/davecgh/go-spew/spew" 7 "github.com/pmezard/go-difflib/difflib" 8 ) 9 10 var spewConfig = spew.ConfigState{ 11 Indent: " ", 12 DisablePointerAddresses: true, 13 DisableCapacities: true, 14 SortKeys: true, 15 } 16 17 func typeAndKind(v interface{}) (reflect.Type, reflect.Kind) { 18 t := reflect.TypeOf(v) 19 k := t.Kind() 20 21 if k == reflect.Ptr { 22 t = t.Elem() 23 k = t.Kind() 24 } 25 return t, k 26 } 27 28 // Diff returns a diff of both values as long as both are of the same type and 29 // are a struct, map, slice, array or string. Otherwise it returns an empty string. 30 func Diff(expected interface{}, actual interface{}) string { 31 if expected == nil || actual == nil { 32 return "" 33 } 34 35 et, ek := typeAndKind(expected) 36 at, _ := typeAndKind(actual) 37 38 if et != at { 39 return "" 40 } 41 42 if ek != reflect.Struct && ek != reflect.Map && ek != reflect.Slice && ek != reflect.Array && ek != reflect.String { 43 return "" 44 } 45 46 var e, a string 47 if et != reflect.TypeOf("") { 48 e = spewConfig.Sdump(expected) 49 a = spewConfig.Sdump(actual) 50 } else { 51 e = expected.(string) 52 a = actual.(string) 53 } 54 55 diff, _ := difflib.GetUnifiedDiffString(difflib.UnifiedDiff{ 56 A: difflib.SplitLines(e), 57 B: difflib.SplitLines(a), 58 FromFile: "Expected", 59 FromDate: "", 60 ToFile: "Actual", 61 ToDate: "", 62 Context: 1, 63 }) 64 65 return "\n\nDiff:\n" + diff 66 }