diff --git a/cmd/kubectx/fzf.go b/cmd/kubectx/fzf.go index 38fb5b0d..986608f5 100644 --- a/cmd/kubectx/fzf.go +++ b/cmd/kubectx/fzf.go @@ -23,6 +23,7 @@ type InteractiveSwitchOp struct { func (op InteractiveSwitchOp) Run(_, stderr io.Writer) error { // parse kubeconfig just to see if it can be loaded kc := new(kubeconfig.Kubeconfig).WithLoader(kubeconfig.DefaultLoader) + if err := kc.Parse(); err != nil { if cmdutil.IsNotFoundErr(err) { printer.Warning(stderr, "kubeconfig file not found") @@ -30,6 +31,12 @@ func (op InteractiveSwitchOp) Run(_, stderr io.Writer) error { } return errors.Wrap(err, "kubeconfig error") } + + ctxs := kc.ContextNames() + if ctxs == nil { + err := printer.Warning(stderr, "No kubectl context found") + return errors.Wrap(err, "kubeconfig error") + } kc.Close() cmd := exec.Command("fzf", "--ansi", "--no-preview") diff --git a/cmd/kubectx/list.go b/cmd/kubectx/list.go index 783fd736..e097e49a 100644 --- a/cmd/kubectx/list.go +++ b/cmd/kubectx/list.go @@ -27,6 +27,10 @@ func (_ ListOp) Run(stdout, stderr io.Writer) error { } ctxs := kc.ContextNames() + if ctxs == nil { + err := printer.Warning(stderr, "No kubectl context found") + return errors.Wrap(err, "kubeconfig error") + } natsort.Sort(ctxs) cur := kc.GetCurrentContext() diff --git a/test/kubectx.bats b/test/kubectx.bats index bacb82a6..c0a8308b 100644 --- a/test/kubectx.bats +++ b/test/kubectx.bats @@ -214,7 +214,7 @@ load common run ${COMMAND} echo "$output" [ "$status" -eq 0 ] - [[ "$output" = "" ]] + [[ "$output" = "warning: No kubectl context found" ]] } @test "delete several contexts including a non existent one" { @@ -242,3 +242,11 @@ load common run ${COMMAND} -c [ "$status" -ne 0 ] } + +@test "display msg on empty context" { + use_config config3 + run ${COMMAND} + echo "$output" + [ "$status" -eq 0 ] + [[ "$output" = "warning: No kubectl context found" ]] +} diff --git a/test/testdata/config3 b/test/testdata/config3 new file mode 100644 index 00000000..232acc31 --- /dev/null +++ b/test/testdata/config3 @@ -0,0 +1,15 @@ +# config with no context + +apiVersion: v1 +clusters: +- cluster: + server: "" + name: cluster1 +contexts: +- context: +current-context: "" +kind: Config +preferences: {} +users: +- name: user1 + user: {}