Skip to content

Commit 1d28411

Browse files
authored
Merge pull request sergi#30 from zimmski/pretty-text
Colored text diff
2 parents e99546f + af9d84e commit 1d28411

File tree

2 files changed

+34
-0
lines changed

2 files changed

+34
-0
lines changed

diffmatchpatch/dmp.go

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1412,6 +1412,29 @@ func (dmp *DiffMatchPatch) DiffPrettyHtml(diffs []Diff) string {
14121412
return buff.String()
14131413
}
14141414

1415+
// DiffPrettyText converts a []Diff into a colored text report.
1416+
func (dmp *DiffMatchPatch) DiffPrettyText(diffs []Diff) string {
1417+
var buff bytes.Buffer
1418+
for _, diff := range diffs {
1419+
text := diff.Text
1420+
1421+
switch diff.Type {
1422+
case DiffInsert:
1423+
_, _ = buff.WriteString("\x1b[32m")
1424+
_, _ = buff.WriteString(text)
1425+
_, _ = buff.WriteString("\x1b[0m")
1426+
case DiffDelete:
1427+
_, _ = buff.WriteString("\x1b[31m")
1428+
_, _ = buff.WriteString(text)
1429+
_, _ = buff.WriteString("\x1b[0m")
1430+
case DiffEqual:
1431+
_, _ = buff.WriteString(text)
1432+
}
1433+
}
1434+
1435+
return buff.String()
1436+
}
1437+
14151438
// DiffText1 computes and returns the source text (all equalities and deletions).
14161439
func (dmp *DiffMatchPatch) DiffText1(diffs []Diff) string {
14171440
//StringBuilder text = new StringBuilder()

diffmatchpatch/dmp_test.go

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -746,6 +746,17 @@ func Test_diffPrettyHtml(t *testing.T) {
746746
dmp.DiffPrettyHtml(diffs))
747747
}
748748

749+
func Test_diffPrettyText(t *testing.T) {
750+
dmp := New()
751+
// Pretty print.
752+
diffs := []Diff{
753+
Diff{DiffEqual, "a\n"},
754+
Diff{DiffDelete, "<B>b</B>"},
755+
Diff{DiffInsert, "c&d"}}
756+
assert.Equal(t, "a\n\x1b[31m<B>b</B>\x1b[0m\x1b[32mc&d\x1b[0m",
757+
dmp.DiffPrettyText(diffs))
758+
}
759+
749760
func Test_diffText(t *testing.T) {
750761
dmp := New()
751762
// Compute the source and destination texts.

0 commit comments

Comments
 (0)