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 <smeyer@fastmail.com>
  • Loading branch information
notoriaga committed Sep 6, 2023
1 parent a5fd7dd commit 160fdc9
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

Check failure on line 1 in pkg/orderedmap/convert_test.go

View workflow job for this annotation

GitHub Actions / lint

Missed header for check (goheader)

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 160fdc9

Please sign in to comment.