mirror of
https://github.com/ahmetb/kubectx.git
synced 2025-06-23 05:59:00 +00:00
Save last context name in state file
Signed-off-by: Ahmet Alp Balkan <ahmetb@google.com>
This commit is contained in:
parent
7a40a5ed07
commit
74a30a60e0
@ -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) {
|
||||
|
@ -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
|
||||
}
|
||||
|
||||
|
Loading…
Reference in New Issue
Block a user