This repository was archived by the owner on Dec 10, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcobra-prompt.go
196 lines (158 loc) · 5.69 KB
/
cobra-prompt.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
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
package cobraprompt
import (
"context"
"os"
"regexp"
"strings"
"github.com/spf13/cobra"
"github.com/spf13/pflag"
"github.com/verkada/go-prompt"
)
// DynamicSuggestionsAnnotation for dynamic suggestions.
const DynamicSuggestionsAnnotation = "cobra-prompt-dynamic-suggestions"
// PersistFlagValuesFlag the flag that will be avaiailable when PersistFlagValues is true
const PersistFlagValuesFlag = "persist-flag-values"
// CobraPrompt given a Cobra command it will make every flag and sub commands available as suggestions.
// Command.Short will be used as description for the suggestion.
type CobraPrompt struct {
// RootCmd is the start point, all its sub commands and flags will be available as suggestions
RootCmd *cobra.Command
// GoPromptOptions is for customize go-prompt
// see https://github.com/verkada/go-prompt/blob/master/option.go
GoPromptOptions []prompt.Option
// DynamicSuggestionsFunc will be executed if an command has CallbackAnnotation as an annotation. If it's included
// the value will be provided to the DynamicSuggestionsFunc function.
DynamicSuggestionsFunc func(annotationValue string, document *prompt.Document) []prompt.Suggest
// PersistFlagValues will persist flags. For example have verbose turned on every command.
PersistFlagValues bool
// ShowHelpCommandAndFlags will make help command and flag for every command available.
ShowHelpCommandAndFlags bool
// DisableCompletionCommand will disable the default completion command for cobra
DisableCompletionCommand bool
// ShowHiddenCommands makes hidden commands available
ShowHiddenCommands bool
// ShowHiddenFlags makes hidden flags available
ShowHiddenFlags bool
// AddDefaultExitCommand adds a command for exiting prompt loop
AddDefaultExitCommand bool
// OnErrorFunc handle error for command.Execute, if not set print error and exit
OnErrorFunc func(err error)
// InArgsParser adds a custom parser for the command line arguments (default: strings.Fields)
InArgsParser func(args string) []string
// SuggestionFilter will be uses when filtering suggestions as typing
SuggestionFilter func(suggestions []prompt.Suggest, document *prompt.Document) []prompt.Suggest
}
// Run will automatically generate suggestions for all cobra commands and flags defined by RootCmd
// and execute the selected commands. Run will also reset all given flags by default, see PersistFlagValues
func (co CobraPrompt) Run() {
co.RunContext(nil)
}
// RunContext same as Run but with context
func (co CobraPrompt) RunContext(ctx context.Context) {
if co.RootCmd == nil {
panic("RootCmd is not set. Please set RootCmd")
}
co.prepare()
p := prompt.New(
func(in string) {
promptArgs := co.parseArgs(in)
os.Args = append([]string{os.Args[0]}, promptArgs...)
if err := co.RootCmd.ExecuteContext(ctx); err != nil {
if co.OnErrorFunc != nil {
co.OnErrorFunc(err)
} else {
co.RootCmd.PrintErrln(err)
os.Exit(1)
}
}
},
func(d prompt.Document) []prompt.Suggest {
return findSuggestions(&co, &d)
},
co.GoPromptOptions...,
)
p.Run()
}
func parseArgsWithQuotes(input string) []string {
re := regexp.MustCompile(`"[^"]+"|\S+`)
matches := re.FindAllString(input, -1)
var args []string
for _, match := range matches {
// Remove surrounding double quotes if present
if strings.HasPrefix(match, `"`) && strings.HasSuffix(match, `"`) {
match = match[1 : len(match)-1]
}
args = append(args, match)
}
return args
}
func (co CobraPrompt) parseArgs(in string) []string {
if co.InArgsParser != nil {
return co.InArgsParser(in)
}
return parseArgsWithQuotes(in)
}
func (co CobraPrompt) prepare() {
if co.ShowHelpCommandAndFlags {
// TODO: Add suggestions for help command
co.RootCmd.InitDefaultHelpCmd()
}
if co.DisableCompletionCommand {
co.RootCmd.CompletionOptions.DisableDefaultCmd = true
}
if co.AddDefaultExitCommand {
co.RootCmd.AddCommand(&cobra.Command{
Use: "exit",
Short: "Exit prompt",
Run: func(cmd *cobra.Command, args []string) {
os.Exit(0)
},
})
}
if co.PersistFlagValues {
co.RootCmd.PersistentFlags().BoolP(PersistFlagValuesFlag, "",
false, "Persist last given value for flags")
}
}
func findSuggestions(co *CobraPrompt, d *prompt.Document) []prompt.Suggest {
command := co.RootCmd
args := strings.Fields(d.CurrentLine())
if found, _, err := command.Find(args); err == nil {
command = found
}
var suggestions []prompt.Suggest
persistFlagValues, _ := command.Flags().GetBool(PersistFlagValuesFlag)
addFlags := func(flag *pflag.Flag) {
if flag.Changed && !persistFlagValues {
flag.Value.Set(flag.DefValue)
}
if flag.Hidden && !co.ShowHiddenFlags {
return
}
if strings.HasPrefix(d.GetWordBeforeCursor(), "--") {
suggestions = append(suggestions, prompt.Suggest{Text: "--" + flag.Name, Description: flag.Usage})
} else if strings.HasPrefix(d.GetWordBeforeCursor(), "-") && flag.Shorthand != "" {
suggestions = append(suggestions, prompt.Suggest{Text: "-" + flag.Shorthand, Description: flag.Usage})
}
}
command.LocalFlags().VisitAll(addFlags)
command.InheritedFlags().VisitAll(addFlags)
if command.HasAvailableSubCommands() {
for _, c := range command.Commands() {
if !c.Hidden && !co.ShowHiddenCommands {
suggestions = append(suggestions, prompt.Suggest{Text: c.Name(), Description: c.Short})
}
if co.ShowHelpCommandAndFlags {
c.InitDefaultHelpFlag()
}
}
}
annotation := command.Annotations[DynamicSuggestionsAnnotation]
if co.DynamicSuggestionsFunc != nil && annotation != "" {
suggestions = append(suggestions, co.DynamicSuggestionsFunc(annotation, d)...)
}
if co.SuggestionFilter != nil {
return co.SuggestionFilter(suggestions, d)
}
return prompt.FilterHasPrefix(suggestions, d.GetWordBeforeCursor(), true)
}