From 840bc0667e945710b5ea12c119553de4552370a7 Mon Sep 17 00:00:00 2001 From: Scott Nemes Date: Thu, 16 Nov 2023 06:11:34 -0800 Subject: [PATCH] =?UTF-8?q?fix:=20updates=20how=20the=20context=20name=20i?= =?UTF-8?q?s=20chosen=20when=20adding=20new=20contexts.=E2=80=A6=20(#58)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- pkg/kubeconfig/write.go | 12 +++++++++--- pkg/kubeconfig/write_test.go | 16 ++++++++++++++++ 2 files changed, 25 insertions(+), 3 deletions(-) diff --git a/pkg/kubeconfig/write.go b/pkg/kubeconfig/write.go index 9a3e70c..f6f953b 100644 --- a/pkg/kubeconfig/write.go +++ b/pkg/kubeconfig/write.go @@ -53,10 +53,16 @@ func (k *KConf) Merge(config *clientcmdapi.Config, name string) { if renamed, ok := renamedUsers[ctx.AuthInfo]; ok { ctx.AuthInfo = renamed } - if name == "" { - name = ctxName + // the context name is chosen based on the following priority: + // 1. provided via --context-name + // 2. specified in the provided config file + // 3. generated from the cluster and user name (-) + if name != "" { + ctxName = name + } else if ctxName == "" && name == "" { + ctxName = fmt.Sprintf("%s-%s", ctx.Cluster, ctx.AuthInfo) } - added := k.AddContext(name, ctx) + added := k.AddContext(ctxName, ctx) if added != "" { // this context was newly added if added != ctxName { Out.Log().Msgf("renamed context '%s' to '%s'", ctxName, added) diff --git a/pkg/kubeconfig/write_test.go b/pkg/kubeconfig/write_test.go index 1bd7a65..77bea59 100644 --- a/pkg/kubeconfig/write_test.go +++ b/pkg/kubeconfig/write_test.go @@ -180,6 +180,22 @@ func TestMerge(t *testing.T) { AssertContext(t, k, "test") AssertContext(t, k, "test-1") // renamed context }, + "merge multiple unique contexts": func(t *testing.T) { + k := MockConfig(1) + k2 := MockConfig(3) + + // we need k and k2 to be two unique configs, so delete the first config in k2 + err := k2.Remove("test") + if err != nil { + t.Fatal(err) + } + + k.Merge(&k2.Config, "") + + AssertContext(t, k, "test") + AssertContext(t, k, "test-1") + AssertContext(t, k, "test-2") + }, "rename cluster if it already exists": func(t *testing.T) { k := MockConfig(1) k2 := MockConfig(2)