Skip to content

Commit

Permalink
fix: updates how the context name is chosen when adding new contexts.… (
Browse files Browse the repository at this point in the history
  • Loading branch information
scottnemes authored Nov 16, 2023
1 parent 0b22942 commit 840bc06
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 3 deletions.
12 changes: 9 additions & 3 deletions pkg/kubeconfig/write.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 (<cluster>-<user>)
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)
Expand Down
16 changes: 16 additions & 0 deletions pkg/kubeconfig/write_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down

0 comments on commit 840bc06

Please sign in to comment.