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 filtering contexts #432

Closed
wants to merge 1 commit into from
Closed
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
10 changes: 10 additions & 0 deletions cmd/kubectx/flags.go
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,16 @@ func parseArgs(argv []string) Op {
return ListOp{}
}

if argv[0] == "--list" || argv[0] == "-l" {
Copy link
Author

Choose a reason for hiding this comment

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

The call will be kubectx --list cluster=c1 so it does not collide with any existing functionality

if len(argv) == 1 {
return ListOp{}
}
if filters, ok := parseFilterSyntax(argv[1:]); ok {
return ListOp{Filters: filters}
}
return UnsupportedOp{Err: fmt.Errorf("'-l' filters must use A=B format")}
}

if argv[0] == "-d" {
if len(argv) == 1 {
if cmdutil.IsInteractiveMode(os.Stdout) {
Expand Down
15 changes: 15 additions & 0 deletions cmd/kubectx/flags_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,21 @@ func Test_parseArgs_new(t *testing.T) {
{name: "help long form",
args: []string{"--help"},
want: HelpOp{}},
{name: "list shorthand",
args: []string{"-l"},
want: ListOp{}},
{name: "list long form",
args: []string{"--list"},
want: ListOp{}},
{name: "list long form filters",
args: []string{"--list", "cluster=cl"},
want: ListOp{Filters: map[string]string{"cluster": "cl"}}},
{name: "list long form filters - wrong syntax",
args: []string{"--list", "cluster-cl"},
want: UnsupportedOp{fmt.Errorf("'-l' filters must use A=B format")}},
{name: "current long form",
args: []string{"--current"},
want: CurrentOp{}},
{name: "current shorthand",
args: []string{"-c"},
want: CurrentOp{}},
Expand Down
2 changes: 1 addition & 1 deletion cmd/kubectx/fzf.go
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,7 @@ func (op InteractiveDeleteOp) Run(_, stderr io.Writer) error {
}
kc.Close()

if len(kc.ContextNames()) == 0 {
if len(kc.ContextNames(nil)) == 0 {
return errors.New("no contexts found in config")
}

Expand Down
27 changes: 24 additions & 3 deletions cmd/kubectx/list.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ package main
import (
"fmt"
"io"
"strings"

"facette.io/natsort"
"github.com/pkg/errors"
Expand All @@ -27,9 +28,29 @@ import (
)

// ListOp describes listing contexts.
type ListOp struct{}
type ListOp struct {
Filters map[string]string
}

// parseFilterSyntax parses multiple A=B form into a map[A]=B and returns
// whether it is parsed correctly.
func parseFilterSyntax(v []string) (map[string]string, bool) {
m := make(map[string]string)
for _, vv := range v {
s := strings.Split(vv, "=")
if len(s) != 2 {
return nil, false
}
key, value := s[0], s[1]
if key == "" || value == "" {
return nil, false
}
m[key] = value
}
return m, true
}

func (_ ListOp) Run(stdout, stderr io.Writer) error {
func (op ListOp) Run(stdout, stderr io.Writer) error {
kc := new(kubeconfig.Kubeconfig).WithLoader(kubeconfig.DefaultLoader)
defer kc.Close()
if err := kc.Parse(); err != nil {
Expand All @@ -40,7 +61,7 @@ func (_ ListOp) Run(stdout, stderr io.Writer) error {
return errors.Wrap(err, "kubeconfig error")
}

ctxs := kc.ContextNames()
ctxs := kc.ContextNames(op.Filters)
natsort.Sort(ctxs)

cur := kc.GetCurrentContext()
Expand Down
15 changes: 13 additions & 2 deletions internal/kubeconfig/contexts.go
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ func (k *Kubeconfig) contextNode(name string) (*yaml.Node, error) {
return nil, errors.Errorf("context with name \"%s\" not found", name)
}

func (k *Kubeconfig) ContextNames() []string {
func (k *Kubeconfig) ContextNames(filters map[string]string) []string {
Copy link
Author

@malarzm malarzm Nov 25, 2024

Choose a reason for hiding this comment

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

I'm open to suggestions how you want to handle optional parameters, be it a struct, separate function, or anything else

contexts := valueOf(k.rootNode, "contexts")
if contexts == nil {
return nil
Expand All @@ -54,8 +54,19 @@ func (k *Kubeconfig) ContextNames() []string {
}

var ctxNames []string
ctxLoop:
Copy link
Author

@malarzm malarzm Nov 25, 2024

Choose a reason for hiding this comment

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

I believe this could be refactored to avoid syntax that feels like a goto to me, maybe having the filtering as a separate function instead of a nested loop. I'm open to suggestions

for _, ctx := range contexts.Content {
nameVal := valueOf(ctx, "name")
for k, v := range filters {
ctxVal := valueOf(ctx, "context")
if ctxVal == nil {
continue ctxLoop
}
vVal := valueOf(ctxVal, k)
if vVal == nil || vVal.Value != v {
continue ctxLoop
}
}
if nameVal != nil {
ctxNames = append(ctxNames, nameVal.Value)
}
Expand All @@ -64,7 +75,7 @@ func (k *Kubeconfig) ContextNames() []string {
}

func (k *Kubeconfig) ContextExists(name string) bool {
ctxNames := k.ContextNames()
ctxNames := k.ContextNames(nil)
for _, v := range ctxNames {
if v == name {
return true
Expand Down
25 changes: 22 additions & 3 deletions internal/kubeconfig/contexts_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -33,20 +33,39 @@ func TestKubeconfig_ContextNames(t *testing.T) {
t.Fatal(err)
}

ctx := kc.ContextNames()
ctx := kc.ContextNames(nil)
expected := []string{"abc", "def", "ghi"}
if diff := cmp.Diff(expected, ctx); diff != "" {
t.Fatalf("%s", diff)
}
}

func TestKubeconfig_ContextNames_Filtered(t *testing.T) {
tl := WithMockKubeconfigLoader(
testutil.KC().WithCtxs(
testutil.Ctx("abc").Ns("ns1"),
testutil.Ctx("def"),
testutil.Ctx("ghi").Ns("ns2"),
).Set("field1", map[string]string{"bar": "zoo"}).ToYAML(t))
kc := new(Kubeconfig).WithLoader(tl)
if err := kc.Parse(); err != nil {
t.Fatal(err)
}

ctx := kc.ContextNames(map[string]string{"namespace": "ns2"})
expected := []string{"ghi"}
if diff := cmp.Diff(expected, ctx); diff != "" {
t.Fatalf("%s", diff)
}
}

func TestKubeconfig_ContextNames_noContextsEntry(t *testing.T) {
tl := WithMockKubeconfigLoader(`a: b`)
kc := new(Kubeconfig).WithLoader(tl)
if err := kc.Parse(); err != nil {
t.Fatal(err)
}
ctx := kc.ContextNames()
ctx := kc.ContextNames(nil)
var expected []string = nil
if diff := cmp.Diff(expected, ctx); diff != "" {
t.Fatalf("%s", diff)
Expand All @@ -59,7 +78,7 @@ func TestKubeconfig_ContextNames_nonArrayContextsEntry(t *testing.T) {
if err := kc.Parse(); err != nil {
t.Fatal(err)
}
ctx := kc.ContextNames()
ctx := kc.ContextNames(nil)
var expected []string = nil
if diff := cmp.Diff(expected, ctx); diff != "" {
t.Fatalf("%s", diff)
Expand Down