Skip to content

Commit

Permalink
Respect existing behavior
Browse files Browse the repository at this point in the history
and set k9s's active ns if no ns specified in the context
  • Loading branch information
mikutas committed Aug 29, 2023
1 parent f6b6071 commit 468bc2b
Show file tree
Hide file tree
Showing 4 changed files with 30 additions and 3 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
6 changes: 5 additions & 1 deletion internal/view/app.go
Original file line number Diff line number Diff line change
Expand Up @@ -403,7 +403,11 @@ func (a *App) switchContext(name string) error {
a.Halt()
defer a.Resume()
{
ns := a.Config.ActiveNamespace()
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)

if e := a.command.Reset(true); e != nil {
Expand Down

0 comments on commit 468bc2b

Please sign in to comment.