Backtestshugorun-20260930-140149#15068
Add encoding.HexDecode/Encode
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
The issue
View on GitHubSee 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
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{
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:HexEncodeandHexDecode, written the same way asBase64Encode/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 asencoding.HexEncode/encoding.HexDecode. Other recently added functions don't have aliases either.
Test evidence:
- New unit tests:
TestHexDecodeandTestHexEncodeintpl/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:
TestHexEncodeDecodeSRIintpl/encoding/encoding_integration_test.gobuilds a site. It checks that the SRI string equalsfingerprint "sha256"'s.Data.Integrityfor the same content. - Before and after: without the production change the
tpl/encodingpackage doesn't compile ("ns.HexDecode undefined"). With it, all three tests pass, and so doesTestTemplateFuncsExamples, which runs the new examples. - How I ran them:
./bt-testcouldn't build anything because the container has no network to download Go modules. I rango testagainst the local module cache instead (GOMODCACHE=/bt/cache/go-mod GOPROXY=off). - Other
tplpackages: everything under./tpl/...passes exceptTestVimeoShortcodeintpl/tplimpl. That test fails the same way on the unchanged code, so the change didn't cause it.
Requirements:
- Add
encoding.HexDecode/HexEncode(the title): done, with tests. - Get an SRI hash without creating a resource: done. The integration test checks the output matches
fingerprint's integrity value. hash.Fingerprint/crypto.Fingerprintfrom 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-callFingerprint, it's a small follow-up.- Accept a
Resourceas input: not handled specially. The new functions accept the same inputs as the existing Base64 and crypto functions, which don't unwrap resources either. - Code reuse:
fingerprint "sha256"'s internals weren't touched. The template pipeline reuses the existingcrypto.SHA256andbase64Encode.
Also note:
- No doc pages: I didn't add
HexDecode.md/HexEncode.mdunderdocs/content/en/functions/encoding/, and the generateddocs/data/docs.yamlisn't updated. - Existing deletions:
AGENTS.mdandCLAUDE.mdwere already deleted in the working tree before I started, and I left them as they were.
Nothing is committed.