Save last context name in state file

Signed-off-by: Ahmet Alp Balkan <ahmetb@google.com>
This commit is contained in:
Ahmet Alp Balkan 2020-04-10 14:27:52 -07:00
parent 7a40a5ed07
commit 74a30a60e0
No known key found for this signature in database
GPG Key ID: 441833503E604E2C
3 changed files with 27 additions and 10 deletions

View File

@ -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) {

View File

@ -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
}