Created
November 11, 2015 18:43
-
-
Save agileknight/fbf00a42950a8d846bda to your computer and use it in GitHub Desktop.
golang formatting readable diff between two arbitrary types using console colors
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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()) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
If someone else in the future gets here, like I did, from googling "coloured git diff golang" (Or colored I guess for American folks!) then this is now natively in the
diffmatchpatch
library with theDiffPrettyText
function:Code ustream:
https://github.com/sergi/go-diff/blob/da645544ed44df016359bd4c0e3dc60ee3a0da43/diffmatchpatch/diff.go#L1182
😄