diff --git a/pkg/cue/model/value/value.go b/pkg/cue/model/value/value.go index dce0a7c..9c73fcd 100644 --- a/pkg/cue/model/value/value.go +++ b/pkg/cue/model/value/value.go @@ -17,6 +17,7 @@ limitations under the License. package value import ( + "encoding/json" "fmt" "strconv" "strings" @@ -301,3 +302,12 @@ func FieldPath(paths ...string) cue.Path { } return cue.ParsePath(s) } + +// UnmarshalTo unmarshal value into golang object +func UnmarshalTo(val cue.Value, x interface{}) error { + data, err := val.MarshalJSON() + if err != nil { + return err + } + return json.Unmarshal(data, x) +} diff --git a/pkg/cue/model/value/value_test.go b/pkg/cue/model/value/value_test.go index 1dadee1..5005856 100644 --- a/pkg/cue/model/value/value_test.go +++ b/pkg/cue/model/value/value_test.go @@ -17,6 +17,7 @@ limitations under the License. package value import ( + "encoding/json" "fmt" "testing" @@ -257,3 +258,37 @@ a: b: c: [{x: 100}, {x: 101}, {x: 102}]`, r.Equal(s, tCase.expected, tCase.name) } } + +func TestUnmarshal(t *testing.T) { + case1 := ` +provider: "kube" +do: "apply" +` + out := struct { + Provider string `json:"provider"` + Do string `json:"do"` + }{} + + r := require.New(t) + cuectx := cuecontext.New() + val := cuectx.CompileString(case1) + err := UnmarshalTo(val, &out) + r.NoError(err) + r.Equal(out.Provider, "kube") + r.Equal(out.Do, "apply") + + bt, err := val.MarshalJSON() + r.NoError(err) + expectedJson, err := json.Marshal(out) + r.NoError(err) + r.Equal(string(bt), string(expectedJson)) + + caseIncomplete := ` +provider: string +do: string +` + val = cuectx.CompileString(caseIncomplete) + r.NoError(err) + err = UnmarshalTo(val, &out) + r.Error(err) +}