Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add domain list command #3

Merged
merged 4 commits into from
Nov 11, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions pkg/command/domain/domain.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ func NewDomainCmd(p *pkg.AdminParams) *cobra.Command {
}
domainCmd.AddCommand(NewDomainSetCommand(p))
domainCmd.AddCommand(NewDomainUnSetCommand(p))
domainCmd.AddCommand(NewDomainListCommand(p))
domainCmd.InitDefaultHelpCmd()
return domainCmd
}
2 changes: 1 addition & 1 deletion pkg/command/domain/domain_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ import (
func TestNewDomainCmd(t *testing.T) {
cmd := NewDomainCmd(nil)
assert.Check(t, cmd.HasSubCommands(), "cmd domain should have subcommands")
assert.Equal(t, 3, len(cmd.Commands()), "domain command should have 3 subcommands")
assert.Equal(t, 4, len(cmd.Commands()), "domain command should have 4 subcommands")

_, _, err := cmd.Find([]string{"set"})
assert.NilError(t, err, "domain command should have set subcommand")
Expand Down
77 changes: 77 additions & 0 deletions pkg/command/domain/human_readable_flags.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
// Copyright © 2020 The Knative 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 domain

import (
"sort"
"strings"

corev1 "k8s.io/api/core/v1"
metav1beta1 "k8s.io/apimachinery/pkg/apis/meta/v1beta1"

hprinters "knative.dev/client/pkg/printers"
)

// DomainListHandlers adds print handlers for domain list command
func DomainListHandlers(h hprinters.PrintHandler) {
kDomainColumnDefinitions := []metav1beta1.TableColumnDefinition{
{Name: "Custom-Domain", Type: "string", Description: "Name of Knative custom domain.", Priority: 1},
{Name: "Selector", Type: "string", Description: "Selector of Knative custom domains.", Priority: 1},
}
h.TableHandler(kDomainColumnDefinitions, printKDomainList)
}

// printKDomainList populates the Knative custom domain list table rows
func printKDomainList(domainCM *corev1.ConfigMap, options hprinters.PrintOptions) ([]metav1beta1.TableRow, error) {
kDomainList := domainCM.Data
delete(kDomainList, "_example")

//sort the map for output
sortedKeys := make([]string, 0, len(kDomainList))
for k := range kDomainList {
sortedKeys = append(sortedKeys, k)
}
sort.Strings(sortedKeys)

rows := make([]metav1beta1.TableRow, 0, len(kDomainList))
for _, k := range sortedKeys {
row := metav1beta1.TableRow{}
row.Cells = append(row.Cells, k, formatSelectorForPrint(kDomainList[k]))
rows = append(rows, []metav1beta1.TableRow{row}...)
}
return rows, nil
}

//format change for selector from "selector:\n key1: value1\n key2: value2\n" to "key1=value1; key2=value2;
func formatSelectorForPrint(selector string) string {
parts := strings.Split(strings.ReplaceAll(strings.TrimSpace(selector), ":", "="), "\n")
selectorForPrint := ""
for i, v := range parts {
//parts is from split by \n, so the first item i=0 will be start with "selector="", if not, return ""
if i == 0 && !strings.HasPrefix(v, "selector=") {
return ""

} else if i > 0 { //skip the first item i=0 "selector="
if strings.Contains(v, "=") {
selectorForPrint = strings.Join([]string{selectorForPrint, strings.ReplaceAll(v, " ", "")}, "")
//no ; for last selector entry
if i < len(parts)-1 {
selectorForPrint = strings.Join([]string{selectorForPrint, "; "}, "")
}
}
}
}
return selectorForPrint
}
41 changes: 41 additions & 0 deletions pkg/command/domain/human_readable_flags_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
// Copyright © 2020 The Knative Authors
//

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Same as above

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

agree, code changed. Thank you.

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Same as above.

Copy link
Contributor Author

@ZhuangYuZY ZhuangYuZY Nov 3, 2020

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hi @zhanggbj , In Conversation, the file is outdated. Please check "Files changed" tab. I already made the change of 2019 --> 2020. Thank you.

// 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 domain

import "testing"

func Test_formatSelectorForPrint(t *testing.T) {
tests := []struct {
name string
input string
output string
}{
{"normal case with one selector key value", "selector:\n key1: value1\n", "key1=value1"},
{"normal case with two selector key value", "selector:\n key1: value1\n key2: value2\n", "key1=value1; key2=value2"},
{"invalid input no selector", "notselector:\n key1= value1\n", ""},
{"invalid input no selector value", "selector:\n", ""},
{"invalid input wrong selector value", "selector:\n key1 value1\n", ""},
{"invalid input wrong selector values", "selector:\n key1 value1\n key2: value2", "key2=value2"},
{"empty selector", "", ""},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
output := formatSelectorForPrint(tt.input)
if output != tt.output {
t.Errorf("formatSelectorForPrint() got = %v, want %v", output, tt.output)
}
})
}
}
60 changes: 60 additions & 0 deletions pkg/command/domain/list.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
// Copyright © 2020 The Knative 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 domain

