Browse Source

default description about kube contexts

Signed-off-by: Guillaume Tardif <[email protected]>
Guillaume Tardif 4 years ago
parent
commit
96f20946af
2 changed files with 75 additions and 1 deletions
  1. 17 1
      kube/context.go
  2. 58 0
      kube/context_test.go

+ 17 - 1
kube/context.go

@@ -19,6 +19,8 @@
 package kube
 
 import (
+	"fmt"
+
 	"github.com/AlecAivazis/survey/v2/terminal"
 	"github.com/docker/compose-cli/api/context/store"
 	"github.com/docker/compose-cli/api/errdefs"
@@ -105,5 +107,19 @@ func (cp ContextParams) CreateContextData() (interface{}, string, error) {
 		ContextName:     cp.KubeContextName,
 		KubeconfigPath:  cp.KubeConfigPath,
 		FromEnvironment: cp.FromEnvironment,
-	}, cp.Description, nil
+	}, cp.getDescription(), nil
+}
+
+func (cp ContextParams) getDescription() string {
+	if cp.Description != "" {
+		return cp.Description
+	}
+	if cp.FromEnvironment {
+		return "From environment variables"
+	}
+	configFile := "default kube config"
+	if cp.KubeconfigPath != "" {
+		configFile = cp.KubeconfigPath
+	}
+	return fmt.Sprintf("%s (in %s)", cp.ContextName, configFile)
 }

+ 58 - 0
kube/context_test.go

@@ -0,0 +1,58 @@
+// +build kube
+
+/*
+   Copyright 2020 Docker Compose CLI authors
+
+   Licensed under the Apache License, Version 2.0 (the "License");
+   you may not use this file except in compliance with the License.
+   You may obtain a copy of the License at
+
+       http://www.apache.org/licenses/LICENSE-2.0
+
+   Unless required by applicable law or agreed to in writing, software
+   distributed under the License is distributed on an "AS IS" BASIS,
+   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+   See the License for the specific language governing permissions and
+   limitations under the License.
+*/
+
+package kube
+
+import (
+	"testing"
+
+	"gotest.tools/v3/assert"
+)
+
+func TestContextDescriptionIfEnvVar(t *testing.T) {
+	cp := ContextParams{
+		FromEnvironment: true,
+	}
+	description := cp.getDescription()
+	assert.Equal(t, description, "From environment variables")
+}
+
+func TestContextDescriptionIfProvided(t *testing.T) {
+	cp := ContextParams{
+		Description:     "custom description",
+		FromEnvironment: true,
+	}
+	description := cp.getDescription()
+	assert.Equal(t, description, "custom description")
+}
+
+func TestContextDescriptionIfConfigFile(t *testing.T) {
+	cp := ContextParams{
+		ContextName:    "my-context",
+		KubeconfigPath: "~/.kube/config",
+	}
+	description := cp.getDescription()
+	assert.Equal(t, description, "my-context (in ~/.kube/config)")
+}
+func TestContextDescriptionIfDefaultConfigFile(t *testing.T) {
+	cp := ContextParams{
+		ContextName: "my-context",
+	}
+	description := cp.getDescription()
+	assert.Equal(t, description, "my-context (in default kube config)")
+}