From d60a25b2db52d7e180b0962e23cc06e71f36fb29 Mon Sep 17 00:00:00 2001 From: Mike Spreitzer Date: Fri, 26 Jan 2024 13:28:06 -0500 Subject: [PATCH] Add DeletionHandlingObjectToName Signed-off-by: Mike Spreitzer --- .../client-go/tools/cache/controller.go | 10 +++++++ .../client-go/tools/cache/controller_test.go | 28 +++++++++++++++++++ 2 files changed, 38 insertions(+) diff --git a/staging/src/k8s.io/client-go/tools/cache/controller.go b/staging/src/k8s.io/client-go/tools/cache/controller.go index 8a1104bde80..ee19a5af95c 100644 --- a/staging/src/k8s.io/client-go/tools/cache/controller.go +++ b/staging/src/k8s.io/client-go/tools/cache/controller.go @@ -336,6 +336,16 @@ func DeletionHandlingMetaNamespaceKeyFunc(obj interface{}) (string, error) { return MetaNamespaceKeyFunc(obj) } +// DeletionHandlingObjectToName checks for +// DeletedFinalStateUnknown objects before calling +// ObjectToName. +func DeletionHandlingObjectToName(obj interface{}) (ObjectName, error) { + if d, ok := obj.(DeletedFinalStateUnknown); ok { + return ParseObjectName(d.Key) + } + return ObjectToName(obj) +} + // NewInformer returns a Store and a controller for populating the store // while also providing event notifications. You should only used the returned // Store for Get/List operations; Add/Modify/Deletes will cause the event diff --git a/staging/src/k8s.io/client-go/tools/cache/controller_test.go b/staging/src/k8s.io/client-go/tools/cache/controller_test.go index 8dff7679c9d..4058581154f 100644 --- a/staging/src/k8s.io/client-go/tools/cache/controller_test.go +++ b/staging/src/k8s.io/client-go/tools/cache/controller_test.go @@ -574,3 +574,31 @@ func TestTransformingInformer(t *testing.T) { close(stopCh) } + +func TestDeletionHandlingObjectToName(t *testing.T) { + cm := &v1.ConfigMap{ + ObjectMeta: metav1.ObjectMeta{ + Name: "testname", + Namespace: "testnamespace", + }, + } + stringKey, err := MetaNamespaceKeyFunc(cm) + if err != nil { + t.Error(err) + } + deleted := DeletedFinalStateUnknown{ + Key: stringKey, + Obj: cm, + } + expected, err := ObjectToName(cm) + if err != nil { + t.Error(err) + } + actual, err := DeletionHandlingObjectToName(deleted) + if err != nil { + t.Error(err) + } + if expected != actual { + t.Errorf("Expected %#v, got %#v", expected, actual) + } +}