@@ -19,6 +19,7 @@ package client
19
19
import (
20
20
"context"
21
21
"fmt"
22
+ "strings"
22
23
23
24
"k8s.io/apimachinery/pkg/api/meta"
24
25
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
@@ -159,7 +160,6 @@ type client struct {
159
160
}
160
161
161
162
// resetGroupVersionKind is a helper function to restore and preserve GroupVersionKind on an object.
162
- // TODO(vincepri): Remove this function and its calls once controller-runtime dependencies are upgraded to 1.16?
163
163
func (c * client ) resetGroupVersionKind (obj runtime.Object , gvk schema.GroupVersionKind ) {
164
164
if gvk != schema .EmptyObjectKind .GroupVersionKind () {
165
165
if v , ok := obj .(schema.ObjectKind ); ok {
@@ -246,6 +246,8 @@ func (c *client) Get(ctx context.Context, key ObjectKey, obj Object) error {
246
246
case * unstructured.Unstructured :
247
247
return c .unstructuredClient .Get (ctx , key , obj )
248
248
case * metav1.PartialObjectMetadata :
249
+ // Metadata only object should always preserve the GVK coming in from the caller.
250
+ defer c .resetGroupVersionKind (obj , obj .GetObjectKind ().GroupVersionKind ())
249
251
return c .metadataClient .Get (ctx , key , obj )
250
252
default :
251
253
return c .typedClient .Get (ctx , key , obj )
@@ -254,11 +256,33 @@ func (c *client) Get(ctx context.Context, key ObjectKey, obj Object) error {
254
256
255
257
// List implements client.Client
256
258
func (c * client ) List (ctx context.Context , obj ObjectList , opts ... ListOption ) error {
257
- switch obj .(type ) {
259
+ switch x := obj .(type ) {
258
260
case * unstructured.UnstructuredList :
259
261
return c .unstructuredClient .List (ctx , obj , opts ... )
260
262
case * metav1.PartialObjectMetadataList :
261
- return c .metadataClient .List (ctx , obj , opts ... )
263
+ // Metadata only object should always preserve the GVK.
264
+ gvk := obj .GetObjectKind ().GroupVersionKind ()
265
+ defer c .resetGroupVersionKind (obj , gvk )
266
+
267
+ // Call the list client.
268
+ if err := c .metadataClient .List (ctx , obj , opts ... ); err != nil {
269
+ return err
270
+ }
271
+
272
+ // Restore the GVK for each item in the list.
273
+ itemGVK := schema.GroupVersionKind {
274
+ Group : gvk .Group ,
275
+ Version : gvk .Version ,
276
+ // TODO: this is producing unsafe guesses that don't actually work,
277
+ // but it matches ~99% of the cases out there.
278
+ Kind : strings .TrimSuffix (gvk .Kind , "List" ),
279
+ }
280
+ for i := range x .Items {
281
+ item := & x .Items [i ]
282
+ item .SetGroupVersionKind (itemGVK )
283
+ }
284
+
285
+ return nil
262
286
default :
263
287
return c .typedClient .List (ctx , obj , opts ... )
264
288
}
0 commit comments