Backtestshugorun-20260930-140149#15068

Issue #15068 Merged fix PR # Run 30 Sep 2026 · run-20260930-140149 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.

Both patches implement HexDecode/HexEncode in tpl/encoding the same way: cast.ToStringE, then hex.DecodeString or hex.EncodeToString. Both register the method mappings with examples, so the two are functionally equivalent. Either one enables the SRI workflow the issue asks for: crypto.SHA256 | encoding.HexDecode | base64Encode.

The main difference is tests. Patch B's unit tests cover more edge cases:
- uppercase hex input
- empty strings
- invalid characters ("zz")
- odd-length input ("abc")
- non-string input (42)

Patch A's unit tests have only one happy path and one type-error case each. Patch B also adds a focused integration test in the encoding package. It checks encode and decode, and it checks that the hand-built SRI string matches resources' fingerprint Data.Integrity for the same content, which directly validates the use case in the issue. Patch B also adds an SRI example to the HexDecode method mapping, which doubles as documentation.

Patch A's integration test verifies a similar equivalence but places it in tpl/templates/decorator_integration_test.go. It uses a fairly elaborate setup (a Netlify headers output format, hugo.Store, templates.Inner), so it is less focused and sits in an unrelated test file.

Patch B's HexDecode returns a partial string alongside an error, which is harmless because the error takes precedence. Overall, Patch B has stronger, better-targeted tests and slightly better documentation.

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

13m 51s16 turns

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

141vs 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+141 −0
tpl/encoding/encoding.goindex 6ac0e4f1e..cfa5d93f6 100644@@ -16,6 +16,7 @@ package encoding  import ( 	"encoding/base64"+	"encoding/hex" 	"encoding/json" 	"errors" 	"html/template"@@ -56,6 +57,27 @@ func (ns *Namespace) Base64Encode(content any) (string, error) { 	return base64.StdEncoding.EncodeToString([]byte(conv)), nil } +// HexDecode returns the string represented by the given hexadecimal content.+func (ns *Namespace) HexDecode(content any) (string, error) {+	conv, err := cast.ToStringE(content)+	if err != nil {+		return "", err+	}++	dec, err := hex.DecodeString(conv)+	return string(dec), err+}++// 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..fd4fb0c20@@ -0,0 +1,44 @@+// 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", "sitemap", "rss"]+-- layouts/home.html --+HexEncode: {{ "Hello world" | encoding.HexEncode }}|+HexDecode: {{ "48656c6c6f20776f726c64" | encoding.HexDecode }}|+SRI: sha256-{{ "Hello world" | crypto.SHA256 | encoding.HexDecode | base64Encode }}|+Fingerprint: {{ ("Hello world" | resources.FromString "foo.txt" | fingerprint "sha256").Data.Integrity }}|+`++	b := hugolib.Test(t, files)++	b.AssertFileContent("public/index.html",+		"HexEncode: 48656c6c6f20776f726c64|",+		"HexDecode: Hello world|",+		"SRI: sha256-ZOyIygCyaOW6GjVnihtTFtIS9PNmskdyMlNKiuyjfzw=|",+		"Fingerprint: sha256-ZOyIygCyaOW6GjVnihtTFtIS9PNmskdyMlNKiuyjfzw=|",+	)+}tpl/encoding/encoding_test.goindex 8e6e2da48..b567ea995 100644@@ -77,6 +77,66 @@ 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+	}{+		{"48656c6c6f20776f726c64", "Hello world"},+		{"48656C6C6F20776F726C64", "Hello world"},+		{"", ""},+		// errors+		{"zz", false},+		{"abc", 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)+	}+}+ func TestJsonify(t *testing.T) { 	t.Parallel() 	c := qt.New(t)tpl/encoding/init.goindex 1c3322d6e..46044595f 100644@@ -46,6 +46,21 @@ func init() { 			}, 		) +		ns.AddMethodMapping(ctx.HexDecode,+			nil,+			[][2]string{+				{`{{ "48656c6c6f20776f726c64" | encoding.HexDecode }}`, `Hello world`},+				{`{{ "Hello world" | crypto.SHA256 | encoding.HexDecode | base64Encode }}`, `ZOyIygCyaOW6GjVnihtTFtIS9PNmskdyMlNKiuyjfzw=`},+			},+		)++		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=';")+} 

What the agent reported

I added encoding.HexEncode and encoding.HexDecode. With them you can get an SRI hash from a string without creating a resource:

sha256-{{ "Hello world" | crypto.SHA256 | encoding.HexDecode | base64Encode }}
→ sha256-ZOyIygCyaOW6GjVnihtTFtIS9PNmskdyMlNKiuyjfzw=

What was wrong: crypto.SHA256 returns a hex string, but SRI needs the base64 of the raw digest bytes. No template function converted between the two, so the only way to get an SRI hash was to create a resource (with a made-up filename) and call fingerprint on it.

What I changed: I followed the issue title rather than the crypto.Fingerprint idea in its body. The two new functions plus the existing ones produce the SRI string.

  • tpl/encoding/encoding.go: HexEncode and HexDecode, written the same way as Base64Encode/Base64Decode. Bad hex input (odd length or non-hex characters) returns an error.
  • tpl/encoding/init.go: registers both with examples, including the SRI one. They have no short alias, so you call them as encoding.HexEncode / encoding.HexDecode. Other recently added functions don't have aliases either.

Test evidence:

  • New unit tests: TestHexDecode and TestHexEncode in tpl/encoding/encoding_test.go, in the same table style as the Base64 tests. They cover upper-case hex, empty input, a number input, and the error cases.
  • New integration test: TestHexEncodeDecodeSRI in tpl/encoding/encoding_integration_test.go builds a site. It checks that the SRI string equals fingerprint "sha256"'s .Data.Integrity for the same content.
  • Before and after: without the production change the tpl/encoding package doesn't compile ("ns.HexDecode undefined"). With it, all three tests pass, and so does TestTemplateFuncsExamples, which runs the new examples.
  • How I ran them: ./bt-test couldn't build anything because the container has no network to download Go modules. I ran go test against the local module cache instead (GOMODCACHE=/bt/cache/go-mod GOPROXY=off).
  • Other tpl packages: everything under ./tpl/... passes except TestVimeoShortcode in tpl/tplimpl. That test fails the same way on the unchanged code, so the change didn't cause it.

Requirements:

  1. Add encoding.HexDecode/HexEncode (the title): done, with tests.
  2. Get an SRI hash without creating a resource: done. The integration test checks the output matches fingerprint's integrity value.
  3. hash.Fingerprint / crypto.Fingerprint from the body: not added. The title asks for the hex functions, and those cover this use case with less new code. If you still want a one-call Fingerprint, it's a small follow-up.
  4. Accept a Resource as input: not handled specially. The new functions accept the same inputs as the existing Base64 and crypto functions, which don't unwrap resources either.
  5. Code reuse: fingerprint "sha256"'s internals weren't touched. The template pipeline reuses the existing crypto.SHA256 and base64Encode.

Also note:

  • No doc pages: I didn't add HexDecode.md/HexEncode.md under docs/content/en/functions/encoding/, and the generated docs/data/docs.yaml isn't updated.
  • Existing deletions: AGENTS.md and CLAUDE.md were already deleted in the working tree before I started, and I left them as they were.

Nothing is committed.