Merge pull request #6400 from adamreese/ref/envvars

ref(pkg/cli): refactor environment variable setup
pull/6500/head
Adam Reese 5 years ago committed by GitHub
commit fef60966f6
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

@ -19,7 +19,6 @@ package main
import ( import (
"fmt" "fmt"
"io" "io"
"sort"
"helm.sh/helm/pkg/cli" "helm.sh/helm/pkg/cli"
@ -56,16 +55,8 @@ type envOptions struct {
} }
func (o *envOptions) run(out io.Writer) error { func (o *envOptions) run(out io.Writer) error {
for k, v := range o.settings.EnvVars() {
// Sorting keys to display in alphabetical order fmt.Printf("%s=\"%s\" \n", k, v)
var keys []string
for k := range o.settings.EnvironmentVariables {
keys = append(keys, k)
}
sort.Strings(keys)
for _, k := range keys {
fmt.Printf("%s=\"%s\" \n", k, o.settings.EnvironmentVariables[k])
} }
return nil return nil
} }

@ -89,8 +89,13 @@ func loadPlugins(baseCmd *cobra.Command, out io.Writer) {
return errors.Errorf("plugin %q exited with error", md.Name) return errors.Errorf("plugin %q exited with error", md.Name)
} }
env := os.Environ()
for k, v := range settings.EnvVars() {
env = append(env, fmt.Sprintf("%s=%s", k, v))
}
prog := exec.Command(main, argv...) prog := exec.Command(main, argv...)
prog.Env = os.Environ() prog.Env = env
prog.Stdin = os.Stdin prog.Stdin = os.Stdin
prog.Stdout = out prog.Stdout = out
prog.Stderr = os.Stderr prog.Stderr = os.Stderr

