Backtestshugorun-20261002-200313#15068

Issue #15068 Merged fix PR # Run 2 Oct 2026 · run-20261002-200313 gohugoio/hugo

Add encoding.HexDecode/Encode

Better

Our patch was judged better than the merged fix.

In this judgment, Patch B = our agent, Patch A = the merged fix.

The production code is functionally identical in both patches: `HexDecode` and `HexEncode` on the encoding namespace use `cast.ToStringE` plus `encoding/hex`, with the same method mappings and examples in `init.go`. Correctness is therefore equal, and the difference comes down to tests and craft. Patch B's unit tests are more thorough. They cover uppercase hex input, empty strings, invalid characters (`zz`), odd-length input (`486`), non-string input (42), and a round-trip check that encoding then decoding reproduces the original. Patch A's unit tests have only one happy-path case and one type-error case per function. Both patches add an integration test that checks the issue's motivating case: building an SRI string with `crypto.SHA256 | encoding.HexDecode | encoding.Base64Encode` and comparing it to the `Data.Integrity` of a fingerprinted resource. Patch B puts this test in a new `encoding_integration_test.go` next to the feature it exercises, and it also checks plain encode and decode output. Patch A puts its test in `tpl/templates/decorator_integration_test.go`, which is an odd place unrelated to the encoding package, and it pulls in decorator, Store and CSP-header machinery that obscures what the test is for. Patch B also adds documentation pages for both functions, including the SRI use case. That earns little credit on its own but adds no risk. Overall, Patch B has stronger edge-case tests and better-placed integration tests for the same implementation.

The judge saw only the two patches, labelled A and B in random order, with issue links and version numbers removed. The reasoning above is shown verbatim.

Solve

57m 4s

Wall-clock time in the container

Full test suite

No new failures

3,667 passed · 93 skipped · 3,769 total

Contamination audit

Clean

No sign the agent saw the real fix

Patch size

195vs 137 merged

Changed lines, ours vs merged

See https://github.com/gohugoio/hugo/issues/15060#issuecomment-4790405347

It's clumsy that you need to create a resource (making up an unique filename) to get a SRI hash.

I suggest we add crypto.Fingerprint with a similar signature to https://gohugo.io/functions/resources/fingerprint/

hash.Fingerprint [ALGORITHM] any -> string

The function name is a little clumsy, but we need to keep the two very similar functions in line.

Where any typically is a string (but can also be a Resource -- we have similar unwrappers elsewhere).

It would then return e.g. sha256-Yuh...rfE=.

Note to implementer: There's some obvious code reuse potential here.

The two patches

