knative.dev/pkg@v0.0.0-20260602142205-ac97e43f6622/controller/helper.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 https://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 controller 18 19 import ( 20 "k8s.io/apimachinery/pkg/api/meta" 21 "k8s.io/apimachinery/pkg/runtime/schema" 22 23 "knative.dev/pkg/kmeta" 24 ) 25 26 // Callback is a function that is passed to an informer's event handler. 27 type Callback func(interface{}) 28 29 // EnsureTypeMeta augments the passed-in callback, ensuring that all objects that pass 30 // through this callback have their TypeMeta set according to the provided GVK. 31 func EnsureTypeMeta(f Callback, gvk schema.GroupVersionKind) Callback { 32 apiVersion, kind := gvk.ToAPIVersionAndKind() 33 34 return func(untyped interface{}) { 35 typed, err := kmeta.DeletionHandlingAccessor(untyped) 36 if err != nil { 37 // TODO: We should consider logging here. 38 return 39 } 40 41 accessor, err := meta.TypeAccessor(typed) 42 if err != nil { 43 return 44 } 45 46 // If TypeMeta is already what we want, exit early. 47 if accessor.GetAPIVersion() == apiVersion && accessor.GetKind() == kind { 48 f(typed) 49 return 50 } 51 52 // We need to populate TypeMeta, but cannot trample the 53 // informer's copy. 54 copy := typed.DeepCopyObject() 55 56 accessor, err = meta.TypeAccessor(copy) 57 if err != nil { 58 return 59 } 60 accessor.SetAPIVersion(apiVersion) 61 accessor.SetKind(kind) 62 63 // Pass in the mutated copy (accessor is not just a type cast) 64 f(copy) 65 } 66 }