Fix bug about where cur ns was stored in yaml

Signed-off-by: Ahmet Alp Balkan <ahmetb@google.com>
This commit is contained in:
Ahmet Alp Balkan 2020-04-18 16:17:47 -07:00
parent 2915103e3d
commit fc2e1c6b08
No known key found for this signature in database
GPG Key ID: 441833503E604E2C
4 changed files with 30 additions and 9 deletions

View File

@ -11,7 +11,11 @@ func (k *Kubeconfig) NamespaceOfContext(contextName string) (string, error) {
if err != nil {
return "", err
}
ns := valueOf(ctx, "namespace")
ctxBody := valueOf(ctx, "context")
if ctxBody == nil {
return defaultNamespace, nil
}
ns := valueOf(ctxBody, "namespace")
if ns == nil || ns.Value == "" {
return defaultNamespace, nil
}
@ -19,11 +23,21 @@ func (k *Kubeconfig) NamespaceOfContext(contextName string) (string, error) {
}
func (k *Kubeconfig) SetNamespace(ctxName string, ns string) error {
ctx, err := k.contextNode(ctxName)
ctxNode, err := k.contextNode(ctxName)
if err != nil {
return err
}
nsNode := valueOf(ctx, "namespace")
var ctxBodyNodeWasEmpty bool // actual namespace value is in contexts[index].context.namespace, but .context might not exist
ctxBodyNode := valueOf(ctxNode, "context")
if ctxBodyNode == nil {
ctxBodyNodeWasEmpty = true
ctxBodyNode = &yaml.Node{
Kind: yaml.MappingNode,
}
}
nsNode := valueOf(ctxBodyNode, "namespace")
if nsNode != nil {
nsNode.Value = ns
return nil
@ -37,6 +51,13 @@ func (k *Kubeconfig) SetNamespace(ctxName string, ns string) error {
Kind: yaml.ScalarNode,
Value: ns,
Tag: "!!str"}
ctx.Content = append(ctx.Content, keyNode, valueNode)
ctxBodyNode.Content = append(ctxBodyNode.Content, keyNode, valueNode)
if ctxBodyNodeWasEmpty {
ctxNode.Content = append(ctxNode.Content, &yaml.Node{
Kind: yaml.ScalarNode,
Value: "context",
Tag: "!!str",
}, ctxBodyNode)
}
return nil
}

View File

@ -8,12 +8,14 @@ import (
)
type Context struct {
Name string `yaml:"name,omitempty"`
Namespace string `yaml:"namespace,omitempty"`
Name string `yaml:"name,omitempty"`
Context struct {
Namespace string `yaml:"namespace,omitempty"`
} `yaml:"context,omitempty"`
}
func Ctx(name string) *Context { return &Context{Name: name} }
func (c *Context) Ns(ns string) *Context { c.Namespace = ns; return c }
func (c *Context) Ns(ns string) *Context { c.Context.Namespace = ns; return c }
type Kubeconfig map[string]interface{}

View File

@ -1 +0,0 @@
package testutil

View File

@ -21,7 +21,6 @@ load common
run ${COMMAND}
echo "$output"
[[ "$status" -eq 1 ]]
[[ "$output" = *"current-context is not set"* ]]
}
@test "list namespaces" {