-
Notifications
You must be signed in to change notification settings - Fork 160
/
completion.go
176 lines (157 loc) · 5.24 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
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
package completion
import (
"bytes"
"reflect"
"strings"
boshcmd "github.com/cloudfoundry/bosh-cli/v7/cmd"
"github.com/cloudfoundry/bosh-cli/v7/cmd/opts"
boshui "github.com/cloudfoundry/bosh-cli/v7/ui"
boshlog "github.com/cloudfoundry/bosh-utils/logger"
"github.com/spf13/cobra"
)
const initCmdName = "help"
const cobraCompletionCmdName = "completion"
const cobraCompleteCmdName = "__complete"
const logTag = "completion"
func IsItCompletionCommand(args []string) bool {
return len(args) > 0 && (args[0] == cobraCompletionCmdName || args[0] == cobraCompleteCmdName)
}
type CmdContext struct {
ConfigPath string
EnvironmentName string
DeploymentName string
}
func (c *CmdContext) findStoreForFlagValue(flagName string) *string {
switch flagName {
case "environment":
return &c.EnvironmentName
case "config":
return &c.ConfigPath
case "deployment":
return &c.DeploymentName
}
return nil
}
type BoshComplete struct {
completionFunctionsMap *CompleteFunctionsMap
rootCmd *cobra.Command
cmdContext *CmdContext
logger boshlog.Logger
}
func NewBoshComplete(blindUi *boshui.ConfUI, logger boshlog.Logger) *BoshComplete {
deps := boshcmd.NewBasicDeps(blindUi, logger)
cmdFactory := boshcmd.NewFactory(deps)
var session boshcmd.Session
cmd, err := cmdFactory.New([]string{initCmdName}) // just to init session
if err != nil {
logger.Debug(logTag, "session initialization (command '%s') error: %v", initCmdName, err)
} else {
session = NewCmdBridge(cmd, deps).Session()
}
cmdContext := &CmdContext{}
dq := NewDirectorQuery(logger, cmdContext, session)
cfMap := NewCompleteFunctionsMap(logger, dq)
return NewBoshCompleteWithFunctions(logger, cmdContext, cfMap)
}
func NewBoshCompleteWithFunctions(logger boshlog.Logger, cmdContext *CmdContext, completionFunctionsMap *CompleteFunctionsMap) *BoshComplete {
// https://github.com/spf13/cobra/blob/main/site/content/completions/_index.md
c := &BoshComplete{
completionFunctionsMap: completionFunctionsMap,
logger: logger,
rootCmd: &cobra.Command{Use: "bosh"},
cmdContext: cmdContext,
}
c.discoverBoshCommands(c.rootCmd, reflect.TypeOf(opts.BoshOpts{}), 0)
return c
}
func (c *BoshComplete) discoverBoshCommands(parentCommand *cobra.Command, fieldType reflect.Type, level int) {
for i := 0; i < fieldType.NumField(); i++ {
field := fieldType.Field(i)
if field.Name == "Args" {
c.tryToBindValidArgsFunction(parentCommand, field.Type.Name())
} else if field.Tag.Get("long") != "" {
c.addFlag(parentCommand, field, level == 0)
} else if fc := field.Tag.Get("command"); fc != "" && fc != cobraCompletionCmdName && fc != cobraCompleteCmdName {
newCmd := c.addCommand(parentCommand, field)
if field.Type.Kind() == reflect.Struct {
c.discoverBoshCommands(newCmd, field.Type, level+1)
}
}
}
}
func (c *BoshComplete) addCommand(parentCommand *cobra.Command, field reflect.StructField) *cobra.Command {
cmdName := field.Tag.Get("command")
newCmd := &cobra.Command{
Use: cmdName,
Short: field.Tag.Get("description"),
Aliases: c.getTagValues(field.Tag, "alias"),
Run: func(_ *cobra.Command, _ []string) {},
}
parentCommand.AddCommand(newCmd)
return newCmd
}
func (c *BoshComplete) getTagValues(fieldTag reflect.StructTag, tagName string) []string {
rawTag := string(fieldTag)
parts := strings.Split(rawTag, " ")
prefix := tagName + ":"
var values []string
for _, part := range parts {
if strings.HasPrefix(part, prefix) {
value := strings.TrimPrefix(part, prefix)
values = append(values, value)
}
}
return values
}
func (c *BoshComplete) addFlag(cmd *cobra.Command, field reflect.StructField, rootLevel bool) {
name := field.Tag.Get("long")
short := field.Tag.Get("short")
value := field.Tag.Get("default")
usage := field.Tag.Get("description")
env := field.Tag.Get("env")
if env != "" {
usage = usage + ", env: " + env
}
flagSet := cmd.Flags()
if rootLevel {
flagSet = cmd.PersistentFlags()
}
p := c.cmdContext.findStoreForFlagValue(name)
if p == nil {
flagSet.StringP(name, short, value, usage)
} else {
flagSet.StringVarP(p, name, short, value, usage)
}
if fun, ok := (*c.completionFunctionsMap)["--"+name]; ok {
err := cmd.RegisterFlagCompletionFunc(name, fun)
if err != nil {
c.logger.Warn(logTag, "register flag %s completion function error: %v", name, err)
}
}
}
func (c *BoshComplete) Execute(args []string) (*cobra.Command, error) {
c.rootCmd.SetArgs(args)
return c.rootCmd.ExecuteC()
}
func (c *BoshComplete) ExecuteCaptured(args []string) (*CapturedResult, error) {
buf := new(bytes.Buffer)
c.rootCmd.SetOut(buf)
retCmd, err := c.Execute(args)
if err != nil {
return nil, err
}
retLines := strings.Split(buf.String(), "\n")
return &CapturedResult{Lines: retLines, Command: retCmd}, nil
}
func (c *BoshComplete) tryToBindValidArgsFunction(cmd *cobra.Command, argsTypeName string) {
if fun, ok := (*c.completionFunctionsMap)[argsTypeName]; ok {
//c.logger.Debug(c.logTag, "Command ValidArgsFunction '%s': `%v`", cmd.Name(), GetShortFunName(fun))
cmd.ValidArgsFunction = fun
} else {
c.logger.Warn(logTag, "Unknown Args Type %s, command %s", argsTypeName, cmd.Name())
}
}
type CapturedResult struct {
Lines []string
Command *cobra.Command
}