From 9edf7d613c6029fb27c111d8edaeec168714df76 Mon Sep 17 00:00:00 2001 From: RageCage64 Date: Wed, 21 Sep 2022 07:58:24 -0400 Subject: [PATCH] rename MultilineDiff, return diff count --- cmd/experiment/main.go | 22 ---------------------- internal/experiment/main.go | 24 ++++++++++++++++++++++++ multilinediff.go | 9 ++++----- reporter.go | 11 ++++++----- 4 files changed, 34 insertions(+), 32 deletions(-) delete mode 100644 cmd/experiment/main.go create mode 100644 internal/experiment/main.go diff --git a/cmd/experiment/main.go b/cmd/experiment/main.go deleted file mode 100644 index bde3026..0000000 --- a/cmd/experiment/main.go +++ /dev/null @@ -1,22 +0,0 @@ -package main - -import ( - "fmt" - - "github.com/RageCage64/multilinediff" -) - -func main() { - a := `a -b -c -diff` - b := `a -b -c -f -f -f` - - fmt.Println(multilinediff.MultilineDiff(a, b, "\n")) -} diff --git a/internal/experiment/main.go b/internal/experiment/main.go new file mode 100644 index 0000000..e725dd6 --- /dev/null +++ b/internal/experiment/main.go @@ -0,0 +1,24 @@ +package main + +import ( + "fmt" + + "github.com/RageCage64/multilinediff" +) + +func main() { + a := `a +b +c +diff` + b := `a b +c +f +f +f +diff` + diff, count := multilinediff.Diff(a, b, "\n") + fmt.Println(count) + fmt.Println("--------") + fmt.Println(diff) +} diff --git a/multilinediff.go b/multilinediff.go index b1fabcd..68bafdd 100644 --- a/multilinediff.go +++ b/multilinediff.go @@ -7,10 +7,9 @@ import ( "github.com/google/go-cmp/cmp/cmpopts" ) -func MultilineDiff(a, b, lineSep string) string { - reporter := Reporter{ - LineSep: lineSep, - } +// Get the diff between two strings. +func Diff(a, b, lineSep string) (string, int) { + reporter := Reporter{LineSep: lineSep} cmp.Diff( a, b, cmpopts.AcyclicTransformer("multiline", func(s string) []string { @@ -18,5 +17,5 @@ func MultilineDiff(a, b, lineSep string) string { }), cmp.Reporter(&reporter), ) - return reporter.String() + return reporter.String(), reporter.DiffCount } diff --git a/reporter.go b/reporter.go index 2cfe812..b78edbe 100644 --- a/reporter.go +++ b/reporter.go @@ -46,12 +46,13 @@ func (l diffLine) toLine(length int) string { return line } +// A pretty reporter to pass into cmp.Diff using the cmd.Reporter function. type Reporter struct { - LineSep string + LineSep string + DiffCount int - path cmp.Path - lines []diffLine - diffCount int + path cmp.Path + lines []diffLine } func (r *Reporter) PushStep(ps cmp.PathStep) { @@ -62,7 +63,7 @@ func (r *Reporter) Report(rs cmp.Result) { line := diffLine{} vOld, vNew := r.path.Last().Values() if !rs.Equal() { - r.diffCount++ + r.DiffCount++ if vOld.IsValid() { line.diff = diffTypeChange line.old = fmt.Sprintf("%+v", vOld)