Use current k9s NS if new context has no default NS (#2197)

* Fix resetting active namespace when switching ctx

* Respect existing behavior

and set k9s's active ns if no ns specified in the context
mine
Takumi Sue 2023-11-13 02:23:46 +09:00 committed by GitHub
parent 21f1987fba
commit 23e600bef5
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
4 changed files with 26 additions and 2 deletions

View File

@ -94,6 +94,19 @@ func (c *Config) CurrentContextName() (string, error) {
return cfg.CurrentContext, nil
}
func (c *Config) CurrentContextNamespace() (string, error) {
name, err := c.CurrentContextName()
if err != nil {
return "", err
}
context, err := c.GetContext(name)
if err != nil {
return "", err
}
return context.Namespace, nil
}
// GetContext fetch a given context or error if it does not exists.
func (c *Config) GetContext(n string) (*clientcmdapi.Context, error) {
cfg, err := c.RawConfig()
@ -283,6 +296,13 @@ func (c *Config) CurrentUserName() (string, error) {
func (c *Config) CurrentNamespaceName() (string, error) {
ns, _, err := c.clientConfig().Namespace()
if ns == "default" {
ns, err = c.CurrentContextNamespace()
if ns == "" && err == nil {
return "", errors.New("No namespace specified in context")
}
}
return ns, err
}

View File

@ -111,7 +111,7 @@ func TestConfigCurrentNamespace(t *testing.T) {
}{
"default": {
flags: &genericclioptions.ConfigFlags{KubeConfig: &kubeConfig},
namespace: "default",
namespace: "",
},
"withContext": {
flags: &genericclioptions.ConfigFlags{KubeConfig: &kubeConfig, Context: &bleeCTX},
@ -128,7 +128,9 @@ func TestConfigCurrentNamespace(t *testing.T) {
t.Run(k, func(t *testing.T) {
cfg := client.NewConfig(u.flags)
ns, err := cfg.CurrentNamespaceName()
assert.Nil(t, err)
if ns != "" {
assert.Nil(t, err)
}
assert.Equal(t, u.namespace, ns)
})
}

View File

@ -21,6 +21,7 @@ contexts:
name: fred
- context:
cluster: blee
namespace: zorg
user: blee
name: blee
- context:

View File

@ -405,6 +405,7 @@ func (a *App) switchContext(name string) error {
ns, err := a.Conn().Config().CurrentNamespaceName()
if err != nil {
log.Warn().Msg("No namespace specified in context. Using K9s config")
ns = a.Config.ActiveNamespace()
}
a.initFactory(ns)