From 17c1fccd9c6c8e59339f1970576ea1815c9fb454 Mon Sep 17 00:00:00 2001 From: iwilltry42 Date: Fri, 5 Jun 2020 08:54:27 +0200 Subject: [PATCH] completion: add custom completion for 'get clusters' --- cmd/get/getCluster.go | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/cmd/get/getCluster.go b/cmd/get/getCluster.go index 5d9535d5..fb298e57 100644 --- a/cmd/get/getCluster.go +++ b/cmd/get/getCluster.go @@ -58,6 +58,7 @@ func NewCmdGetCluster() *cobra.Command { clusters := buildClusterList(cmd.Context(), args) PrintClusters(clusters, clusterFlags) }, + ValidArgsFunction: validArgsFunc, } // add flags @@ -70,6 +71,31 @@ func NewCmdGetCluster() *cobra.Command { return cmd } +// validArgsFunc is used for shell completion: proposes the list of existing clusters +func validArgsFunc(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { + + var completions []string + var clusters []*k3d.Cluster + clusters, err := k3cluster.GetClusters(context.Background(), runtimes.SelectedRuntime) + if err != nil { + log.Errorln("Failed to get list of clusters for shell completion") + return nil, cobra.ShellCompDirectiveError + } + +clusterLoop: + for _, cluster := range clusters { + for _, arg := range args { + if arg == cluster.Name { // only clusters, that are not in the args yet + continue clusterLoop + } + } + if strings.HasPrefix(cluster.Name, toComplete) { + completions = append(completions, cluster.Name) + } + } + return completions, cobra.ShellCompDirectiveDefault +} + func buildClusterList(ctx context.Context, args []string) []*k3d.Cluster { var clusters []*k3d.Cluster var err error