Skip to content

Commit

Permalink
Merge pull request #870 from swift-nav/steve/orderedmap-fix
Browse files Browse the repository at this point in the history
don't modify input when converting to orderedmap
  • Loading branch information
joaopapereira authored Mar 13, 2024
2 parents 6cad190 + f2458e6 commit 9d65662
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 5 deletions.
11 changes: 6 additions & 5 deletions pkg/orderedmap/convert.go
Original file line number Diff line number Diff line change
Expand Up @@ -70,20 +70,21 @@ func (c Conversion) fromUnorderedMaps(object interface{}) interface{} {
panic("Expected map[interface{}]interface{} instead of *unordered.Map in fromUnorderedMaps")

case []interface{}:
result := make([]interface{}, len(typedObj))
for i, item := range typedObj {
typedObj[i] = c.fromUnorderedMaps(item)
result[i] = c.fromUnorderedMaps(item)
}
return typedObj
return result

// some sources (e.g. toml library) yield specific type of slices.
// slices in Go are not covariant, so each flavor of slice must have its own case, here.
// process these exactly the same way we do for generic slices (prior case)
case []map[string]interface{}:
resultArray := make([]interface{}, len(typedObj))
result := make([]interface{}, len(typedObj))
for i, item := range typedObj {
resultArray[i] = c.fromUnorderedMaps(item)
result[i] = c.fromUnorderedMaps(item)
}
return resultArray
return result
default:
return typedObj
}
Expand Down
25 changes: 25 additions & 0 deletions pkg/orderedmap/convert_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
// Copyright 2020 VMware, Inc.
// SPDX-License-Identifier: Apache-2.0
package orderedmap_test

import (
"reflect"
"testing"

"carvel.dev/ytt/pkg/orderedmap"
)

func TestFromUnorderedMaps(t *testing.T) {
inputA := map[string]interface{}{
"key": []interface{}{map[string]interface{}{"nestedKey": "nestedValue"}},
}
inputB := map[string]interface{}{
"key": []interface{}{map[string]interface{}{"nestedKey": "nestedValue"}},
}

orderedmap.Conversion{Object: inputA}.FromUnorderedMaps()

if !reflect.DeepEqual(inputA, inputB) {
t.Errorf("Nested object was modified. Got: %v, Expected: %v", inputA, inputB)
}
}

0 comments on commit 9d65662

Please sign in to comment.