github.com/oam-dev/kubevela@v1.9.11/pkg/cmd/utils.go (about)

     1  /*
     2  Copyright 2022 The KubeVela 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 cmd
    18  
    19  import (
    20  	"github.com/spf13/cobra"
    21  
    22  	"github.com/oam-dev/kubevela/apis/types"
    23  	cmdutil "github.com/oam-dev/kubevela/pkg/cmd/util"
    24  	"github.com/oam-dev/kubevela/pkg/utils/env"
    25  )
    26  
    27  // GetNamespace get namespace from command flags and env
    28  func GetNamespace(_ Factory, cmd *cobra.Command) string {
    29  	namespace, err := cmd.Flags().GetString(flagNamespace)
    30  	cmdutil.CheckErr(err)
    31  	if namespace != "" {
    32  		return namespace
    33  	}
    34  	// find namespace from env
    35  	envName, err := cmd.Flags().GetString(flagEnv)
    36  	if err != nil {
    37  		// ignore env if the command does not use the flag
    38  		return ""
    39  	}
    40  	var envMeta *types.EnvMeta
    41  	if envName != "" {
    42  		envMeta, err = env.GetEnvByName(envName)
    43  	} else {
    44  		envMeta, err = env.GetCurrentEnv()
    45  	}
    46  	if err != nil {
    47  		return ""
    48  	}
    49  	return envMeta.Namespace
    50  }
    51  
    52  // GetCluster get cluster from command flags
    53  func GetCluster(cmd *cobra.Command) string {
    54  	cluster, err := cmd.Flags().GetString(flagCluster)
    55  	cmdutil.CheckErr(err)
    56  	if cluster == "" {
    57  		return types.ClusterLocalName
    58  	}
    59  	return cluster
    60  }
    61  
    62  // GetClusters get cluster from command flags
    63  func GetClusters(cmd *cobra.Command) []string {
    64  	clusters, err := cmd.Flags().GetStringSlice(flagCluster)
    65  	cmdutil.CheckErr(err)
    66  	if len(clusters) == 0 {
    67  		return []string{types.ClusterLocalName}
    68  	}
    69  	return clusters
    70  }