Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

De/restructure objects via JSON #48

Merged
merged 1 commit into from
Oct 25, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
Loading