istio.io/istio@v0.0.0-20240520182934-d79c90f27776/pkg/config/schema/kubetypes/common.go (about) 1 // Copyright Istio Authors 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 package kubetypes 16 17 import ( 18 "fmt" 19 20 "k8s.io/apimachinery/pkg/runtime" 21 "k8s.io/apimachinery/pkg/runtime/schema" 22 23 "istio.io/istio/pkg/config" 24 "istio.io/istio/pkg/config/schema/gvk" 25 "istio.io/istio/pkg/ptr" 26 "istio.io/istio/pkg/typemap" 27 ) 28 29 func MustGVRFromType[T runtime.Object]() schema.GroupVersionResource { 30 if gk, ok := getGvk(ptr.Empty[T]()); ok { 31 gr, ok := gvk.ToGVR(gk) 32 if !ok { 33 panic(fmt.Sprintf("unknown GVR for GVK %v", gk)) 34 } 35 return gr 36 } 37 if rp := typemap.Get[RegisterType[T]](registeredTypes); rp != nil { 38 return (*rp).GetGVR() 39 } 40 panic("unknown kind: " + ptr.TypeName[T]()) 41 } 42 43 func MustGVKFromType[T runtime.Object]() (cfg config.GroupVersionKind) { 44 if gvk, ok := getGvk(ptr.Empty[T]()); ok { 45 return gvk 46 } 47 if rp := typemap.Get[RegisterType[T]](registeredTypes); rp != nil { 48 return (*rp).GetGVK() 49 } 50 panic("unknown kind: " + cfg.String()) 51 } 52 53 func MustToGVR[T runtime.Object](cfg config.GroupVersionKind) schema.GroupVersionResource { 54 if r, ok := gvk.ToGVR(cfg); ok { 55 return r 56 } 57 if rp := typemap.Get[RegisterType[T]](registeredTypes); rp != nil { 58 return (*rp).GetGVR() 59 } 60 panic("unknown kind: " + cfg.String()) 61 } 62 63 func GvkFromObject(obj runtime.Object) config.GroupVersionKind { 64 if gvk, ok := getGvk(obj); ok { 65 return gvk 66 } 67 panic("unknown kind: " + obj.GetObjectKind().GroupVersionKind().String()) 68 } 69 70 var registeredTypes = typemap.NewTypeMap() 71 72 func Register[T runtime.Object](reg RegisterType[T]) { 73 typemap.Set[RegisterType[T]](registeredTypes, reg) 74 } 75 76 type RegisterType[T runtime.Object] interface { 77 GetGVK() config.GroupVersionKind 78 GetGVR() schema.GroupVersionResource 79 Object() T 80 }