From 441b3616a4c2244b4c8f56602692d4e9d415496c Mon Sep 17 00:00:00 2001 From: Guilherme Cassolato Date: Fri, 25 Oct 2024 16:34:38 +0200 Subject: [PATCH] De/restructure objects via JSON Signed-off-by: Guilherme Cassolato --- controller/runnable.go | 22 ++++++++++++++++------ 1 file changed, 16 insertions(+), 6 deletions(-) diff --git a/controller/runnable.go b/controller/runnable.go index fb9ef29..f0033f4 100644 --- a/controller/runnable.go +++ b/controller/runnable.go @@ -2,6 +2,7 @@ package controller import ( "context" + "encoding/json" "fmt" "reflect" "strings" @@ -159,7 +160,11 @@ func StateReconciler[T Object](obj T, resource schema.GroupVersionResource, name controller.logger.Error(err, "failed to restructure object", "kind", kind) return nil } - runtimeObj, _ := obj.(Object) + runtimeObj, ok := obj.(Object) + if !ok { + controller.logger.Error(fmt.Errorf("unexpected object type: %T", obj), "failed to cast object", "kind", kind) + return nil + } return runtimeObj }) }, @@ -221,16 +226,21 @@ func Restructure[T any](obj any) (any, error) { if !ok { return nil, fmt.Errorf("unexpected object type: %T", obj) } - o := *new(T) - if err := runtime.DefaultUnstructuredConverter.FromUnstructured(unstructuredObj.UnstructuredContent(), &o); err != nil { + j, err := unstructuredObj.MarshalJSON() + if err != nil { + return nil, err + } + o := new(T) + if err := json.Unmarshal(j, o); err != nil { return nil, err } - return o, nil + return *o, nil } func Destruct[T any](obj T) (*unstructured.Unstructured, error) { - u, err := runtime.DefaultUnstructuredConverter.ToUnstructured(&obj) - if err != nil { + j, _ := json.Marshal(obj) + var u map[string]interface{} + if err := json.Unmarshal(j, &u); err != nil { return nil, err } return &unstructured.Unstructured{Object: u}, nil