github.com/trim21/go-phpserialize@v0.0.22-0.20240301204449-2fca0319b3f0/internal/test/diff.go (about)

     1  package test
     2  
     3  import (
     4  	"bytes"
     5  	"testing"
     6  
     7  	"github.com/fatih/color"
     8  	"github.com/sergi/go-diff/diffmatchpatch"
     9  )
    10  
    11  func init() {
    12  	color.NoColor = false // force color
    13  }
    14  
    15  func diff(a, b string) []diffmatchpatch.Diff {
    16  	dmp := diffmatchpatch.New()
    17  	diffs := dmp.DiffMain(a, b, true)
    18  	if len(diffs) > 2 {
    19  		diffs = dmp.DiffCleanupSemantic(diffs)
    20  		diffs = dmp.DiffCleanupEfficiency(diffs)
    21  	}
    22  	return diffs
    23  }
    24  
    25  // CharacterDiff returns an inline diff between the two strings, using (++added++) and (~~deleted~~) markup.
    26  func CharacterDiff(a, b string) string {
    27  	return diffsToString(diff(a, b))
    28  }
    29  
    30  func diffsToString(diffs []diffmatchpatch.Diff) string {
    31  	var buff bytes.Buffer
    32  	for _, diff := range diffs {
    33  		text := diff.Text
    34  		switch diff.Type {
    35  		case diffmatchpatch.DiffDelete:
    36  			buff.WriteString(color.RedString(text))
    37  		case diffmatchpatch.DiffEqual:
    38  			buff.WriteString(text)
    39  		}
    40  	}
    41  
    42  	buff.WriteString("\n")
    43  
    44  	for _, diff := range diffs {
    45  		text := diff.Text
    46  		switch diff.Type {
    47  		case diffmatchpatch.DiffInsert:
    48  			buff.WriteString(color.GreenString(text))
    49  		case diffmatchpatch.DiffEqual:
    50  			buff.WriteString(text)
    51  		}
    52  	}
    53  
    54  	return buff.String()
    55  }
    56  
    57  func StringEqual(t *testing.T, expected, actual string) {
    58  	t.Helper()
    59  	if actual != expected {
    60  		t.Errorf("Result not as expected:\n%v", CharacterDiff(expected, actual))
    61  		t.FailNow()
    62  	}
    63  }