Skip to content

Commit

Permalink
Use current k9s NS if new context has no default NS (#2197)
Browse files Browse the repository at this point in the history
* Fix resetting active namespace when switching ctx

* Respect existing behavior

and set k9s's active ns if no ns specified in the context
  • Loading branch information
mikutas authored Nov 12, 2023
1 parent 21f1987 commit 23e600b
Show file tree
Hide file tree
Showing 4 changed files with 26 additions and 2 deletions.
20 changes: 20 additions & 0 deletions internal/client/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down Expand Up @@ -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
}

Expand Down
6 changes: 4 additions & 2 deletions internal/client/config_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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},
Expand All @@ -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)
})
}
Expand Down
1 change: 1 addition & 0 deletions internal/dao/testdata/config
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ contexts:
name: fred
- context:
cluster: blee
namespace: zorg
user: blee
name: blee
- context:
Expand Down
1 change: 1 addition & 0 deletions internal/view/app.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)

Expand Down

0 comments on commit 23e600b

Please sign in to comment.