@ -216,9 +216,6 @@ func newRootCmd(actionConfig *action.Configuration, out io.Writer, args []string
flags.ParseErrorsWhitelist.UnknownFlags = true flags.ParseErrorsWhitelist.UnknownFlags = true
flags.Parse(args) flags.Parse(args)
// set defaults from environment
settings.Init(flags)
// Add subcommands // Add subcommands
cmd.AddCommand( cmd.AddCommand(
// chart commands // chart commands

@ -1,7 +1,7 @@
#!/bin/sh #!/bin/sh
echo $HELM_PLUGIN_NAME echo $HELM_PLUGIN_NAME
echo $HELM_PLUGIN_DIR echo $HELM_PLUGIN_DIR
echo $HELM_PLUGIN echo $HELM_PLUGINS
echo $HELM_REPOSITORY_CONFIG echo $HELM_REPOSITORY_CONFIG
echo $HELM_REPOSITORY_CACHE echo $HELM_REPOSITORY_CACHE
echo $HELM_BIN echo $HELM_BIN

@ -25,6 +25,7 @@ package cli
import ( import (
"fmt" "fmt"
"os" "os"
"strconv"
"github.com/spf13/pflag" "github.com/spf13/pflag"
@ -50,72 +51,45 @@ type EnvSettings struct {
RepositoryCache string RepositoryCache string
// PluginsDirectory is the path to the plugins directory. // PluginsDirectory is the path to the plugins directory.
PluginsDirectory string PluginsDirectory string
// Environment Variables Store.
EnvironmentVariables map[string]string
} }
func New() *EnvSettings { func New() *EnvSettings {
envSettings := EnvSettings{ env := EnvSettings{
PluginsDirectory: helmpath.DataPath("plugins"), Namespace: os.Getenv("HELM_NAMESPACE"),
RegistryConfig: helmpath.ConfigPath("registry.json"), PluginsDirectory: envOr("HELM_PLUGINS", helmpath.DataPath("plugins")),
RepositoryConfig: helmpath.ConfigPath("repositories.yaml"), RegistryConfig: envOr("HELM_REGISTRY_CONFIG", helmpath.ConfigPath("registry.json")),
RepositoryCache: helmpath.CachePath("repository"), RepositoryConfig: envOr("HELM_REPOSITORY_CONFIG", helmpath.ConfigPath("repositories.yaml")),
EnvironmentVariables: make(map[string]string), RepositoryCache: envOr("HELM_REPOSITORY_CACHE", helmpath.CachePath("repository")),
} }
envSettings.setHelmEnvVars() env.Debug, _ = strconv.ParseBool(os.Getenv("HELM_DEBUG"))
return &envSettings return &env
} }
// AddFlags binds flags to the given flagset. // AddFlags binds flags to the given flagset.
func (s *EnvSettings) AddFlags(fs *pflag.FlagSet) { func (s *EnvSettings) AddFlags(fs *pflag.FlagSet) {
fs.StringVarP(&s.Namespace, "namespace", "n", "", "namespace scope for this request") fs.StringVarP(&s.Namespace, "namespace", "n", s.Namespace, "namespace scope for this request")
fs.StringVar(&s.KubeConfig, "kubeconfig", "", "path to the kubeconfig file") fs.StringVar(&s.KubeConfig, "kubeconfig", "", "path to the kubeconfig file")
fs.StringVar(&s.KubeContext, "kube-context", "", "name of the kubeconfig context to use") fs.StringVar(&s.KubeContext, "kube-context", "", "name of the kubeconfig context to use")
fs.BoolVar(&s.Debug, "debug", false, "enable verbose output") fs.BoolVar(&s.Debug, "debug", s.Debug, "enable verbose output")
fs.StringVar(&s.RegistryConfig, "registry-config", s.RegistryConfig, "path to the registry config file") fs.StringVar(&s.RegistryConfig, "registry-config", s.RegistryConfig, "path to the registry config file")
fs.StringVar(&s.RepositoryConfig, "repository-config", s.RepositoryConfig, "path to the file containing repository names and URLs") fs.StringVar(&s.RepositoryConfig, "repository-config", s.RepositoryConfig, "path to the file containing repository names and URLs")
fs.StringVar(&s.RepositoryCache, "repository-cache", s.RepositoryCache, "path to the file containing cached repository indexes") fs.StringVar(&s.RepositoryCache, "repository-cache", s.RepositoryCache, "path to the file containing cached repository indexes")
} }
// envMap maps flag names to envvars func envOr(name, def string) string {
var envMap = map[string]string{ if v, ok := os.LookupEnv(name); ok {
"debug": "HELM_DEBUG", return v
"namespace": "HELM_NAMESPACE",
"registry-config": "HELM_REGISTRY_CONFIG",
"repository-config": "HELM_REPOSITORY_CONFIG",
}
func setFlagFromEnv(name, envar string, fs *pflag.FlagSet) {
if fs.Changed(name) {
return
}
if v, ok := os.LookupEnv(envar); ok {
fs.Set(name, v)
} }
return def
} }
func (s *EnvSettings) setHelmEnvVars() { func (s *EnvSettings) EnvVars() map[string]string {
for key, val := range map[string]string{ return map[string]string{
"HELM_HOME": helmpath.DataPath(), "HELM_BIN": os.Args[0],
"HELM_PATH_STARTER": helmpath.DataPath("starters"),
"HELM_DEBUG": fmt.Sprint(s.Debug), "HELM_DEBUG": fmt.Sprint(s.Debug),
"HELM_PLUGINS": s.PluginsDirectory,
"HELM_REGISTRY_CONFIG": s.RegistryConfig, "HELM_REGISTRY_CONFIG": s.RegistryConfig,
"HELM_REPOSITORY_CONFIG": s.RepositoryConfig,
"HELM_REPOSITORY_CACHE": s.RepositoryCache, "HELM_REPOSITORY_CACHE": s.RepositoryCache,
"HELM_PLUGIN": s.PluginsDirectory, "HELM_REPOSITORY_CONFIG": s.RepositoryConfig,
} {
if eVal := os.Getenv(key); len(eVal) > 0 {
val = eVal
}
s.EnvironmentVariables[key] = val
}
}
// Init sets values from the environment.
func (s *EnvSettings) Init(fs *pflag.FlagSet) {
for name, envar := range envMap {
setFlagFromEnv(name, envar, fs)
} }
} }

@ -71,12 +71,10 @@ func TestEnvSettings(t *testing.T) {
flags := pflag.NewFlagSet("testing", pflag.ContinueOnError) flags := pflag.NewFlagSet("testing", pflag.ContinueOnError)
settings := &EnvSettings{} settings := New()
settings.AddFlags(flags) settings.AddFlags(flags)
flags.Parse(strings.Split(tt.args, " ")) flags.Parse(strings.Split(tt.args, " "))
settings.Init(flags)
if settings.Debug != tt.debug { if settings.Debug != tt.debug {
t.Errorf("expected debug %t, got %t", tt.debug, settings.Debug) t.Errorf("expected debug %t, got %t", tt.debug, settings.Debug)
} }
@ -94,7 +92,7 @@ func resetEnv() func() {
origEnv := os.Environ() origEnv := os.Environ()
// ensure any local envvars do not hose us // ensure any local envvars do not hose us
for _, e := range envMap { for e := range New().EnvVars() {
os.Unsetenv(e) os.Unsetenv(e)
} }

@ -26,7 +26,6 @@ import (
"sigs.k8s.io/yaml" "sigs.k8s.io/yaml"
"helm.sh/helm/pkg/cli" "helm.sh/helm/pkg/cli"
"helm.sh/helm/pkg/helmpath"
) )
const pluginFileName = "plugin.yaml" const pluginFileName = "plugin.yaml"
@ -217,20 +216,10 @@ func FindPlugins(plugdirs string) ([]*Plugin, error) {
// the plugin subsystem itself needs access to the environment variables // the plugin subsystem itself needs access to the environment variables
// created here. // created here.
func SetupPluginEnv(settings *cli.EnvSettings, name, base string) { func SetupPluginEnv(settings *cli.EnvSettings, name, base string) {
for key, val := range map[string]string{ env := settings.EnvVars()
"HELM_PLUGIN_NAME": name, env["HELM_PLUGIN_NAME"] = name
"HELM_PLUGIN_DIR": base, env["HELM_PLUGIN_DIR"] = base
"HELM_BIN": os.Args[0], for key, val := range env {
"HELM_PLUGIN": settings.PluginsDirectory,
// Set vars that convey common information.
"HELM_REGISTRY_CONFIG": settings.RegistryConfig,
"HELM_REPOSITORY_CONFIG": settings.RepositoryConfig,
"HELM_REPOSITORY_CACHE": settings.RepositoryCache,
"HELM_PATH_STARTER": helmpath.DataPath("starters"),
"HELM_HOME": helmpath.DataPath(), // for backwards compatibility with Helm 2 plugins
"HELM_DEBUG": fmt.Sprint(settings.Debug),
} {
os.Setenv(key, val) os.Setenv(key, val)
} }
} }

Loading…
Cancel
Save