Our patch+195 −0
docs/content/en/functions/encoding/HexDecode.mdnew file mode 100644index 000000000..9f7e8651d@@ -0,0 +1,28 @@+---+title: encoding.HexDecode+description: Returns the hexadecimal decoding of the given content.+categories: []+keywords: []+params:+  functions_and_methods:+    aliases: []+    returnType: string+    signatures: [encoding.HexDecode INPUT]+---++{{< new-in 0.164.0 />}}++```go-html-template+{{ "4875676f" | encoding.HexDecode }} → Hugo+```++Combine with a hash function such as [`crypto.SHA256`] and [`encoding.Base64Encode`] to create a [Subresource Integrity] (SRI) hash from a string, without first creating a resource:++```go-html-template+{{ $integrity := printf "sha256-%s" ("Hugo" | crypto.SHA256 | encoding.HexDecode | encoding.Base64Encode) }}+{{ $integrity }} → sha256-1wtIm7l+wJ26+nLkYcgyDQThOtFg3XTI5ppg6mLcj/0=+```++[`crypto.SHA256`]: /functions/crypto/sha256/+[`encoding.Base64Encode`]: /functions/encoding/base64encode/+[Subresource Integrity]: https://developer.mozilla.org/en-US/docs/Web/Security/Subresource_Integritydocs/content/en/functions/encoding/HexEncode.mdnew file mode 100644index 000000000..86c72185d@@ -0,0 +1,17 @@+---+title: encoding.HexEncode+description: Returns the hexadecimal encoding of the given content.+categories: []+keywords: []+params:+  functions_and_methods:+    aliases: []+    returnType: string+    signatures: [encoding.HexEncode INPUT]+---++{{< new-in 0.164.0 />}}++```go-html-template+{{ "Hugo" | encoding.HexEncode }} → 4875676f+```tpl/encoding/encoding.goindex 6ac0e4f1e..e6d316e0e 100644@@ -16,6 +16,7 @@ package encoding  import ( 	"encoding/base64"+	"encoding/hex" 	"encoding/json" 	"errors" 	"html/template"@@ -56,6 +57,30 @@ func (ns *Namespace) Base64Encode(content any) (string, error) { 	return base64.StdEncoding.EncodeToString([]byte(conv)), nil } +// HexDecode returns the hexadecimal decoding of the given content.+func (ns *Namespace) HexDecode(content any) (string, error) {+	conv, err := cast.ToStringE(content)+	if err != nil {+		return "", err+	}++	dec, err := hex.DecodeString(conv)+	if err != nil {+		return "", err+	}+	return string(dec), nil+}++// HexEncode returns the hexadecimal encoding of the given content.+func (ns *Namespace) HexEncode(content any) (string, error) {+	conv, err := cast.ToStringE(content)+	if err != nil {+		return "", err+	}++	return hex.EncodeToString([]byte(conv)), nil+}+ // Jsonify encodes a given object to JSON.  To pretty print the JSON, pass a map // or dictionary of options as the first value in args.  Supported options are // "prefix" and "indent".  Each JSON element in the output will begin on a newtpl/encoding/encoding_integration_test.gonew file mode 100644index 000000000..661003b5f@@ -0,0 +1,46 @@+// Copyright 2026 The Hugo Authors. All rights reserved.+//+// Licensed under the Apache License, Version 2.0 (the "License");+// you may not use this file except in compliance with the License.+// You may obtain a copy of the License at+// http://www.apache.org/licenses/LICENSE-2.0+//+// Unless required by applicable law or agreed to in writing, software+// distributed under the License is distributed on an "AS IS" BASIS,+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+// See the License for the specific language governing permissions and+// limitations under the License.++package encoding_test++import (+	"testing"++	"github.com/gohugoio/hugo/hugolib"+)++// Issue 15060.+func TestHexEncodeDecodeSRI(t *testing.T) {+	t.Parallel()++	files := `+-- hugo.toml --+disableKinds = ["page", "section", "taxonomy", "term", "rss", "sitemap", "404"]+-- layouts/home.html --+{{ $s := "Hugo" }}+HexEncode: {{ $s | encoding.HexEncode }}|+HexDecode: {{ $s | encoding.HexEncode | encoding.HexDecode }}|+{{ $r := resources.FromString "foo.txt" $s | fingerprint "sha256" }}+SRI resource: {{ $r.Data.Integrity }}|+SRI string: {{ printf "sha256-%s" ($s | crypto.SHA256 | encoding.HexDecode | encoding.Base64Encode) }}|+`++	b := hugolib.Test(t, files)++	b.AssertFileContent("public/index.html",+		"HexEncode: 4875676f|",+		"HexDecode: Hugo|",+		"SRI resource: sha256-1wtIm7l&#43;wJ26&#43;nLkYcgyDQThOtFg3XTI5ppg6mLcj/0=|",+		"SRI string: sha256-1wtIm7l&#43;wJ26&#43;nLkYcgyDQThOtFg3XTI5ppg6mLcj/0=|",+	)+}tpl/encoding/encoding_test.goindex 8e6e2da48..3f6f64262 100644@@ -19,6 +19,7 @@ import ( 	"testing"  	qt "github.com/frankban/quicktest"+	"github.com/spf13/cast" )  type tstNoStringer struct{}@@ -119,3 +120,67 @@ func TestJsonify(t *testing.T) { 		c.Assert(result, qt.Equals, test.expect, qt.Commentf("#%d", i)) 	} }++func TestHexDecode(t *testing.T) {+	t.Parallel()+	c := qt.New(t)++	ns := New()++	for _, test := range []struct {+		v      any+		expect any+	}{+		{"48656c6c6f20776f726c64", "Hello world"},+		{"48656C6C6F", "Hello"},+		{"", ""},+		// errors+		{"zz", false},+		{"486", false},+		{t, false},+	} {++		result, err := ns.HexDecode(test.v)++		if b, ok := test.expect.(bool); ok && !b {+			c.Assert(err, qt.Not(qt.IsNil))+			continue+		}++		c.Assert(err, qt.IsNil)+		c.Assert(result, qt.Equals, test.expect)+	}+}++func TestHexEncode(t *testing.T) {+	t.Parallel()+	c := qt.New(t)++	ns := New()++	for _, test := range []struct {+		v      any+		expect any+	}{+		{"Hello world", "48656c6c6f20776f726c64"},+		{42, "3432"},+		{"", ""},+		// errors+		{t, false},+	} {++		result, err := ns.HexEncode(test.v)++		if b, ok := test.expect.(bool); ok && !b {+			c.Assert(err, qt.Not(qt.IsNil))+			continue+		}++		c.Assert(err, qt.IsNil)+		c.Assert(result, qt.Equals, test.expect)++		decoded, err := ns.HexDecode(result)+		c.Assert(err, qt.IsNil)+		c.Assert(decoded, qt.Equals, cast.ToString(test.v))+	}+}tpl/encoding/init.goindex 1c3322d6e..aab411e4d 100644@@ -46,6 +46,20 @@ func init() { 			}, 		) +		ns.AddMethodMapping(ctx.HexDecode,+			nil,+			[][2]string{+				{`{{ "48656c6c6f20776f726c64" | encoding.HexDecode }}`, `Hello world`},+			},+		)++		ns.AddMethodMapping(ctx.HexEncode,+			nil,+			[][2]string{+				{`{{ "Hello world" | encoding.HexEncode }}`, `48656c6c6f20776f726c64`},+			},+		)+ 		ns.AddMethodMapping(ctx.Jsonify, 			[]string{"jsonify"}, 			[][2]string{ 
Merged fix · PR #+137 −0
tpl/encoding/encoding.goindex 6ac0e4f1e..1f7cf7b79 100644@@ -16,6 +16,7 @@ package encoding  import ( 	"encoding/base64"+	"encoding/hex" 	"encoding/json" 	"errors" 	"html/template"@@ -56,6 +57,28 @@ func (ns *Namespace) Base64Encode(content any) (string, error) { 	return base64.StdEncoding.EncodeToString([]byte(conv)), nil } +// HexDecode returns the hex decoding of the given content.+func (ns *Namespace) HexDecode(content any) (string, error) {+	conv, err := cast.ToStringE(content)+	if err != nil {+		return "", err+	}+	b, err := hex.DecodeString(conv)+	if err != nil {+		return "", err+	}+	return string(b), nil+}++// HexEncode returns the hex encoding of the given content.+func (ns *Namespace) HexEncode(content any) (string, error) {+	conv, err := cast.ToStringE(content)+	if err != nil {+		return "", err+	}+	return hex.EncodeToString([]byte(conv)), nil+}+ // Jsonify encodes a given object to JSON.  To pretty print the JSON, pass a map // or dictionary of options as the first value in args.  Supported options are // "prefix" and "indent".  Each JSON element in the output will begin on a newtpl/encoding/encoding_test.goindex 8e6e2da48..116bef408 100644@@ -77,6 +77,60 @@ func TestBase64Encode(t *testing.T) { 	} } +func TestHexDecode(t *testing.T) {+	t.Parallel()+	c := qt.New(t)++	ns := New()++	for _, test := range []struct {+		v      any+		expect any+	}{+		{"616263313233213f242a2628292d3d407e", "abc123!?$*&()-=@~"},+		// errors+		{t, false},+	} {++		result, err := ns.HexDecode(test.v)++		if b, ok := test.expect.(bool); ok && !b {+			c.Assert(err, qt.Not(qt.IsNil))+			continue+		}++		c.Assert(err, qt.IsNil)+		c.Assert(result, qt.Equals, test.expect)+	}+}++func TestHexEncode(t *testing.T) {+	t.Parallel()+	c := qt.New(t)++	ns := New()++	for _, test := range []struct {+		v      any+		expect any+	}{+		{"abc123!?$*&()-=@~", "616263313233213f242a2628292d3d407e"},+		// errors+		{t, false},+	} {++		result, err := ns.HexEncode(test.v)++		if b, ok := test.expect.(bool); ok && !b {+			c.Assert(err, qt.Not(qt.IsNil))+			continue+		}++		c.Assert(err, qt.IsNil)+		c.Assert(result, qt.Equals, test.expect)+	}+}+ func TestJsonify(t *testing.T) { 	t.Parallel() 	c := qt.New(t)tpl/encoding/init.goindex 1c3322d6e..aab411e4d 100644@@ -46,6 +46,20 @@ func init() { 			}, 		) +		ns.AddMethodMapping(ctx.HexDecode,+			nil,+			[][2]string{+				{`{{ "48656c6c6f20776f726c64" | encoding.HexDecode }}`, `Hello world`},+			},+		)++		ns.AddMethodMapping(ctx.HexEncode,+			nil,+			[][2]string{+				{`{{ "Hello world" | encoding.HexEncode }}`, `48656c6c6f20776f726c64`},+			},+		)+ 		ns.AddMethodMapping(ctx.Jsonify, 			[]string{"jsonify"}, 			[][2]string{tpl/templates/decorator_integration_test.goindex 253a09316..e671c446c 100644@@ -453,3 +453,49 @@ Home. {{ partial "a" }}:Done. 		} 	} }++func TestDecoratorFingerprintScript(t *testing.T) {+	t.Parallel()++	files := `+-- hugo.toml --+baseURL = "https://example.org/"+[outputs]+home = ["html", "headers"]+[mediaTypes]+[mediaTypes."text/netlify"]+delimiter = ""+[outputFormats]+[outputFormats.headers]+baseName       = "_headers"+isPlainText    = true+mediatype      = "text/netlify"+notAlternative = true+-- layouts/_partials/script.html --+{{ $s := (templates.Inner .) }}+{{ $r := resources.FromString ($s | xxhash) $s | fingerprint }}+{{ $hash := $s | crypto.SHA256 | encoding.HexDecode | encoding.Base64Encode }}+{{ $sri := (printf "sha256-%s" $hash) }}+{{ if ne $sri $r.Data.Integrity }}+	{{ errorf "SRI hash mismatch: %s != %s" $sri $r.Data.Integrity }}+{{ end }}+{{ hugo.Store.SetInMap "srihashes" $sri true }}+<script>{{ $s | safeJS }}</script>+-- layouts/home.html --+Home.+{{ with partial "script.html" . }}+console.log("Hello world");+{{ end }}+{{ with partial "script.html" . }}+console.log("Hugo rocks!");+{{ end }}+-- layouts/home.headers --+{{ $hashes := hugo.Store.Get "srihashes" -}}+Content-Security-Policy: script-src 'self'{{ range $k, $v := $hashes }} '{{ $k }}'{{ end }};+`++	b := hugolib.Test(t, files)++	b.AssertFileContentExact("public/index.html", "<script>\nconsole.log(\"Hello world\");\n</script>")+	b.AssertFileContentExact("public/_headers", "Content-Security-Policy: script-src 'self' 'sha256-t6z9j4/CagmaDDbn6nHbntzt8PRk8HZ1TwrgdYuZjbE=' 'sha256-wVbS8f78ttoSSGU80KghGoPcTO8DXqT0Uc/87a7zMdk=';")+}