Skip to content

Commit 42f277f

Browse files
committed
Replace to gopkg.in/yaml with github.com/goccy/go-yaml (note)
Fixes #8822 Fixes #13043
1 parent fc3d1cb commit 42f277f

17 files changed

+139
-243
lines changed

Diff for: commands/gen.go

+1-1
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,7 @@ import (
2727
"github.com/alecthomas/chroma/v2/formatters/html"
2828
"github.com/alecthomas/chroma/v2/styles"
2929
"github.com/bep/simplecobra"
30+
"github.com/goccy/go-yaml"
3031
"github.com/gohugoio/hugo/common/hugo"
3132
"github.com/gohugoio/hugo/docshelper"
3233
"github.com/gohugoio/hugo/helpers"
@@ -35,7 +36,6 @@ import (
3536
"github.com/gohugoio/hugo/parser"
3637
"github.com/spf13/cobra"
3738
"github.com/spf13/cobra/doc"
38-
"gopkg.in/yaml.v2"
3939
)
4040

4141
func newGenCommand() *genCommand {

Diff for: commands/server.go

-1
Original file line numberDiff line numberDiff line change
@@ -1160,7 +1160,6 @@ func chmodFilter(dst, src os.FileInfo) bool {
11601160
}
11611161

11621162
func cleanErrorLog(content string) string {
1163-
content = strings.ReplaceAll(content, "\n", " ")
11641163
content = logReplacer.Replace(content)
11651164
content = logDuplicateTemplateExecuteRe.ReplaceAllString(content, "")
11661165
content = logDuplicateTemplateParseRe.ReplaceAllString(content, "")

Diff for: common/herrors/file_error.go

+9-10
Original file line numberDiff line numberDiff line change
@@ -110,11 +110,11 @@ func (fe *fileError) UpdateContent(r io.Reader, linematcher LineMatcherFn) FileE
110110

111111
fe.errorContext = ectx
112112

113-
if ectx.Position.LineNumber > 0 {
113+
if ectx.Position.LineNumber > 0 && ectx.Position.LineNumber > fe.position.LineNumber {
114114
fe.position.LineNumber = ectx.Position.LineNumber
115115
}
116116

117-
if ectx.Position.ColumnNumber > 0 {
117+
if ectx.Position.ColumnNumber > 0 && ectx.Position.ColumnNumber > fe.position.ColumnNumber {
118118
fe.position.ColumnNumber = ectx.Position.ColumnNumber
119119
}
120120

@@ -177,6 +177,7 @@ func NewFileErrorFromName(err error, name string) FileError {
177177
// Filetype is used to determine the Chroma lexer to use.
178178
fileType, pos := extractFileTypePos(err)
179179
pos.Filename = name
180+
180181
if fileType == "" {
181182
_, fileType = paths.FileAndExtNoDelimiter(filepath.Clean(name))
182183
}
@@ -234,7 +235,9 @@ func NewFileErrorFromFile(err error, filename string, fs afero.Fs, linematcher L
234235
return NewFileErrorFromName(err, realFilename)
235236
}
236237
defer f.Close()
237-
return NewFileErrorFromName(err, realFilename).UpdateContent(f, linematcher)
238+
fe := NewFileErrorFromName(err, realFilename)
239+
fe = fe.UpdateContent(f, linematcher)
240+
return fe
238241
}
239242

240243
func openFile(filename string, fs afero.Fs) (afero.File, string, error) {
@@ -302,13 +305,9 @@ func extractFileTypePos(err error) (string, text.Position) {
302305
}
303306

304307
// Look in the error message for the line number.
305-
for _, handle := range lineNumberExtractors {
306-
lno, col := handle(err)
307-
if lno > 0 {
308-
pos.ColumnNumber = col
309-
pos.LineNumber = lno
310-
break
311-
}
308+
if lno, col := commonLineNumberExtractor(err); lno > 0 {
309+
pos.ColumnNumber = col
310+
pos.LineNumber = lno
312311
}
313312

314313
if fileType == "" && pos.Filename != "" {

Diff for: common/herrors/line_number_extractors.go

+13-3
Original file line numberDiff line numberDiff line change
@@ -19,17 +19,27 @@ import (
1919
)
2020

2121
var lineNumberExtractors = []lineNumberExtractor{
22+
// YAML parse errors.
23+
newLineNumberErrHandlerFromRegexp(`\[(\d+):(\d+)\]`),
24+
2225
// Template/shortcode parse errors
2326
newLineNumberErrHandlerFromRegexp(`:(\d+):(\d*):`),
2427
newLineNumberErrHandlerFromRegexp(`:(\d+):`),
2528

26-
// YAML parse errors
27-
newLineNumberErrHandlerFromRegexp(`line (\d+):`),
28-
2929
// i18n bundle errors
3030
newLineNumberErrHandlerFromRegexp(`\((\d+),\s(\d*)`),
3131
}
3232

33+
func commonLineNumberExtractor(e error) (int, int) {
34+
for _, handler := range lineNumberExtractors {
35+
lno, col := handler(e)
36+
if lno > 0 {
37+
return lno, col
38+
}
39+
}
40+
return 0, 0
41+
}
42+
3343
type lineNumberExtractor func(e error) (int, int)
3444

3545
func newLineNumberErrHandlerFromRegexp(expression string) lineNumberExtractor {

Diff for: common/herrors/line_number_extractors_test.go

+31
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
// Copyright 2024 The Hugo Authors. All rights reserved.
2+
//
3+
// Licensed under the Apache License, Version 2.0 (the "License");
4+
// you may not use this file except in compliance with the License.
5+
// You may obtain a copy of the License at
6+
// http://www.apache.org/licenses/LICENSE-2.0
7+
//
8+
// Unless required by applicable law or agreed to in writing, software
9+
// distributed under the License is distributed on an "AS IS" BASIS,
10+
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11+
// See the License for the specific language governing permissions and
12+
// limitations under the License.
13+
14+
package herrors
15+
16+
import (
17+
"errors"
18+
"testing"
19+
20+
qt "github.com/frankban/quicktest"
21+
)
22+
23+
func TestCommonLineNumberExtractor(t *testing.T) {
24+
t.Parallel()
25+
26+
c := qt.New(t)
27+
28+
lno, col := commonLineNumberExtractor(errors.New("[4:9] value is not allowed in this context"))
29+
c.Assert(lno, qt.Equals, 4)
30+
c.Assert(col, qt.Equals, 9)
31+
}

Diff for: go.mod

+1
Original file line numberDiff line numberDiff line change
@@ -125,6 +125,7 @@ require (
125125
github.com/go-logr/stdr v1.2.2 // indirect
126126
github.com/go-openapi/jsonpointer v0.20.2 // indirect
127127
github.com/go-openapi/swag v0.22.8 // indirect
128+
github.com/goccy/go-yaml v1.15.3 // indirect
128129
github.com/golang-jwt/jwt/v5 v5.2.1 // indirect
129130
github.com/golang/groupcache v0.0.0-20210331224755-41bb18bfe9da // indirect
130131
github.com/google/s2a-go v0.1.8 // indirect

Diff for: go.sum

+2
Original file line numberDiff line numberDiff line change
@@ -223,6 +223,8 @@ github.com/gobuffalo/flect v1.0.3 h1:xeWBM2nui+qnVvNM4S3foBhCAL2XgPU+a7FdpelbTq4
223223
github.com/gobuffalo/flect v1.0.3/go.mod h1:A5msMlrHtLqh9umBSnvabjsMrCcCpAyzglnDvkbYKHs=
224224
github.com/gobwas/glob v0.2.3 h1:A4xDbljILXROh+kObIiy5kIaPYD8e96x1tgBhUI5J+Y=
225225
github.com/gobwas/glob v0.2.3/go.mod h1:d3Ez4x06l9bZtSvzIay5+Yzi0fmZzPgnTbPcKjJAkT8=
226+
github.com/goccy/go-yaml v1.15.3 h1:wQ4UwLFkgbSazdi+i9AVmZE3vKTktlNlI2kQqXo5L+I=
227+
github.com/goccy/go-yaml v1.15.3/go.mod h1:XBurs7gK8ATbW4ZPGKgcbrY1Br56PdM69F7LkFRi1kA=
226228
github.com/gohugoio/go-i18n/v2 v2.1.3-0.20230805085216-e63c13218d0e h1:QArsSubW7eDh8APMXkByjQWvuljwPGAGQpJEFn0F0wY=
227229
github.com/gohugoio/go-i18n/v2 v2.1.3-0.20230805085216-e63c13218d0e/go.mod h1:3Ltoo9Banwq0gOtcOwxuHG6omk+AwsQPADyw2vQYOJQ=
228230
github.com/gohugoio/hashstructure v0.1.0 h1:kBSTMLMyTXbrJVAxaKI+wv30MMJJxn9Q8kfQtJaZ400=

Diff for: hugolib/frontmatter_test.go

+2-2
Original file line numberDiff line numberDiff line change
@@ -40,7 +40,7 @@ Strings: {{ printf "%T" .Params.strings }} {{ range .Params.strings }}Strings: {
4040

4141
b.Build()
4242

43-
b.AssertFileContent("public/post/one/index.html", "Ints: []interface {} Int: 1 (int)|Int: 2 (int)|Int: 3 (int)|")
44-
b.AssertFileContent("public/post/one/index.html", "Mixed: []interface {} Mixed: 1 (string)|Mixed: 2 (int)|Mixed: 3 (int)|")
43+
b.AssertFileContent("public/post/one/index.html", "Ints: []interface {} Int: 1 (uint64)|Int: 2 (uint64)|Int: 3 (uint64)|")
44+
b.AssertFileContent("public/post/one/index.html", "Mixed: []interface {} Mixed: 1 (string)|Mixed: 2 (uint64)|Mixed: 3 (uint64)|")
4545
b.AssertFileContent("public/post/one/index.html", "Strings: []string Strings: 1 (string)|Strings: 2 (string)|Strings: 3 (string)|")
4646
}

Diff for: hugolib/hugo_sites_build_errors_test.go

+33-1
Original file line numberDiff line numberDiff line change
@@ -476,7 +476,7 @@ line 5
476476
errors := herrors.UnwrapFileErrorsWithErrorContext(err)
477477

478478
b.Assert(errors, qt.HasLen, 3)
479-
b.Assert(errors[0].Error(), qt.Contains, filepath.FromSlash(`"/content/_index.md:1:1": "/layouts/_default/_markup/render-heading.html:2:5": execute of template failed`))
479+
b.Assert(errors[0].Error(), qt.Contains, filepath.FromSlash(`"/content/_index.md:2:5": "/layouts/_default/_markup/render-heading.html:2:5": execute of template failed`))
480480
}
481481

482482
func TestErrorRenderHookCodeblock(t *testing.T) {
@@ -645,3 +645,35 @@ Home.
645645
b.Assert(err.Error(), qt.Contains, filepath.FromSlash(`/layouts/index.html:2:3`))
646646
b.Assert(err.Error(), qt.Contains, `can't evaluate field ThisDoesNotExist`)
647647
}
648+
649+
func TestErrorFrontmatterYAMLSyntax(t *testing.T) {
650+
t.Parallel()
651+
652+
files := `
653+
-- hugo.toml --
654+
-- content/_index.md --
655+
656+
657+
658+
659+
660+
---
661+
line1: 'value1'
662+
x
663+
line2: 'value2'
664+
line3: 'value3'
665+
---
666+
`
667+
668+
b, err := TestE(t, files)
669+
670+
b.Assert(err, qt.Not(qt.IsNil))
671+
b.Assert(err.Error(), qt.Contains, "> 3 |")
672+
fe := herrors.UnwrapFileError(err)
673+
b.Assert(fe, qt.Not(qt.IsNil))
674+
pos := fe.Position()
675+
b.Assert(pos.Filename, qt.Contains, filepath.FromSlash("content/_index.md"))
676+
b.Assert(fe.ErrorContext(), qt.Not(qt.IsNil))
677+
b.Assert(pos.LineNumber, qt.Equals, 9)
678+
b.Assert(pos.ColumnNumber, qt.Equals, 1)
679+
}

Diff for: hugolib/page__content.go

+11-14
Original file line numberDiff line numberDiff line change
@@ -283,23 +283,20 @@ func (c *contentParseInfo) parseFrontMatter(it pageparser.Item, iter *pageparser
283283
var err error
284284
c.frontMatter, err = metadecoders.Default.UnmarshalToMap(it.Val(source), f)
285285
if err != nil {
286-
if fe, ok := err.(herrors.FileError); ok {
287-
pos := fe.Position()
286+
fe := herrors.UnwrapFileError(err)
287+
if fe == nil {
288+
fe = herrors.NewFileError(err)
289+
}
290+
pos := fe.Position()
288291

289-
// Offset the starting position of front matter.
290-
offset := iter.LineNumber(source) - 1
291-
if f == metadecoders.YAML {
292-
offset -= 1
293-
}
294-
pos.LineNumber += offset
292+
// Offset the starting position of front matter.
293+
offset := iter.LineNumber(source) - 1
295294

296-
fe.UpdatePosition(pos)
297-
fe.SetFilename("") // It will be set later.
295+
pos.LineNumber += offset
298296

299-
return fe
300-
} else {
301-
return err
302-
}
297+
fe.UpdatePosition(pos)
298+
fe.SetFilename("") // It will be set later.
299+
return fe
303300
}
304301

305302
return nil

Diff for: hugolib/pages_capture.go

+1-1
Original file line numberDiff line numberDiff line change
@@ -123,7 +123,7 @@ func (c *pagesCollector) Collect() (collectErr error) {
123123
Handle: func(ctx context.Context, fi hugofs.FileMetaInfo) error {
124124
numPages, numResources, err := c.m.AddFi(fi, c.buildConfig)
125125
if err != nil {
126-
return hugofs.AddFileInfoToError(err, fi, c.fs)
126+
return hugofs.AddFileInfoToError(err, fi, c.h.SourceFs)
127127
}
128128
numFilesProcessedTotal.Add(1)
129129
numPagesProcessedTotal.Add(numPages)

Diff for: langs/i18n/translationProvider.go

+1-1
Original file line numberDiff line numberDiff line change
@@ -20,9 +20,9 @@ import (
2020

2121
"github.com/gohugoio/hugo/common/paths"
2222

23+
yaml "github.com/goccy/go-yaml"
2324
"github.com/gohugoio/hugo/common/herrors"
2425
"golang.org/x/text/language"
25-
yaml "gopkg.in/yaml.v2"
2626

2727
"github.com/gohugoio/go-i18n/v2/i18n"
2828
"github.com/gohugoio/hugo/helpers"

Diff for: parser/frontmatter.go

+1-3
Original file line numberDiff line numberDiff line change
@@ -22,8 +22,6 @@ import (
2222

2323
toml "github.com/pelletier/go-toml/v2"
2424

25-
yaml "gopkg.in/yaml.v2"
26-
2725
xml "github.com/clbanning/mxj/v2"
2826
)
2927

@@ -39,7 +37,7 @@ func InterfaceToConfig(in any, format metadecoders.Format, w io.Writer) error {
3937

4038
switch format {
4139
case metadecoders.YAML:
42-
b, err := yaml.Marshal(in)
40+
b, err := metadecoders.MarshalYAML(in)
4341
if err != nil {
4442
return err
4543
}

Diff for: parser/metadecoders/decoder.go

+3-78
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
// Copyright 2018 The Hugo Authors. All rights reserved.
1+
// Copyright 2024 The Hugo Authors. All rights reserved.
22
//
33
// Licensed under the Apache License, Version 2.0 (the "License");
44
// you may not use this file except in compliance with the License.
@@ -28,10 +28,10 @@ import (
2828
"github.com/niklasfasching/go-org/org"
2929

3030
xml "github.com/clbanning/mxj/v2"
31+
yaml "github.com/goccy/go-yaml"
3132
toml "github.com/pelletier/go-toml/v2"
3233
"github.com/spf13/afero"
3334
"github.com/spf13/cast"
34-
yaml "gopkg.in/yaml.v2"
3535
)
3636

3737
// Decoder provides some configuration options for the decoders.
@@ -164,35 +164,7 @@ func (d Decoder) UnmarshalTo(data []byte, f Format, v any) error {
164164
case TOML:
165165
err = toml.Unmarshal(data, v)
166166
case YAML:
167-
err = yaml.Unmarshal(data, v)
168-
if err != nil {
169-
return toFileError(f, data, fmt.Errorf("failed to unmarshal YAML: %w", err))
170-
}
171-
172-
// To support boolean keys, the YAML package unmarshals maps to
173-
// map[interface{}]interface{}. Here we recurse through the result
174-
// and change all maps to map[string]interface{} like we would've
175-
// gotten from `json`.
176-
var ptr any
177-
switch vv := v.(type) {
178-
case *map[string]any:
179-
ptr = *vv
180-
case *any:
181-
ptr = *vv
182-
default:
183-
// Not a map.
184-
}
185-
186-
if ptr != nil {
187-
if mm, changed := stringifyMapKeys(ptr); changed {
188-
switch vv := v.(type) {
189-
case *map[string]any:
190-
*vv = mm.(map[string]any)
191-
case *any:
192-
*vv = mm
193-
}
194-
}
195-
}
167+
return yaml.Unmarshal(data, v)
196168
case CSV:
197169
return d.unmarshalCSV(data, v)
198170

@@ -269,50 +241,3 @@ func (d Decoder) unmarshalORG(data []byte, v any) error {
269241
func toFileError(f Format, data []byte, err error) error {
270242
return herrors.NewFileErrorFromName(err, fmt.Sprintf("_stream.%s", f)).UpdateContent(bytes.NewReader(data), nil)
271243
}
272-
273-
// stringifyMapKeys recurses into in and changes all instances of
274-
// map[interface{}]interface{} to map[string]interface{}. This is useful to
275-
// work around the impedance mismatch between JSON and YAML unmarshaling that's
276-
// described here: https://github.com/go-yaml/yaml/issues/139
277-
//
278-
// Inspired by https://github.com/stripe/stripe-mock, MIT licensed
279-
func stringifyMapKeys(in any) (any, bool) {
280-
switch in := in.(type) {
281-
case []any:
282-
for i, v := range in {
283-
if vv, replaced := stringifyMapKeys(v); replaced {
284-
in[i] = vv
285-
}
286-
}
287-
case map[string]any:
288-
for k, v := range in {
289-
if vv, changed := stringifyMapKeys(v); changed {
290-
in[k] = vv
291-
}
292-
}
293-
case map[any]any:
294-
res := make(map[string]any)
295-
var (
296-
ok bool
297-
err error
298-
)
299-
for k, v := range in {
300-
var ks string
301-
302-
if ks, ok = k.(string); !ok {
303-
ks, err = cast.ToStringE(k)
304-
if err != nil {
305-
ks = fmt.Sprintf("%v", k)
306-
}
307-
}
308-
if vv, replaced := stringifyMapKeys(v); replaced {
309-
res[ks] = vv
310-
} else {
311-
res[ks] = v
312-
}
313-
}
314-
return res, true
315-
}
316-
317-
return nil, false
318-
}

0 commit comments

Comments
 (0)