github.com/kubevela/workflow@v0.6.0/pkg/cue/utils.go (about) 1 /* 2 Copyright 2022 The KubeVela Authors. 3 4 Licensed under the Apache License, Version 2.0 (the "License"); 5 you may not use this file except in compliance with the License. 6 You may obtain a copy of the License at 7 8 http://www.apache.org/licenses/LICENSE-2.0 9 10 Unless required by applicable law or agreed to in writing, software 11 distributed under the License is distributed on an "AS IS" BASIS, 12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 See the License for the specific language governing permissions and 14 limitations under the License. 15 */ 16 17 package cue 18 19 import ( 20 "bytes" 21 22 "cuelang.org/go/pkg/encoding/json" 23 "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" 24 "k8s.io/apimachinery/pkg/runtime" 25 26 "github.com/kubevela/workflow/pkg/cue/model/value" 27 ) 28 29 // int data can evaluate with number in CUE, so it's OK if we convert the original float type data to int 30 func isIntegral(val float64) bool { 31 return val == float64(int(val)) 32 } 33 34 // IntifyValues will make values to int. 35 // JSON marshalling of user values will put integer into float, 36 // we have to change it back so that CUE check will succeed. 37 func IntifyValues(raw interface{}) interface{} { 38 switch v := raw.(type) { 39 case map[string]interface{}: 40 return intifyMap(v) 41 case []interface{}: 42 return intifyList(v) 43 case float64: 44 if isIntegral(v) { 45 return int(v) 46 } 47 return v 48 default: 49 return raw 50 } 51 } 52 53 func intifyList(l []interface{}) interface{} { 54 l2 := make([]interface{}, 0, len(l)) 55 for _, v := range l { 56 l2 = append(l2, IntifyValues(v)) 57 } 58 return l2 59 } 60 61 func intifyMap(m map[string]interface{}) interface{} { 62 m2 := make(map[string]interface{}, len(m)) 63 for k, v := range m { 64 m2[k] = IntifyValues(v) 65 } 66 return m2 67 } 68 69 // FillUnstructuredObject fill runtime.Unstructured to *value.Value 70 func FillUnstructuredObject(v *value.Value, obj runtime.Unstructured, paths ...string) error { 71 var buf bytes.Buffer 72 if err := unstructured.UnstructuredJSONScheme.Encode(obj, &buf); err != nil { 73 return v.FillObject(err.Error(), "err") 74 } 75 expr, err := json.Unmarshal(buf.Bytes()) 76 if err != nil { 77 return v.FillObject(err.Error(), "err") 78 } 79 return v.FillObject(expr, paths...) 80 } 81 82 // SetUnstructuredObject set runtime.Unstructured to *value.Value 83 func SetUnstructuredObject(v *value.Value, obj runtime.Unstructured, path string) error { 84 var buf bytes.Buffer 85 if err := unstructured.UnstructuredJSONScheme.Encode(obj, &buf); err != nil { 86 return v.FillObject(err.Error(), "err") 87 } 88 expr, err := json.Unmarshal(buf.Bytes()) 89 if err != nil { 90 return v.FillObject(err.Error(), "err") 91 } 92 return v.SetObject(expr, path) 93 }