Skip to content

Commit

Permalink
Complete --from and --to fields
Browse files Browse the repository at this point in the history
Signed-off-by: Daichi Sakaue <[email protected]>
  • Loading branch information
yokaze committed Dec 9, 2024
1 parent 995d2e4 commit ddc0e55
Show file tree
Hide file tree
Showing 3 changed files with 40 additions and 0 deletions.
36 changes: 36 additions & 0 deletions cmd/npv/app/helper_completion.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package app

import (
"context"
"strings"

"github.com/spf13/cobra"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
Expand Down Expand Up @@ -46,3 +47,38 @@ func completePods(cmd *cobra.Command, args []string, toComplete string) (ret []s
}
return
}

func completeNamespacePods(cmd *cobra.Command, args []string, toComplete string) (ret []string, directive cobra.ShellCompDirective) {
ret = make([]string, 0)
directive = cobra.ShellCompDirectiveNoFileComp

clientset, _, err := createK8sClients()
if err != nil {
return
}

li := strings.Split(toComplete, "/")
switch len(li) {
case 2: // namespace already filled
pods, err := listRelevantPods(context.Background(), clientset, li[0])
if err != nil {
return
}
for _, p := range pods {
ret = append(ret, li[0]+"/"+p.Name)
}
return

default:
nss, err := clientset.CoreV1().Namespaces().List(context.Background(), metav1.ListOptions{})
if err != nil {
return
}

for _, ns := range nss.Items {
ret = append(ret, ns.Name+"/")
}
directive = cobra.ShellCompDirectiveNoSpace
return
}
}
2 changes: 2 additions & 0 deletions cmd/npv/app/manifest_generate.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,8 @@ func init() {
manifestGenerateCmd.Flags().BoolVar(&manifestGenerateOptions.deny, "deny", false, "generate deny rule")
manifestGenerateCmd.Flags().StringVar(&manifestGenerateOptions.from, "from", "", "egress pod")
manifestGenerateCmd.Flags().StringVar(&manifestGenerateOptions.to, "to", "", "ingress pod")
manifestGenerateCmd.RegisterFlagCompletionFunc("from", completeNamespacePods)
manifestGenerateCmd.RegisterFlagCompletionFunc("to", completeNamespacePods)
manifestCmd.AddCommand(manifestGenerateCmd)
}

Expand Down
2 changes: 2 additions & 0 deletions cmd/npv/app/manifest_range.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,8 @@ var manifestRangeOptions struct {
func init() {
manifestRangeCmd.Flags().StringVar(&manifestRangeOptions.from, "from", "", "egress pod")
manifestRangeCmd.Flags().StringVar(&manifestRangeOptions.to, "to", "", "ingress pod")
manifestRangeCmd.RegisterFlagCompletionFunc("from", completeNamespacePods)
manifestRangeCmd.RegisterFlagCompletionFunc("to", completeNamespacePods)
manifestCmd.AddCommand(manifestRangeCmd)
}

Expand Down

0 comments on commit ddc0e55

Please sign in to comment.