Skip to content

Commit

Permalink
fix(yaml): make MarshalYAML deterministic
Browse files Browse the repository at this point in the history
This PR sorts the keys of a map[string]interface{} before marshaling to
YAML, similar to what the standard encoding/json does.

* fixes go-swagger/go-swagger#2850

Signed-off-by: Frederic BIDON <fredbi@yahoo.com>
  • Loading branch information
fredbi committed Dec 22, 2023
1 parent 3f60c98 commit 11b0957
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 2 deletions.
10 changes: 9 additions & 1 deletion yaml.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ import (
"fmt"
"path/filepath"
"reflect"
"sort"
"strconv"

"github.com/mailru/easyjson/jlexer"
Expand Down Expand Up @@ -286,7 +287,14 @@ func json2yaml(item interface{}) (*yaml.Node, error) {
case map[string]interface{}:
var n yaml.Node
n.Kind = yaml.MappingNode
for k, v := range val {
keys := make([]string, 0, len(val))
for k := range val {
keys = append(keys, k)
}
sort.Strings(keys)

for _, k := range keys {
v := val[k]
childNode, err := json2yaml(v)
if err != nil {
return nil, err
Expand Down
24 changes: 23 additions & 1 deletion yaml_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -75,8 +75,30 @@ y: some value
assert.Equal(t, expected, string(ny.([]byte)))
}

func TestYAMLToJSON(t *testing.T) {
func TestMarshalYAML(t *testing.T) {
t.Run("marshalYAML should be deterministic", func(t *testing.T) {
const (
jazon = `{"1":"x","2":null,"3":{"a":1,"b":2,"c":3}}`
expected = `"1": x
"2": null
"3":
a: !!float 1
b: !!float 2
c: !!float 3
`
)
const iterations = 10
for n := 0; n < iterations; n++ {
var data JSONMapSlice
require.NoError(t, json.Unmarshal([]byte(jazon), &data))
ny, err := data.MarshalYAML()
require.NoError(t, err)
assert.Equal(t, expected, string(ny.([]byte)))
}
})
}

func TestYAMLToJSON(t *testing.T) {
sd := `---
1: the int key value
name: a string value
Expand Down

0 comments on commit 11b0957

Please sign in to comment.