Skip to content

Commit

Permalink
don't modify input when converting to orderedmap
Browse files Browse the repository at this point in the history
Signed-off-by: notoriaga <[email protected]>
  • Loading branch information
notoriaga committed Feb 15, 2024
1 parent 6d2001d commit 21d94ed
Show file tree
Hide file tree
Showing 2 changed files with 29 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
23 changes: 23 additions & 0 deletions pkg/orderedmap/convert_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
package orderedmap_test

import (
"reflect"
"testing"

"github.com/vmware-tanzu/carvel-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 21d94ed

Please sign in to comment.