From dd249f9d739f5bfc5074a30bd50b85042536871d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?K=C3=A9vin=20Gomez?= Date: Tue, 13 Jun 2023 14:09:48 +0200 Subject: [PATCH] Configure goccy/go-yaml to mimic go-yaml/yaml marshaling style --- pkg/encoding/yaml.go | 25 ++++++++++++++++++++++++- 1 file changed, 24 insertions(+), 1 deletion(-) diff --git a/pkg/encoding/yaml.go b/pkg/encoding/yaml.go index a5b1e592..01b067a9 100644 --- a/pkg/encoding/yaml.go +++ b/pkg/encoding/yaml.go @@ -2,8 +2,10 @@ package encoding import ( "io" + "math" "os" "path/filepath" + "strconv" "github.com/goccy/go-yaml" ) @@ -15,7 +17,28 @@ func NewYAMLDecoder(reader io.Reader) *yaml.Decoder { // MarshalYAML takes an input and renders as a YAML string. func MarshalYAML(input any) (string, error) { - y, err := yaml.Marshal(input) + y, err := yaml.MarshalWithOptions( + input, + yaml.Indent(4), + yaml.IndentSequence(true), + yaml.UseLiteralStyleIfMultiline(true), + yaml.CustomMarshaler[float64](func(v float64) ([]byte, error) { + // goccy/go-yaml tends to add .0 suffixes to floats, even when they're not required. + // To preserve consistency with go-yaml/yaml, this custom marshaler disables that feature. + + if v == math.Inf(0) { + return []byte(".inf"), nil + } + if v == math.Inf(-1) { + return []byte("-.inf"), nil + } + if math.IsNaN(v) { + return []byte(".nan"), nil + } + + return []byte(strconv.FormatFloat(v, 'g', -1, 64)), nil + }), + ) if err != nil { return "", err }