1
0
Fork 0
mirror of https://github.com/kyverno/kyverno.git synced 2025-03-07 00:17:13 +00:00
kyverno/pkg/cel/utils/convert.go
Charles-Edouard Brétéché 47e99166a5
feat: add kyverno vap API (#11790)
* feat: add kyverno vap API

Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com>

* add context lib

Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com>

* codegen

Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com>

---------

Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com>
Co-authored-by: Vishal Choudhary <vishal.choudhary@nirmata.com>
2025-01-08 15:56:36 +00:00

32 lines
839 B
Go

package utils
import (
"reflect"
"github.com/google/cel-go/common/types/ref"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/apimachinery/pkg/runtime"
)
func ConvertToNative[T any](value ref.Val) (T, error) {
// try to convert value to native type
response, err := value.ConvertToNative(reflect.TypeFor[T]())
// if it failed return default value for T and error
if err != nil {
var t T
return t, err
}
// return the converted value
return response.(T), nil
}
func ConvertObjectToUnstructured(obj any) (*unstructured.Unstructured, error) {
if obj == nil || reflect.ValueOf(obj).IsNil() {
return &unstructured.Unstructured{Object: nil}, nil
}
ret, err := runtime.DefaultUnstructuredConverter.ToUnstructured(obj)
if err != nil {
return nil, err
}
return &unstructured.Unstructured{Object: ret}, nil
}