From adfb5a9d599989aebac54687fbe176a47c50f2d7 Mon Sep 17 00:00:00 2001 From: marcushines <80116818+marcushines@users.noreply.github.com> Date: Thu, 18 Aug 2022 13:42:02 -0700 Subject: [PATCH] Fix handling for KUBECONFIG env var (#192) * Fix handling for KUBECONFIG env var * Address comments --- cmd/root.go | 22 ++++++++++++------- cmd/root_test.go | 57 ++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 71 insertions(+), 8 deletions(-) create mode 100644 cmd/root_test.go diff --git a/cmd/root.go b/cmd/root.go index 74165534..ea97cf8e 100644 --- a/cmd/root.go +++ b/cmd/root.go @@ -31,11 +31,10 @@ import ( ) var ( - defaultKubeCfg = "" - kubecfg string - dryrun bool - timeout time.Duration - logLevel = "info" + kubecfg string + dryrun bool + timeout time.Duration + logLevel = "info" rootCmd = &cobra.Command{ Use: "kne", @@ -62,12 +61,19 @@ func ExecuteContext(ctx context.Context) error { return rootCmd.ExecuteContext(ctx) } -func init() { +func defaultKubeCfg() string { + if v := os.Getenv("KUBECONFIG"); v != "" { + return v + } if home := homedir.HomeDir(); home != "" { - defaultKubeCfg = filepath.Join(home, ".kube", "config") + return filepath.Join(home, ".kube", "config") } + return "" +} + +func init() { rootCmd.SetOut(os.Stdout) - rootCmd.PersistentFlags().StringVar(&kubecfg, "kubecfg", defaultKubeCfg, "kubeconfig file") + rootCmd.PersistentFlags().StringVar(&kubecfg, "kubecfg", defaultKubeCfg(), "kubeconfig file") rootCmd.PersistentFlags().StringVarP(&logLevel, "verbosity", "v", logLevel, "log level") createCmd.Flags().BoolVar(&dryrun, "dryrun", false, "Generate topology but do not push to k8s") createCmd.Flags().DurationVar(&timeout, "timeout", 0, "Timeout for pod status enquiry") diff --git a/cmd/root_test.go b/cmd/root_test.go new file mode 100644 index 00000000..d58de397 --- /dev/null +++ b/cmd/root_test.go @@ -0,0 +1,57 @@ +package cmd + +import ( + "os" + "testing" +) + +func TestGetKubeCfg(t *testing.T) { + tests := []struct { + desc string + setVar func() func() + want string + }{{ + desc: "KUBECONFIG Set", + setVar: func() func() { + orig := os.Getenv("KUBECONFIG") + os.Setenv("KUBECONFIG", "/etc/kube/config") + return func() { + os.Setenv("KUBECONFIG", orig) + } + }, + want: "/etc/kube/config", + }, { + desc: "home dir", + setVar: func() func() { + orig := os.Getenv("HOME") + os.Setenv("HOME", "/fakeuser") + return func() { + os.Setenv("HOME", orig) + } + }, + want: "/fakeuser/.kube/config", + }, { + desc: "unknown", + setVar: func() func() { + origH := os.Getenv("HOME") + os.Setenv("HOME", "") + origK := os.Getenv("KUBECONFIG") + os.Setenv("KUBECONFIG", "") + return func() { + os.Setenv("HOME", origH) + os.Setenv("KUBECONFIG", origK) + } + }, + want: "", + }} + for _, tt := range tests { + t.Run(tt.desc, func(t *testing.T) { + unset := tt.setVar() + defer unset() + got := defaultKubeCfg() + if got != tt.want { + t.Fatalf("getKubeCfg() failed: got %v, want %v", got, tt.want) + } + }) + } +}