-
Notifications
You must be signed in to change notification settings - Fork 10
/
completion.go
129 lines (109 loc) · 4.61 KB
/
completion.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
/*
Copyright (C) 2022-2023 ApeCloud Co., Ltd
This file is part of KubeBlocks project
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package util
import (
"bytes"
"io/ioutil"
"os"
"strings"
"github.com/spf13/cobra"
"k8s.io/apimachinery/pkg/api/meta"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/cli-runtime/pkg/genericiooptions"
"k8s.io/cli-runtime/pkg/printers"
"k8s.io/kubectl/pkg/cmd/get"
cmdutil "k8s.io/kubectl/pkg/cmd/util"
utilcomp "k8s.io/kubectl/pkg/util/completion"
"github.com/apecloud/kbcli/pkg/types"
)
func ResourceNameCompletionFunc(f cmdutil.Factory, gvr schema.GroupVersionResource) func(*cobra.Command, []string, string) ([]string, cobra.ShellCompDirective) {
return func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
comps := utilcomp.CompGetResource(f, GVRToString(gvr), toComplete)
seen := make(map[string]bool)
var availableComps []string
for _, arg := range args {
seen[arg] = true
}
for _, comp := range comps {
if !seen[comp] {
availableComps = append(availableComps, comp)
}
}
return availableComps, cobra.ShellCompDirectiveNoFileComp
}
}
// CompGetResourceWithLabels gets the list of the resource specified which begin with `toComplete` and have the specified labels.
// example: CompGetResourceWithLabels(f, cmd, "pods", []string{"app=nginx"}, toComplete)
// gets the name of the pods which have the label `app=nginx` and begin with `toComplete`
func CompGetResourceWithLabels(f cmdutil.Factory, cmd *cobra.Command, resourceName string, labels []string, toComplete string) []string {
template := "{{ range .items }}{{ .metadata.name }} {{ end }}"
return CompGetFromTemplateWithLabels(&template, f, "", cmd, []string{resourceName}, labels, toComplete)
}
// CompGetFromTemplateWithLabels executes a Get operation using the specified template and args and returns the results
// which begin with `toComplete` and have the specified labels.
// example: CompGetFromTemplateWithLabels(&template, f, "", cmd, []string{"pods"}, []string{"app=nginx"}, toComplete)
// will get the output of `kubectl get pods --template=template -l app=nginx`, and split the output by space and return
func CompGetFromTemplateWithLabels(template *string, f cmdutil.Factory, namespace string, cmd *cobra.Command, args []string, labels []string, toComplete string) []string {
buf := new(bytes.Buffer)
streams := genericiooptions.IOStreams{In: os.Stdin, Out: buf, ErrOut: ioutil.Discard}
o := get.NewGetOptions("kubectl", streams)
// Get the list of names of the specified resource
o.PrintFlags.TemplateFlags.GoTemplatePrintFlags.TemplateArgument = template
format := "go-template"
o.PrintFlags.OutputFormat = &format
// Do the steps Complete() would have done.
// We cannot actually call Complete() or Validate() as these function check for
// the presence of flags, which, in our case won't be there
if namespace != "" {
o.Namespace = namespace
o.ExplicitNamespace = true
} else {
var err error
o.Namespace, o.ExplicitNamespace, err = f.ToRawKubeConfigLoader().Namespace()
if err != nil {
return nil
}
}
o.ToPrinter = func(mapping *meta.RESTMapping, outputObjects *bool, withNamespace bool, withKind bool) (printers.ResourcePrinterFunc, error) {
printer, err := o.PrintFlags.ToPrinter()
if err != nil {
return nil, err
}
return printer.PrintObj, nil
}
if len(labels) > 0 {
o.LabelSelector = strings.Join(labels, ",")
}
_ = o.Run(f, args)
var comps []string
resources := strings.Split(buf.String(), " ")
for _, res := range resources {
if res != "" && strings.HasPrefix(res, toComplete) {
comps = append(comps, res)
}
}
return comps
}
func RegisterClusterCompletionFunc(cmd *cobra.Command, f cmdutil.Factory) {
if cmd.Flags().Lookup("cluster") == nil {
return
}
cmdutil.CheckErr(cmd.RegisterFlagCompletionFunc(
"cluster",
func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
return utilcomp.CompGetResource(f, GVRToString(types.ClusterGVR()), toComplete), cobra.ShellCompDirectiveNoFileComp
},
))
}