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())
}
@petems
Copy link

petems commented Jan 6, 2019

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 the DiffPrettyText function:

package main

import (
	"fmt"

	"github.com/sergi/go-diff/diffmatchpatch"
)

const (
	text1 = "Lorem ipsum dolor."
	text2 = "Lorem dolor sit amet."
)

func main() {
	dmp := diffmatchpatch.New()

	diffs := dmp.DiffMain(text1, text2, false)

	fmt.Println(dmp.DiffPrettyText(diffs))
}

Code ustream:

// DiffPrettyText converts a []Diff into a colored text report.
func (dmp *DiffMatchPatch) DiffPrettyText(diffs []Diff) string {
	var buff bytes.Buffer
	for _, diff := range diffs {
		text := diff.Text

		switch diff.Type {
		case DiffInsert:
			_, _ = buff.WriteString("\x1b[32m")
			_, _ = buff.WriteString(text)
			_, _ = buff.WriteString("\x1b[0m")
		case DiffDelete:
			_, _ = buff.WriteString("\x1b[31m")
			_, _ = buff.WriteString(text)
			_, _ = buff.WriteString("\x1b[0m")
		case DiffEqual:
			_, _ = buff.WriteString(text)
		}
	}

	return buff.String()
}

https://github.com/sergi/go-diff/blob/da645544ed44df016359bd4c0e3dc60ee3a0da43/diffmatchpatch/diff.go#L1182

😄

@rewanthtammana
Copy link

Nice one

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