Backtestshugorun-20261005-133023#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.
The core implementations are functionally identical. Both add `HexDecode` and `HexEncode` to the encoding namespace using `cast.ToStringE` plus `encoding/hex`, and both register method mappings with examples. Both let users build an SRI hash via `crypto.SHA256 | encoding.HexDecode | encoding.Base64Encode` without creating a resource, so correctness is a wash. The difference is in testing and completeness. Patch B's unit tests cover more edge cases: uppercase hex, empty input, a non-string numeric input (42), invalid characters ('zz') and odd-length input ('abc'). Its integration test is placed in the encoding package and checks encode, decode, roundtrip and a hardcoded SRI value; that value is the correct base64 of SHA-256('Hello world'). It also has an integration test for the invalid-hex error path. Patch A's unit tests have only one positive and one error case each. Its integration test does compare the computed SRI against `fingerprint`'s `Data.Integrity`, which is a nice equivalence check. However, it lives oddly in `decorator_integration_test.go` and involves unrelated machinery (custom output formats, `hugo.Store`, `templates.Inner`), which obscures what is being tested. Patch B also adds user documentation, including the SRI use case that motivated the issue. Overall B has broader edge-case coverage, better test placement and docs, with no added risk.
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
53m 3s
Wall-clock time in the container
Full test suite
No new failures
3,668 passed · 93 skipped · 3,770 total
Contamination audit
Clean
No sign the agent saw the real fix
Patch size
218vs 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
docs/content/en/functions/encoding/HexDecode.mdnew file mode 100644index 000000000..27a9b4bff@@ -0,0 +1,24 @@+---+title: encoding.HexDecode+description: Returns the decoding of the given hexadecimal content.+categories: []+keywords: []+params:+ functions_and_methods:+ aliases: []+ returnType: string+ signatures: [encoding.HexDecode INPUT]+---++```go-html-template+{{ "4875676f" | encoding.HexDecode }} → Hugo+```++Use the `encoding.HexDecode` function to convert a hexadecimal checksum to its binary form. For example, to create a [Subresource Integrity] (SRI) hash from a string without creating a resource:++```go-html-template+{{ $s := "console.log('Hello world');" }}+{{ $sri := printf "sha256-%s" ($s | crypto.SHA256 | encoding.HexDecode | 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..3e0f0b84a@@ -0,0 +1,15 @@+---+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]+---++```go-html-template+{{ "Hugo" | encoding.HexEncode }} → 4875676f+```docs/data/docs.yamlindex 19b950dd5..6e0cdeee8 100644@@ -2970,6 +2970,24 @@ tpl: Examples: - - '{{ "Hello world" | base64Encode }}' - SGVsbG8gd29ybGQ=+ HexDecode:+ Aliases: null+ Args:+ - content+ Description: HexDecode returns the decoding of the given hexadecimal content.+ Examples:+ - - '{{ "48656c6c6f20776f726c64" | encoding.HexDecode }}'+ - Hello world+ - - '{{ 42 | encoding.HexEncode | encoding.HexDecode }}'+ - '42'+ HexEncode:+ Aliases: null+ Args:+ - content+ Description: HexEncode returns the hexadecimal encoding of the given content.+ Examples:+ - - '{{ "Hello world" | encoding.HexEncode }}'+ - 48656c6c6f20776f726c64 Jsonify: Aliases: - jsonifytpl/encoding/encoding.goindex 6ac0e4f1e..1bd2a6256 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 decoding of 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)+ 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..662c187e3@@ -0,0 +1,61 @@+// 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"++ qt "github.com/frankban/quicktest"+ "github.com/gohugoio/hugo/hugolib"+)++// Issue #15068+func TestHexEncodeDecode(t *testing.T) {+ t.Parallel()++ files := `+-- hugo.toml --+disableKinds = ['page','rss','section','sitemap','taxonomy','term']+-- layouts/home.html --+encode: {{ "Hello world" | encoding.HexEncode }}|+decode: {{ "48656c6c6f20776f726c64" | encoding.HexDecode }}|+roundtrip: {{ "Hugo" | encoding.HexEncode | encoding.HexDecode }}|+sri: sha256-{{ "Hello world" | crypto.SHA256 | encoding.HexDecode | encoding.Base64Encode }}|+`++ b := hugolib.Test(t, files)++ b.AssertFileContent("public/index.html",+ "encode: 48656c6c6f20776f726c64|",+ "decode: Hello world|",+ "roundtrip: Hugo|",+ "sri: sha256-ZOyIygCyaOW6GjVnihtTFtIS9PNmskdyMlNKiuyjfzw=|",+ )+}++func TestHexDecodeInvalid(t *testing.T) {+ t.Parallel()++ files := `+-- hugo.toml --+disableKinds = ['page','rss','section','sitemap','taxonomy','term']+-- layouts/home.html --+{{ "not hex" | encoding.HexDecode }}+`++ b, err := hugolib.TestE(t, files)++ b.Assert(err, qt.IsNotNil)+ b.Assert(err.Error(), qt.Contains, "invalid byte")+}tpl/encoding/encoding_test.goindex 8e6e2da48..037fc0cfb 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+ }{+ {"616263313233213f242a262829272d3d407e", "abc123!?$*&()'-=@~"},+ {"48656C6C6F", "Hello"},+ {"", ""},+ // 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+ }{+ {"abc123!?$*&()'-=@~", "616263313233213f242a262829272d3d407e"},+ {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..6a590bf01 100644@@ -46,6 +46,21 @@ func init() { }, ) + ns.AddMethodMapping(ctx.HexDecode,+ nil,+ [][2]string{+ {`{{ "48656c6c6f20776f726c64" | encoding.HexDecode }}`, `Hello world`},+ {`{{ 42 | encoding.HexEncode | encoding.HexDecode }}`, `42`},+ },+ )++ 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=';")+}