knative.dev/pkg@v0.0.0-20260602142205-ac97e43f6622/apis/duck/unstructured.go (about) 1 /* 2 Copyright 2018 The Knative 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 duck 18 19 import ( 20 "encoding/json" 21 22 "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" 23 ) 24 25 // ToUnstructured takes an instance of a OneOfOurs compatible type and 26 // converts it to unstructured.Unstructured. We take OneOfOurs in place 27 // or runtime.Object because sometimes we get resources that do not have their 28 // TypeMeta populated but that is required for unstructured.Unstructured to 29 // deserialize things, so we leverage our content-agnostic GroupVersionKind() 30 // method to populate this as-needed (in a copy, so that we don't modify the 31 // informer's copy, if that is what we are passed). 32 func ToUnstructured(desired OneOfOurs) (*unstructured.Unstructured, error) { 33 // If the TypeMeta is not populated, then unmarshalling will fail, so ensure 34 // the TypeMeta is populated. See also EnsureTypeMeta. 35 if gvk := desired.GroupVersionKind(); gvk.Version == "" || gvk.Kind == "" { 36 gvk = desired.GetGroupVersionKind() 37 desired = desired.DeepCopyObject().(OneOfOurs) 38 desired.SetGroupVersionKind(gvk) 39 } 40 41 // Convert desired to unstructured.Unstructured 42 b, err := json.Marshal(desired) 43 if err != nil { 44 return nil, err 45 } 46 ud := &unstructured.Unstructured{} 47 if err := json.Unmarshal(b, ud); err != nil { 48 return nil, err 49 } 50 return ud, nil 51 } 52 53 // FromUnstructured takes unstructured object from (say from client-go/dynamic) and 54 // converts it into our duck types. 55 func FromUnstructured(obj json.Marshaler, target interface{}) error { 56 // Use the unstructured marshaller to ensure it's proper JSON 57 raw, err := obj.MarshalJSON() 58 if err != nil { 59 return err 60 } 61 return json.Unmarshal(raw, &target) 62 }