import (
"fmt"

"github.com/spf13/cobra"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"knative.dev/client/pkg/kn/commands/flags"
"knative.dev/kn-plugin-admin/pkg"
)

// NewDomainListCommand represents 'kn-admin domain list' command
func NewDomainListCommand(p *pkg.AdminParams) *cobra.Command {

domainListFlags := flags.NewListPrintFlags(DomainListHandlers)
domainListCommand := &cobra.Command{
Use: "list",
Short: "List domain",
Long: "List Knative custom domain",
Example: `
# To list all custom domains
kn admin domain list`,

RunE: func(cmd *cobra.Command, args []string) error {
domainCm, err := p.ClientSet.CoreV1().ConfigMaps(knativeServing).Get(configDomain, metav1.GetOptions{})
if err != nil {
return fmt.Errorf("failed to get ConfigMap %s in namespace %s: %+v", configDomain, knativeServing, err)
}
domainCmType := metav1.TypeMeta{
Kind: "ConfigMap",
APIVersion: "v1",
}
domainCm.TypeMeta = domainCmType
err = domainListFlags.Print(domainCm, cmd.OutOrStdout())
if err != nil {
return err
}
return nil
},
}
domainListFlags.HumanReadableFlags.AddFlags(domainListCommand)
domainListFlags.GenericPrintFlags.OutputFlagSpecified = func() bool {
return false
}
return domainListCommand
}
106 changes: 106 additions & 0 deletions pkg/command/domain/list_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,106 @@
// Copyright © 2020 The Knative 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 domain

import (
"strings"
"testing"

"gotest.tools/assert"
corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
k8sfake "k8s.io/client-go/kubernetes/fake"
"knative.dev/client/pkg/util"
"knative.dev/kn-plugin-admin/pkg"

"knative.dev/kn-plugin-admin/pkg/testutil"
)

func TestDomainListEmpty(t *testing.T) {
t.Run("list domain", func(t *testing.T) {
cm := &corev1.ConfigMap{
ObjectMeta: metav1.ObjectMeta{
Name: configDomain,
Namespace: knativeServing,
},
Data: map[string]string{},
}
client := k8sfake.NewSimpleClientset(cm)
p := pkg.AdminParams{
ClientSet: client,
}
cmd := NewDomainListCommand(&p)
output, err := testutil.ExecuteCommand(cmd)
assert.NilError(t, err)
rowsOfOutput := strings.Split(output, "\n")
assert.Check(t, util.ContainsAll(rowsOfOutput[0], "CUSTOM-DOMAIN", "SELECTOR"))
})
}

func TestDomainListCommand(t *testing.T) {

t.Run("list domain", func(t *testing.T) {
cm := &corev1.ConfigMap{
ObjectMeta: metav1.ObjectMeta{
Name: configDomain,
Namespace: knativeServing,
},
Data: map[string]string{
"dummy1.domain": "",
"a-dummy.domain": "selector:\n app1: helloworld1\n app2: helloworld2\n",
"dummy2.domain": "selector:\n app: helloworld\n",
},
}
client := k8sfake.NewSimpleClientset(cm)
p := pkg.AdminParams{
ClientSet: client,
}
cmd := NewDomainListCommand(&p)
output, err := testutil.ExecuteCommand(cmd)
assert.NilError(t, err)
rowsOfOutput := strings.Split(output, "\n")
//Domain will be listed with order by domain name
assert.Check(t, util.ContainsAll(rowsOfOutput[0], "CUSTOM-DOMAIN", "SELECTOR"))
assert.Check(t, util.ContainsAll(rowsOfOutput[1], "a-dummy.domain", "app1=helloworld1; app2=helloworld2"))
assert.Check(t, util.ContainsAll(rowsOfOutput[2], "dummy1.domain"))
assert.Check(t, util.ContainsAll(rowsOfOutput[3], "dummy2.domain", "app=helloworld"))
})
}

func TestDomainListCommandNoHeader(t *testing.T) {

t.Run("list domain", func(t *testing.T) {
cm := &corev1.ConfigMap{
ObjectMeta: metav1.ObjectMeta{
Name: configDomain,
Namespace: knativeServing,
},
Data: map[string]string{
"dummy1.domain": "",
"dummy2.domain": "selector:\n app: helloworld\n",
},
}
client := k8sfake.NewSimpleClientset(cm)
p := pkg.AdminParams{
ClientSet: client,
}
cmd := NewDomainListCommand(&p)
output, err := testutil.ExecuteCommand(cmd, "--no-headers")
assert.NilError(t, err)
rowsOfOutput := strings.Split(output, "\n")
assert.Check(t, util.ContainsAll(rowsOfOutput[0], "dummy1.domain"))
assert.Check(t, util.ContainsAll(rowsOfOutput[1], "dummy2.domain", "app=helloworld"))
})
}