github.com/tmsmr/k4wd@v0.9.1-0.20240220054329-da5057436901/internal/pkg/kubeclient/kubeclient.go (about)

     1  package kubeclient
     2  
     3  import (
     4  	"k8s.io/client-go/kubernetes"
     5  	"k8s.io/client-go/rest"
     6  	"k8s.io/client-go/tools/clientcmd"
     7  	"k8s.io/client-go/tools/clientcmd/api"
     8  	"os"
     9  	"path/filepath"
    10  )
    11  
    12  type Kubeclient struct {
    13  	Kubeconfig  string
    14  	Kubecontext string
    15  	APIConfig   *api.Config
    16  }
    17  
    18  type ClientOption func(ff *Kubeclient)
    19  
    20  func WithKubeconfig(path string) ClientOption {
    21  	return func(kc *Kubeclient) {
    22  		kc.Kubeconfig = path
    23  	}
    24  }
    25  
    26  func New(opts ...ClientOption) (*Kubeclient, error) {
    27  	kc := &Kubeclient{}
    28  	for _, opt := range opts {
    29  		opt(kc)
    30  	}
    31  	if kc.Kubeconfig == "" {
    32  		home := os.Getenv("HOME")
    33  		if home == "" {
    34  			home = os.Getenv("USERPROFILE")
    35  		}
    36  		kc.Kubeconfig = filepath.Join(home, ".kube", "config")
    37  	}
    38  	config, err := clientcmd.LoadFromFile(kc.Kubeconfig)
    39  	if err != nil {
    40  		return nil, err
    41  	}
    42  	kc.APIConfig = config
    43  	return kc, nil
    44  }
    45  
    46  func (kc Kubeclient) RESTConfig(context *string) (*rest.Config, error) {
    47  	co := clientcmd.ConfigOverrides{}
    48  	if context != nil {
    49  		co.CurrentContext = *context
    50  	}
    51  	clientConfig := clientcmd.NewDefaultClientConfig(*kc.APIConfig, &co)
    52  	restConfig, err := clientConfig.ClientConfig()
    53  	if err != nil {
    54  		return nil, err
    55  	}
    56  	return restConfig, nil
    57  }
    58  
    59  func (kc Kubeclient) Clientset(context *string, config *rest.Config) (*kubernetes.Clientset, error) {
    60  	var err error
    61  	if config == nil {
    62  		config, err = kc.RESTConfig(context)
    63  		if err != nil {
    64  			return nil, err
    65  		}
    66  	}
    67  	clientset, err := kubernetes.NewForConfig(config)
    68  	if err != nil {
    69  		return nil, err
    70  	}
    71  	return clientset, nil
    72  }