diff --git a/cmd/kubectx/current.go b/cmd/kubectx/current.go new file mode 100644 index 0000000..6a9aa2d --- /dev/null +++ b/cmd/kubectx/current.go @@ -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 +} diff --git a/cmd/kubectx/flags.go b/cmd/kubectx/flags.go index 4511a16..9f0cbed 100644 --- a/cmd/kubectx/flags.go +++ b/cmd/kubectx/flags.go @@ -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} diff --git a/cmd/kubectx/flags_test.go b/cmd/kubectx/flags_test.go index 45a05b4..06c7b29 100644 --- a/cmd/kubectx/flags_test.go +++ b/cmd/kubectx/flags_test.go @@ -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"}}, diff --git a/cmd/kubectx/list.go b/cmd/kubectx/list.go index a8b949d..bdaf604 100644 --- a/cmd/kubectx/list.go +++ b/cmd/kubectx/list.go @@ -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 { diff --git a/cmd/kubectx/main.go b/cmd/kubectx/main.go index bd89c04..7340132 100644 --- a/cmd/kubectx/main.go +++ b/cmd/kubectx/main.go @@ -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