Skip to content

Commit

Permalink
Merge pull request Kuadrant#48 from Kuadrant/fix/unstructured-objects
Browse files Browse the repository at this point in the history
De/restructure objects via JSON
  • Loading branch information
guicassolato authored Oct 25, 2024
2 parents ec853f9 + 3a07f46 commit ca213ee
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 6 deletions.
3 changes: 3 additions & 0 deletions controller/controller.go
Original file line number Diff line number Diff line change
Expand Up @@ -217,6 +217,9 @@ func (c *Controller) Reconcile(ctx context.Context, _ ctrlruntimereconcile.Reque
store := Store{}
for _, f := range c.listFuncs {
for _, object := range f() {
if object == nil {
continue
}
store[string(object.GetUID())] = object
}
}
Expand Down
21 changes: 15 additions & 6 deletions controller/runnable.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package controller

import (
"context"
"encoding/json"
"fmt"
"reflect"
"strings"
Expand Down Expand Up @@ -159,7 +160,10 @@ 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 runtimeObj
})
},
Expand Down Expand Up @@ -221,16 +225,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
}
return o, nil
o := new(T)
if err := json.Unmarshal(j, o); err != nil {
return nil, err
}
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
Expand Down

0 comments on commit ca213ee

Please sign in to comment.