Skip to content

Commit

Permalink
feat: unified diff
Browse files Browse the repository at this point in the history
  • Loading branch information
cobbinma committed Feb 18, 2024
1 parent b034b5a commit 7f86dc6
Show file tree
Hide file tree
Showing 4 changed files with 35 additions and 6 deletions.
2 changes: 1 addition & 1 deletion bromide.go
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ func Snapshot[K comparable](t *testing.T, item K) {
diff := internal.Diff(existing.String(), incoming)

t.Log("snapshot mismatch")
t.Log(diff)
t.Log("\n" + diff)
t.Log("to update snapshots run `bromide review`")

os.WriteFile(pendingPath, []byte(incoming), 0644)
Expand Down
4 changes: 3 additions & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,14 @@ module github.com/cobbinma/bromide
go 1.22.0

require (
github.com/davecgh/go-spew v1.1.1
github.com/hexops/gotextdiff v1.0.3
github.com/hexops/valast v1.4.4
github.com/sergi/go-diff v1.3.1
)

require (
github.com/davecgh/go-spew v1.1.1 // indirect
github.com/andreyvit/diff v0.0.0-20170406064948-c7f18ee00883 // indirect
github.com/google/go-cmp v0.5.9 // indirect
golang.org/x/mod v0.7.0 // indirect
golang.org/x/sys v0.3.0 // indirect
Expand Down
2 changes: 2 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
github.com/andreyvit/diff v0.0.0-20170406064948-c7f18ee00883 h1:bvNMNQO63//z+xNgfBlViaCIJKLlCJ6/fmUseuG0wVQ=
github.com/andreyvit/diff v0.0.0-20170406064948-c7f18ee00883/go.mod h1:rCTlJbsFo29Kk6CurOXKm700vrz8f0KW0JNfpkRJY/8=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
Expand Down
33 changes: 29 additions & 4 deletions internal/diff.go
Original file line number Diff line number Diff line change
@@ -1,13 +1,38 @@
package internal

import (
"github.com/sergi/go-diff/diffmatchpatch"
"fmt"
"strings"

"github.com/hexops/gotextdiff"
"github.com/hexops/gotextdiff/myers"
)

func Diff(old, new string) string {
dmp := diffmatchpatch.New()
edits := myers.ComputeEdits("current", old, new)
diff := fmt.Sprint(gotextdiff.ToUnified("current", "incoming", old, edits))

out := ""
for _, line := range strings.Split(diff, "\n") {
green := "\x1b[32m"
red := "\x1b[31m"
reset := "\x1b[0m"

addition := strings.HasPrefix(line, "+")
subtraction := strings.HasPrefix(line, "-")

l := ""
switch {
case addition:
l = green + line
case subtraction:
l = red + line
default:
l = reset + line
}

diffs := dmp.DiffMain(old, new, true)
out = out + l + "\n"
}

return dmp.DiffPrettyText(diffs)
return out
}

0 comments on commit 7f86dc6

Please sign in to comment.