github.com/cilium/cilium@v1.16.2/pkg/k8s/resource/key.go (about) 1 // SPDX-License-Identifier: Apache-2.0 2 // Copyright Authors of Cilium 3 4 package resource 5 6 import ( 7 "k8s.io/apimachinery/pkg/api/meta" 8 "k8s.io/client-go/tools/cache" 9 ) 10 11 // Key of an K8s object, e.g. name and optional namespace. 12 type Key struct { 13 // Name is the name of the object 14 Name string 15 16 // Namespace is the namespace, or empty if object is not namespaced. 17 Namespace string 18 } 19 20 func (k Key) String() string { 21 if len(k.Namespace) > 0 { 22 return k.Namespace + "/" + k.Name 23 } 24 return k.Name 25 } 26 27 func NewKey(obj any) Key { 28 if d, ok := obj.(cache.DeletedFinalStateUnknown); ok { 29 namespace, name, _ := cache.SplitMetaNamespaceKey(d.Key) 30 return Key{name, namespace} 31 } 32 33 meta, err := meta.Accessor(obj) 34 if err != nil { 35 return Key{} 36 } 37 if len(meta.GetNamespace()) > 0 { 38 return Key{meta.GetName(), meta.GetNamespace()} 39 } 40 return Key{meta.GetName(), ""} 41 }