Skip to content

Commit

Permalink
fix setting nil data values via --data-value flag
Browse files Browse the repository at this point in the history
  • Loading branch information
cppforlife committed May 8, 2019
1 parent a7971f8 commit c1681b1
Show file tree
Hide file tree
Showing 2 changed files with 57 additions and 5 deletions.
15 changes: 10 additions & 5 deletions pkg/yamlmeta/plain.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,11 @@ import (
"github.com/k14s/ytt/pkg/yamlmeta/internal/yaml.v2"
)

func PlainMarshal(val interface{}) ([]byte, error) {
return yaml.Marshal(val)
func PlainMarshal(in interface{}) ([]byte, error) {
return yaml.Marshal(in)
}

func PlainUnmarshal(data []byte, val interface{}) error {
func PlainUnmarshal(data []byte, out interface{}) error {
docSet, err := NewParser(true).ParseBytes(data, "")
if err != nil {
return err
Expand All @@ -21,9 +21,14 @@ func PlainUnmarshal(data []byte, val interface{}) error {
return fmt.Errorf("Expected to find exactly one YAML document")
}

decodedVal := docSet.Items[0].AsInterface(InterfaceConvertOpts{})
newVal := docSet.Items[0].AsInterface(InterfaceConvertOpts{})

reflect.Indirect(reflect.ValueOf(val)).Set(reflect.ValueOf(decodedVal))
outVal := reflect.ValueOf(out)
if newVal == nil {
outVal.Elem().Set(reflect.Zero(outVal.Elem().Type()))
} else {
outVal.Elem().Set(reflect.ValueOf(newVal))
}

return nil
}
47 changes: 47 additions & 0 deletions pkg/yamlmeta/plain_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
package yamlmeta_test

import (
"fmt"
"reflect"
"testing"

"github.com/k14s/ytt/pkg/yamlmeta"
)

var _ = fmt.Sprintf

func TestPlainUnmarshalInt(t *testing.T) {
var val interface{} = "abc" // set to some previous value

err := yamlmeta.PlainUnmarshal([]byte("123"), &val)
if err != nil {
t.Fatalf("Expected to succeed: %s", err)
}
if !reflect.DeepEqual(val, 123) {
t.Fatalf("Expected to be nil: val=%#v type=%T", val, val)
}
}

func TestPlainUnmarshalNil(t *testing.T) {
var val interface{} = 123 // set to some previous value

err := yamlmeta.PlainUnmarshal([]byte("null"), &val)
if err != nil {
t.Fatalf("Expected to succeed: %s", err)
}
if !reflect.DeepEqual(val, nil) {
t.Fatalf("Expected to be nil: val=%#v type=%T", val, val)
}
}

func TestPlainUnmarshalMap(t *testing.T) {
var val interface{} = 123 // set to some previous value

err := yamlmeta.PlainUnmarshal([]byte(`{"a":123}`), &val)
if err != nil {
t.Fatalf("Expected to succeed: %s", err)
}
if !reflect.DeepEqual(val, map[interface{}]interface{}{"a": 123}) {
t.Fatalf("Expected to be nil: val=%#v type=%T", val, val)
}
}

0 comments on commit c1681b1

Please sign in to comment.