Diff compares two gotestfmt objects by creating a JSON representation and then diffing the output. It is not intended to be used outside of gotestfmt as it does not support objects of different sizes.
(o1 interface{}, o2 interface{})
| 10 | // then diffing the output. It is not intended to be used outside of gotestfmt |
| 11 | // as it does not support objects of different sizes. |
| 12 | func Diff(o1 interface{}, o2 interface{}) string { |
| 13 | w1, err := json.MarshalIndent(o1, "", " ") |
| 14 | if err != nil { |
| 15 | panic(err) |
| 16 | } |
| 17 | w2, err := json.MarshalIndent(o2, "", " ") |
| 18 | if err != nil { |
| 19 | panic(err) |
| 20 | } |
| 21 | if string(w1) == string(w2) { |
| 22 | return "" |
| 23 | } |
| 24 | l1 := strings.Split(string(w1), "\n") |
| 25 | l2 := strings.Split(string(w2), "\n") |
| 26 | result := strings.Builder{} |
| 27 | result.WriteString(fmt.Sprintf("--- expected\n+++ actual\n@@ -1,%d +1,%d @@\n", len(l1), len(l2))) |
| 28 | for i := 0; i < len(l1); i++ { |
| 29 | if len(l2) < i+1 { |
| 30 | result.WriteString(fmt.Sprintf("-%s\n", l1[i])) |
| 31 | continue |
| 32 | } |
| 33 | if l1[i] != l2[i] { |
| 34 | result.WriteString(fmt.Sprintf("-%s\n", l1[i])) |
| 35 | result.WriteString(fmt.Sprintf("+%s\n", l2[i])) |
| 36 | } else { |
| 37 | result.WriteString(fmt.Sprintf(" %s\n", l1[i])) |
| 38 | } |
| 39 | } |
| 40 | for i := len(l1); i < len(l2); i++ { |
| 41 | result.WriteString(fmt.Sprintf("+%s\n", l2[i])) |
| 42 | } |
| 43 | return result.String() |
| 44 | } |