Skip to content

Commit

Permalink
Fix handling for KUBECONFIG env var (#192)
Browse files Browse the repository at this point in the history
* Fix handling for KUBECONFIG env var

* Address comments
  • Loading branch information
marcushines authored Aug 18, 2022
1 parent cbd1e77 commit adfb5a9
Show file tree
Hide file tree
Showing 2 changed files with 71 additions and 8 deletions.
22 changes: 14 additions & 8 deletions cmd/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand All @@ -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")
Expand Down
57 changes: 57 additions & 0 deletions cmd/root_test.go
Original file line number Diff line number Diff line change
@@ -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)
}
})
}
}

0 comments on commit adfb5a9

Please sign in to comment.