github.com/SamarSidharth/kpt@v0.0.0-20231122062228-c7d747ae3ace/internal/options/get.go (about)

     1  // Copyright 2022 The kpt Authors
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //      http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package options
    16  
    17  import (
    18  	"fmt"
    19  
    20  	"github.com/spf13/cobra"
    21  	"k8s.io/cli-runtime/pkg/genericclioptions"
    22  	"k8s.io/cli-runtime/pkg/resource"
    23  )
    24  
    25  // Get holds options for a list/get operation
    26  type Get struct {
    27  	*genericclioptions.ConfigFlags
    28  	AllNamespaces bool
    29  }
    30  
    31  func (o *Get) AddFlags(cmd *cobra.Command) {
    32  	cmd.Flags().BoolVarP(&o.AllNamespaces, "all-namespaces", "A", o.AllNamespaces,
    33  		"If present, list the requested object(s) across all namespaces. Namespace in current context is ignored even if specified with --namespace.")
    34  }
    35  
    36  func (o *Get) ResourceBuilder() (*resource.Builder, error) {
    37  	if *o.ConfigFlags.Namespace == "" {
    38  		// Get the namespace from kubeconfig
    39  		namespace, _, err := o.ConfigFlags.ToRawKubeConfigLoader().Namespace()
    40  		if err != nil {
    41  			return nil, fmt.Errorf("error getting namespace: %w", err)
    42  		}
    43  		o.ConfigFlags.Namespace = &namespace
    44  	}
    45  
    46  	b := resource.NewBuilder(o.ConfigFlags).
    47  		NamespaceParam(*o.ConfigFlags.Namespace).AllNamespaces(o.AllNamespaces)
    48  	return b, nil
    49  }