github.com/Racer159/helm-experiment@v0.0.0-20230822001441-1eb31183f614/src/env.go (about)

     1  /*
     2  Copyright The Helm 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  	"fmt"
    21  	"io"
    22  	"sort"
    23  
    24  	"github.com/spf13/cobra"
    25  
    26  	"helm.sh/helm/v3/cmd/helm/require"
    27  )
    28  
    29  var envHelp = `
    30  Env prints out all the environment information in use by Helm.
    31  `
    32  
    33  func newEnvCmd(out io.Writer) *cobra.Command {
    34  	cmd := &cobra.Command{
    35  		Use:   "env",
    36  		Short: "helm client environment information",
    37  		Long:  envHelp,
    38  		Args:  require.MaximumNArgs(1),
    39  		ValidArgsFunction: func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
    40  			if len(args) == 0 {
    41  				keys := getSortedEnvVarKeys()
    42  				return keys, cobra.ShellCompDirectiveNoFileComp
    43  			}
    44  
    45  			return nil, cobra.ShellCompDirectiveNoFileComp
    46  		},
    47  		Run: func(cmd *cobra.Command, args []string) {
    48  			envVars := settings.EnvVars()
    49  
    50  			if len(args) == 0 {
    51  				// Sort the variables by alphabetical order.
    52  				// This allows for a constant output across calls to 'helm env'.
    53  				keys := getSortedEnvVarKeys()
    54  
    55  				for _, k := range keys {
    56  					fmt.Fprintf(out, "%s=\"%s\"\n", k, envVars[k])
    57  				}
    58  			} else {
    59  				fmt.Fprintf(out, "%s\n", envVars[args[0]])
    60  			}
    61  		},
    62  	}
    63  	return cmd
    64  }
    65  
    66  func getSortedEnvVarKeys() []string {
    67  	envVars := settings.EnvVars()
    68  
    69  	var keys []string
    70  	for k := range envVars {
    71  		keys = append(keys, k)
    72  	}
    73  	sort.Strings(keys)
    74  
    75  	return keys
    76  }