Skip to content

Commit

Permalink
add unmarshal to as util func
Browse files Browse the repository at this point in the history
Signed-off-by: FogDong <[email protected]>
  • Loading branch information
FogDong committed Apr 27, 2024
1 parent 3b2ccc8 commit 0bc92e8
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 0 deletions.
10 changes: 10 additions & 0 deletions pkg/cue/model/value/value.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ limitations under the License.
package value

import (
"encoding/json"
"fmt"
"strconv"
"strings"
Expand Down Expand Up @@ -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)
}
35 changes: 35 additions & 0 deletions pkg/cue/model/value/value_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ limitations under the License.
package value

import (
"encoding/json"
"fmt"
"testing"

Expand Down Expand Up @@ -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)
}

0 comments on commit 0bc92e8

Please sign in to comment.