From 74a30a60e04ab7d0d78e0c1011a6d058dc9f752b Mon Sep 17 00:00:00 2001 From: Ahmet Alp Balkan Date: Fri, 10 Apr 2020 14:27:52 -0700 Subject: [PATCH] Save last context name in state file Signed-off-by: Ahmet Alp Balkan --- cmd/kubectx/kubeconfig.go | 15 +++++++++++---- cmd/kubectx/main.go | 6 +++--- cmd/kubectx/switch.go | 16 +++++++++++++--- 3 files changed, 27 insertions(+), 10 deletions(-) diff --git a/cmd/kubectx/kubeconfig.go b/cmd/kubectx/kubeconfig.go index dec6a84..e03e8e5 100644 --- a/cmd/kubectx/kubeconfig.go +++ b/cmd/kubectx/kubeconfig.go @@ -19,15 +19,22 @@ func kubeconfigPath() (string, error) { return v, nil } + home := homeDir() + if home == "" { + return "", errors.New("HOME or USERPROFILE environment variable not set") + } + // return default path + return filepath.Join(home, ".kube", "config"), nil +} + +func homeDir() string { + // TODO move tests out of kubeconfigPath to TestHomeDir() home := os.Getenv("HOME") if home == "" { home = os.Getenv("USERPROFILE") // windows } - if home == "" { - return "", errors.New("HOME or USERPROFILE environment variable not set") - } - return filepath.Join(home, ".kube", "config"), nil + return home } func parseKubeconfig(path string) (kubeconfig, error) { diff --git a/cmd/kubectx/main.go b/cmd/kubectx/main.go index 4c5585f..f21e9f4 100644 --- a/cmd/kubectx/main.go +++ b/cmd/kubectx/main.go @@ -21,9 +21,9 @@ func main() { printListContexts(os.Stdout) case SwitchOp: if v.Target == "-" { - // TODO implement swap - panic("not implemented") - } + // TODO implement swap + panic("not implemented") + } newCtx, err := switchContext(v.Target) if err != nil { printError("faield to switch context: %v", err) diff --git a/cmd/kubectx/switch.go b/cmd/kubectx/switch.go index 4f8c020..8093d14 100644 --- a/cmd/kubectx/switch.go +++ b/cmd/kubectx/switch.go @@ -1,7 +1,6 @@ package main import ( - "fmt" "io" "os" @@ -11,6 +10,11 @@ import ( // switchContext switches to specified context name. func switchContext(name string) (string, error) { + stateFile, err := kubectxFilePath() + if err != nil { + return "", errors.Wrap(err, "failed to determine state file") + } + cfgPath, err := kubeconfigPath() if err != nil { return "", errors.Wrap(err, "cannot determine kubeconfig path") @@ -26,8 +30,7 @@ func switchContext(name string) (string, error) { return "", errors.Wrap(err, "yaml parse error") } - cur := getCurrentContext(kc) - fmt.Printf("current-context=%s\n", cur) + prev := getCurrentContext(kc) if err := modifyCurrentContext(kc, name); err != nil { return "", err @@ -44,6 +47,13 @@ func switchContext(name string) (string, error) { if err := saveKubeconfigRaw(f, kc); err != nil { return "", errors.Wrap(err, "failed to save kubeconfig") } + + if prev != name { + if err := writeLastContext(stateFile, prev); err != nil { + return "", errors.Wrap(err, "failed to save previous context name") + } + } + return name, nil }