]> git.maquefel.me Git - brevno-suite/hugo/commitdiff
tpl/strings: Create strings.Diff template function
authorJoe Mooring <joe.mooring@veriphor.com>
Tue, 2 Apr 2024 02:26:15 +0000 (19:26 -0700)
committerBjørn Erik Pedersen <bjorn.erik.pedersen@gmail.com>
Tue, 2 Apr 2024 16:25:44 +0000 (18:25 +0200)
Closes #12330

tpl/strings/strings.go
tpl/strings/strings_test.go

index cd233b0a4445aa834fa825ad673db0bfb94ef6f5..e6f7aed80d05b2e888de3821386fae22821d85a5 100644 (file)
@@ -27,6 +27,7 @@ import (
        "github.com/gohugoio/hugo/deps"
        "github.com/gohugoio/hugo/helpers"
        "github.com/gohugoio/hugo/tpl"
+       "github.com/rogpeppe/go-internal/diff"
 
        "github.com/spf13/cast"
 )
@@ -172,6 +173,15 @@ func (ns *Namespace) ContainsNonSpace(s any) bool {
        return false
 }
 
+// Diff returns an anchored diff of the two texts old and new in the “unified
+// diff” format. If old and new are identical, Diff returns an empty string.
+func (ns *Namespace) Diff(oldname string, old any, newname string, new any) string {
+       oldb := []byte(cast.ToString(old))
+       newb := []byte(cast.ToString(new))
+
+       return string(diff.Diff(oldname, oldb, newname, newb))
+}
+
 // HasPrefix tests whether the input s begins with prefix.
 func (ns *Namespace) HasPrefix(s, prefix any) (bool, error) {
        ss, err := cast.ToStringE(s)
index 43334a8e8c957bb328d81de92f2bd3e284ef6fef..92767925adecae82c645bb4a4da3366b15f5130c 100644 (file)
@@ -17,10 +17,9 @@ import (
        "html/template"
        "testing"
 
+       qt "github.com/frankban/quicktest"
        "github.com/gohugoio/hugo/config/testconfig"
        "github.com/gohugoio/hugo/deps"
-
-       qt "github.com/frankban/quicktest"
        "github.com/spf13/cast"
 )
 
@@ -808,3 +807,26 @@ func TestRepeat(t *testing.T) {
                c.Assert(result, qt.Equals, test.expect)
        }
 }
+
+func TestDiff(t *testing.T) {
+       t.Parallel()
+       c := qt.New(t)
+
+       for _, tt := range []struct {
+               oldname string
+               old     any
+               newname string
+               new     any
+               expect  string
+       }{
+               {"old", "foo\n", "new", "bar\n", "diff old new\n--- old\n+++ new\n@@ -1,1 +1,1 @@\n-foo\n+bar\n"},
+               {"old", "foo\n", "new", "foo\n", ""},
+               {"old", "foo\n", "new", "", "diff old new\n--- old\n+++ new\n@@ -1,1 +0,0 @@\n-foo\n"},
+               {"old", "foo\n", "new", nil, "diff old new\n--- old\n+++ new\n@@ -1,1 +0,0 @@\n-foo\n"},
+               {"old", "", "new", "", ""},
+       } {
+
+               result := ns.Diff(tt.oldname, tt.old, tt.newname, tt.new)
+               c.Assert(result, qt.Equals, tt.expect)
+       }
+}