...

Source file src/github.com/cert-manager/issuer-lib/internal/kubeutil/util.go

Documentation: github.com/cert-manager/issuer-lib/internal/kubeutil

     1  /*
     2  Copyright 2023 The cert-manager 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      http://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 kubeutil
    18  
    19  import (
    20  	"fmt"
    21  
    22  	"k8s.io/apimachinery/pkg/runtime"
    23  	"k8s.io/apimachinery/pkg/runtime/schema"
    24  	"sigs.k8s.io/controller-runtime/pkg/client"
    25  )
    26  
    27  // setGroupVersionKind populates the Group and Kind fields of obj using the
    28  // scheme type registry.
    29  // Inspired by https://github.com/kubernetes-sigs/controller-runtime/issues/1735#issuecomment-984763173
    30  func SetGroupVersionKind(scheme *runtime.Scheme, obj client.Object) error {
    31  	gvks, unversioned, err := scheme.ObjectKinds(obj)
    32  	if err != nil {
    33  		return err
    34  	}
    35  	if unversioned {
    36  		return fmt.Errorf("ObjectKinds unexpectedly returned unversioned: %#v", unversioned)
    37  	}
    38  	if len(gvks) != 1 {
    39  		return fmt.Errorf("ObjectKinds unexpectedly returned zero or multiple gvks: %#v", gvks)
    40  	}
    41  	obj.GetObjectKind().SetGroupVersionKind(gvks[0])
    42  	return nil
    43  }
    44  
    45  func NewListObject(scheme *runtime.Scheme, gvk schema.GroupVersionKind) (client.ObjectList, error) {
    46  	list, err := scheme.New(gvk.GroupVersion().WithKind(gvk.Kind + "List"))
    47  	if err != nil {
    48  		return nil, err
    49  	}
    50  
    51  	listObj, ok := list.(client.ObjectList)
    52  	if !ok {
    53  		return nil, fmt.Errorf("list object of %v does not implement client.ObjectList", gvk)
    54  	}
    55  
    56  	return listObj, nil
    57  }
    58  

View as plain text