Skip to content

Commit e0cd83b

Browse files
authored
Remove color escape after newline from diff line (#2)
* remove color escape after newline from diff line * clear color codes after emitting format line, tests for color codes
1 parent 9fc5f72 commit e0cd83b

File tree

2 files changed

+46
-4
lines changed

2 files changed

+46
-4
lines changed

difflib/difflib.go

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -595,7 +595,7 @@ func (d *Differ) StructuredDump(tag byte, x []string, low int, high int) (out []
595595
size := high - low
596596
out = make([]DiffLine, size)
597597
for i := 0; i < size; i++ {
598-
out[i] = NewDiffLine(tag, x[i + low])
598+
out[i] = NewDiffLine(tag, x[i+low])
599599
}
600600
return out
601601
}
@@ -877,9 +877,8 @@ func WriteUnifiedDiff(writer io.Writer, diff LineDiffParams) error {
877877
equalFormat := " %s"
878878

879879
if diff.Colored {
880-
addFormat = "\x1b[32m+%s" // Foreground Green
881-
removeFormat = "\x1b[31m-%s" // Foreground Red
882-
equalFormat = "\x1b[0m %s" // No Color
880+
addFormat = "\x1b[32m+%s\x1b[0m" // Foreground Green
881+
removeFormat = "\x1b[31m-%s\x1b[0m" // Foreground Red
883882
}
884883

885884
for _, c := range g {

difflib/difflib_test.go

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -615,3 +615,46 @@ func TestGetUnifiedDiffString(t *testing.T) {
615615
t.Fatal("GetUnifiedDiffString failure:", diffStr)
616616
}
617617
}
618+
619+
func TestColoredDiffString(t *testing.T) {
620+
A := "one\ntwo\nthree\nfour"
621+
B := "one\ntwo\nthr33\nfour"
622+
623+
// Build diff
624+
diff := LineDiffParams{
625+
A: SplitLines(A),
626+
B: SplitLines(B),
627+
Context: 3,
628+
Colored: true,
629+
}
630+
// string builder always returns a nil error so it's safe to ignore here
631+
diffStr, err := GetUnifiedDiffString(diff)
632+
if err != nil {
633+
t.Fatal("Failed")
634+
}
635+
636+
if !strings.Contains(diffStr, "\x1b[31m-three\n\x1b[0m") {
637+
t.Fatal("Failed to remove removeFormat formatting")
638+
}
639+
640+
if !strings.Contains(diffStr, "one\n") {
641+
t.Fatal("Neutal Line contained color format")
642+
}
643+
644+
// Reverse diff
645+
diff = LineDiffParams{
646+
A: SplitLines(B),
647+
B: SplitLines(A),
648+
Context: 3,
649+
Colored: true,
650+
}
651+
// string builder always returns a nil error so it's safe to ignore here
652+
diffStr, err = GetUnifiedDiffString(diff)
653+
if err != nil {
654+
t.Fatal("Failed")
655+
}
656+
657+
if !strings.Contains(diffStr, "\x1b[32m+three\n\x1b[0m") {
658+
t.Fatal("Failed to remove addFormat formatting")
659+
}
660+
}

0 commit comments

Comments
 (0)