Skip to content

Instantly share code, notes, and snippets.

@agileknight
Created November 11, 2015 18:43
Show Gist options
  • Save agileknight/fbf00a42950a8d846bda to your computer and use it in GitHub Desktop.
Save agileknight/fbf00a42950a8d846bda to your computer and use it in GitHub Desktop.
golang formatting readable diff between two arbitrary types using console colors
package diff
import (
"bytes"
"fmt"
"github.com/davecgh/go-spew/spew"
"github.com/sergi/go-diff/diffmatchpatch"
)
// FormatNotEqual pretty prints the diff between two instances for the console (using color)
func FormatNotEqual(expected, actual interface{}) string {
spew.Config.SortKeys = true
a := spew.Sdump(expected)
b := spew.Sdump(actual)
dmp := diffmatchpatch.New()
diffs := dmp.DiffMain(a, b, false)
var buff bytes.Buffer
for _, diff := range diffs {
switch diff.Type {
case diffmatchpatch.DiffInsert:
buff.WriteString("\x1b[102m[+")
buff.WriteString(diff.Text)
buff.WriteString("]\x1b[0m")
case diffmatchpatch.DiffDelete:
buff.WriteString("\x1b[101m[-")
buff.WriteString(diff.Text)
buff.WriteString("]\x1b[0m")
case diffmatchpatch.DiffEqual:
buff.WriteString(diff.Text)
}
}
return fmt.Sprintf("%s", buff.String())
}
@rewanthtammana
Copy link

Nice one

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment