Add support for -c/--current

Signed-off-by: Ahmet Alp Balkan <ahmetb@google.com>
This commit is contained in:
Ahmet Alp Balkan 2020-04-10 14:50:14 -07:00
parent ff6326c122
commit 94e8d3b4c7
No known key found for this signature in database
GPG Key ID: 441833503E604E2C
5 changed files with 48 additions and 2 deletions

27
cmd/kubectx/current.go Normal file
View File

@ -0,0 +1,27 @@
package main
import (
"fmt"
"io"
"github.com/pkg/errors"
)
func printCurrentContext(w io.Writer) error {
cfgPath, err := kubeconfigPath()
if err != nil {
return errors.Wrap(err, "failed to determine kubeconfig path")
}
cfg, err := parseKubeconfig(cfgPath)
if err != nil {
return errors.Wrap(err, "failed to read kubeconfig file")
}
v := cfg.CurrentContext
if v == "" {
return errors.New("current-context is not set")
}
_, err = fmt.Fprintln(w, v)
return err
}

View File

@ -10,6 +10,9 @@ type HelpOp struct{}
// ListOp describes listing contexts.
type ListOp struct{}
// CurrentOp prints the current context
type CurrentOp struct{}
// SwitchOp indicates intention to switch contexts.
type SwitchOp struct {
Target string // '-' for back and forth, or NAME
@ -30,6 +33,9 @@ func parseArgs(argv []string) Op {
if v == "--help" || v == "-h" {
return HelpOp{}
}
if v == "--current" || v == "-c" {
return CurrentOp{}
}
if strings.HasPrefix(v, "-") && v != "-" {
return UnknownOp{argv}

View File

@ -24,6 +24,12 @@ func Test_parseArgs_new(t *testing.T) {
{name: "help long form",
args: []string{"--help"},
want: HelpOp{}},
{name: "current shorthand",
args: []string{"-c"},
want: CurrentOp{}},
{name: "current long form",
args: []string{"--current"},
want: CurrentOp{}},
{name: "switch by name",
args: []string{"foo"},
want: SwitchOp{Target: "foo"}},

View File

@ -31,7 +31,6 @@ func printListContexts(out io.Writer) error {
if err != nil {
return errors.Wrap(err, "failed to read kubeconfig file")
}
_ = cfg
ctxs := make([]string, 0, len(cfg.Contexts))
for _, c := range cfg.Contexts {

View File

@ -17,8 +17,16 @@ func main() {
switch v := op.(type) {
case HelpOp:
printHelp(os.Stdout)
case CurrentOp:
if err := printCurrentContext(os.Stdout); err != nil {
printError(err.Error())
os.Exit(1)
}
case ListOp:
printListContexts(os.Stdout)
if err := printListContexts(os.Stdout); err != nil {
printError(err.Error())
os.Exit(1)
}
case SwitchOp:
var newCtx string
var err error