256
|
1 |
package cobra |
|
2 |
|
|
3 |
import ( |
|
4 |
"fmt" |
|
5 |
"os" |
|
6 |
"strings" |
|
7 |
"sync" |
|
8 |
|
|
9 |
"github.com/spf13/pflag" |
|
10 |
) |
|
11 |
|
|
12 |
const ( |
|
13 |
// ShellCompRequestCmd is the name of the hidden command that is used to request |
|
14 |
// completion results from the program. It is used by the shell completion scripts. |
|
15 |
ShellCompRequestCmd = "__complete" |
|
16 |
// ShellCompNoDescRequestCmd is the name of the hidden command that is used to request |
|
17 |
// completion results without their description. It is used by the shell completion scripts. |
|
18 |
ShellCompNoDescRequestCmd = "__completeNoDesc" |
|
19 |
) |
|
20 |
|
|
21 |
// Global map of flag completion functions. Make sure to use flagCompletionMutex before you try to read and write from it. |
|
22 |
var flagCompletionFunctions = map[*pflag.Flag]func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective){} |
|
23 |
|
|
24 |
// lock for reading and writing from flagCompletionFunctions |
|
25 |
var flagCompletionMutex = &sync.RWMutex{} |
|
26 |
|
|
27 |
// ShellCompDirective is a bit map representing the different behaviors the shell |
|
28 |
// can be instructed to have once completions have been provided. |
|
29 |
type ShellCompDirective int |
|
30 |
|
|
31 |
type flagCompError struct { |
|
32 |
subCommand string |
|
33 |
flagName string |
|
34 |
} |
|
35 |
|
|
36 |
func (e *flagCompError) Error() string { |
|
37 |
return "Subcommand '" + e.subCommand + "' does not support flag '" + e.flagName + "'" |
|
38 |
} |
|
39 |
|
|
40 |
const ( |
|
41 |
// ShellCompDirectiveError indicates an error occurred and completions should be ignored. |
|
42 |
ShellCompDirectiveError ShellCompDirective = 1 << iota |
|
43 |
|
|
44 |
// ShellCompDirectiveNoSpace indicates that the shell should not add a space |
|
45 |
// after the completion even if there is a single completion provided. |
|
46 |
ShellCompDirectiveNoSpace |
|
47 |
|
|
48 |
// ShellCompDirectiveNoFileComp indicates that the shell should not provide |
|
49 |
// file completion even when no completion is provided. |
|
50 |
ShellCompDirectiveNoFileComp |
|
51 |
|
|
52 |
// ShellCompDirectiveFilterFileExt indicates that the provided completions |
|
53 |
// should be used as file extension filters. |
|
54 |
// For flags, using Command.MarkFlagFilename() and Command.MarkPersistentFlagFilename() |
|
55 |
// is a shortcut to using this directive explicitly. The BashCompFilenameExt |
|
56 |
// annotation can also be used to obtain the same behavior for flags. |
|
57 |
ShellCompDirectiveFilterFileExt |
|
58 |
|
|
59 |
// ShellCompDirectiveFilterDirs indicates that only directory names should |
|
60 |
// be provided in file completion. To request directory names within another |
|
61 |
// directory, the returned completions should specify the directory within |
|
62 |
// which to search. The BashCompSubdirsInDir annotation can be used to |
|
63 |
// obtain the same behavior but only for flags. |
|
64 |
ShellCompDirectiveFilterDirs |
|
65 |
|
|
66 |
// =========================================================================== |
|
67 |
|
|
68 |
// All directives using iota should be above this one. |
|
69 |
// For internal use. |
|
70 |
shellCompDirectiveMaxValue |
|
71 |
|
|
72 |
// ShellCompDirectiveDefault indicates to let the shell perform its default |
|
73 |
// behavior after completions have been provided. |
|
74 |
// This one must be last to avoid messing up the iota count. |
|
75 |
ShellCompDirectiveDefault ShellCompDirective = 0 |
|
76 |
) |
|
77 |
|
|
78 |
const ( |
|
79 |
// Constants for the completion command |
|
80 |
compCmdName = "completion" |
|
81 |
compCmdNoDescFlagName = "no-descriptions" |
|
82 |
compCmdNoDescFlagDesc = "disable completion descriptions" |
|
83 |
compCmdNoDescFlagDefault = false |
|
84 |
) |
|
85 |
|
|
86 |
// CompletionOptions are the options to control shell completion |
|
87 |
type CompletionOptions struct { |
|
88 |
// DisableDefaultCmd prevents Cobra from creating a default 'completion' command |
|
89 |
DisableDefaultCmd bool |
|
90 |
// DisableNoDescFlag prevents Cobra from creating the '--no-descriptions' flag |
|
91 |
// for shells that support completion descriptions |
|
92 |
DisableNoDescFlag bool |
|
93 |
// DisableDescriptions turns off all completion descriptions for shells |
|
94 |
// that support them |
|
95 |
DisableDescriptions bool |
260
|
96 |
// HiddenDefaultCmd makes the default 'completion' command hidden |
|
97 |
HiddenDefaultCmd bool |
256
|
98 |
} |
|
99 |
|
|
100 |
// NoFileCompletions can be used to disable file completion for commands that should |
|
101 |
// not trigger file completions. |
|
102 |
func NoFileCompletions(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective) { |
|
103 |
return nil, ShellCompDirectiveNoFileComp |
|
104 |
} |
|
105 |
|
260
|
106 |
// FixedCompletions can be used to create a completion function which always |
|
107 |
// returns the same results. |
|
108 |
func FixedCompletions(choices []string, directive ShellCompDirective) func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective) { |
|
109 |
return func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective) { |
|
110 |
return choices, directive |
|
111 |
} |
|
112 |
} |
|
113 |
|
256
|
114 |
// RegisterFlagCompletionFunc should be called to register a function to provide completion for a flag. |
|
115 |
func (c *Command) RegisterFlagCompletionFunc(flagName string, f func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective)) error { |
|
116 |
flag := c.Flag(flagName) |
|
117 |
if flag == nil { |
|
118 |
return fmt.Errorf("RegisterFlagCompletionFunc: flag '%s' does not exist", flagName) |
|
119 |
} |
|
120 |
flagCompletionMutex.Lock() |
|
121 |
defer flagCompletionMutex.Unlock() |
|
122 |
|
|
123 |
if _, exists := flagCompletionFunctions[flag]; exists { |
|
124 |
return fmt.Errorf("RegisterFlagCompletionFunc: flag '%s' already registered", flagName) |
|
125 |
} |
|
126 |
flagCompletionFunctions[flag] = f |
|
127 |
return nil |
|
128 |
} |
|
129 |
|
|
130 |
// Returns a string listing the different directive enabled in the specified parameter |
|
131 |
func (d ShellCompDirective) string() string { |
|
132 |
var directives []string |
|
133 |
if d&ShellCompDirectiveError != 0 { |
|
134 |
directives = append(directives, "ShellCompDirectiveError") |
|
135 |
} |
|
136 |
if d&ShellCompDirectiveNoSpace != 0 { |
|
137 |
directives = append(directives, "ShellCompDirectiveNoSpace") |
|
138 |
} |
|
139 |
if d&ShellCompDirectiveNoFileComp != 0 { |
|
140 |
directives = append(directives, "ShellCompDirectiveNoFileComp") |
|
141 |
} |
|
142 |
if d&ShellCompDirectiveFilterFileExt != 0 { |
|
143 |
directives = append(directives, "ShellCompDirectiveFilterFileExt") |
|
144 |
} |
|
145 |
if d&ShellCompDirectiveFilterDirs != 0 { |
|
146 |
directives = append(directives, "ShellCompDirectiveFilterDirs") |
|
147 |
} |
|
148 |
if len(directives) == 0 { |
|
149 |
directives = append(directives, "ShellCompDirectiveDefault") |
|
150 |
} |
|
151 |
|
|
152 |
if d >= shellCompDirectiveMaxValue { |
|
153 |
return fmt.Sprintf("ERROR: unexpected ShellCompDirective value: %d", d) |
|
154 |
} |
|
155 |
return strings.Join(directives, ", ") |
|
156 |
} |
|
157 |
|
|
158 |
// Adds a special hidden command that can be used to request custom completions. |
|
159 |
func (c *Command) initCompleteCmd(args []string) { |
|
160 |
completeCmd := &Command{ |
|
161 |
Use: fmt.Sprintf("%s [command-line]", ShellCompRequestCmd), |
|
162 |
Aliases: []string{ShellCompNoDescRequestCmd}, |
|
163 |
DisableFlagsInUseLine: true, |
|
164 |
Hidden: true, |
|
165 |
DisableFlagParsing: true, |
|
166 |
Args: MinimumNArgs(1), |
|
167 |
Short: "Request shell completion choices for the specified command-line", |
|
168 |
Long: fmt.Sprintf("%[2]s is a special command that is used by the shell completion logic\n%[1]s", |
|
169 |
"to request completion choices for the specified command-line.", ShellCompRequestCmd), |
|
170 |
Run: func(cmd *Command, args []string) { |
|
171 |
finalCmd, completions, directive, err := cmd.getCompletions(args) |
|
172 |
if err != nil { |
|
173 |
CompErrorln(err.Error()) |
|
174 |
// Keep going for multiple reasons: |
|
175 |
// 1- There could be some valid completions even though there was an error |
|
176 |
// 2- Even without completions, we need to print the directive |
|
177 |
} |
|
178 |
|
|
179 |
noDescriptions := (cmd.CalledAs() == ShellCompNoDescRequestCmd) |
|
180 |
for _, comp := range completions { |
260
|
181 |
if GetActiveHelpConfig(finalCmd) == activeHelpGlobalDisable { |
|
182 |
// Remove all activeHelp entries in this case |
|
183 |
if strings.HasPrefix(comp, activeHelpMarker) { |
|
184 |
continue |
|
185 |
} |
|
186 |
} |
256
|
187 |
if noDescriptions { |
|
188 |
// Remove any description that may be included following a tab character. |
|
189 |
comp = strings.Split(comp, "\t")[0] |
|
190 |
} |
|
191 |
|
|
192 |
// Make sure we only write the first line to the output. |
|
193 |
// This is needed if a description contains a linebreak. |
|
194 |
// Otherwise the shell scripts will interpret the other lines as new flags |
|
195 |
// and could therefore provide a wrong completion. |
|
196 |
comp = strings.Split(comp, "\n")[0] |
|
197 |
|
|
198 |
// Finally trim the completion. This is especially important to get rid |
|
199 |
// of a trailing tab when there are no description following it. |
|
200 |
// For example, a sub-command without a description should not be completed |
|
201 |
// with a tab at the end (or else zsh will show a -- following it |
|
202 |
// although there is no description). |
|
203 |
comp = strings.TrimSpace(comp) |
|
204 |
|
|
205 |
// Print each possible completion to stdout for the completion script to consume. |
|
206 |
fmt.Fprintln(finalCmd.OutOrStdout(), comp) |
|
207 |
} |
|
208 |
|
|
209 |
// As the last printout, print the completion directive for the completion script to parse. |
|
210 |
// The directive integer must be that last character following a single colon (:). |
|
211 |
// The completion script expects :<directive> |
|
212 |
fmt.Fprintf(finalCmd.OutOrStdout(), ":%d\n", directive) |
|
213 |
|
|
214 |
// Print some helpful info to stderr for the user to understand. |
|
215 |
// Output from stderr must be ignored by the completion script. |
|
216 |
fmt.Fprintf(finalCmd.ErrOrStderr(), "Completion ended with directive: %s\n", directive.string()) |
|
217 |
}, |
|
218 |
} |
|
219 |
c.AddCommand(completeCmd) |
|
220 |
subCmd, _, err := c.Find(args) |
|
221 |
if err != nil || subCmd.Name() != ShellCompRequestCmd { |
|
222 |
// Only create this special command if it is actually being called. |
|
223 |
// This reduces possible side-effects of creating such a command; |
|
224 |
// for example, having this command would cause problems to a |
|
225 |
// cobra program that only consists of the root command, since this |
|
226 |
// command would cause the root command to suddenly have a subcommand. |
|
227 |
c.RemoveCommand(completeCmd) |
|
228 |
} |
|
229 |
} |
|
230 |
|
|
231 |
func (c *Command) getCompletions(args []string) (*Command, []string, ShellCompDirective, error) { |
|
232 |
// The last argument, which is not completely typed by the user, |
|
233 |
// should not be part of the list of arguments |
|
234 |
toComplete := args[len(args)-1] |
|
235 |
trimmedArgs := args[:len(args)-1] |
|
236 |
|
|
237 |
var finalCmd *Command |
|
238 |
var finalArgs []string |
|
239 |
var err error |
|
240 |
// Find the real command for which completion must be performed |
|
241 |
// check if we need to traverse here to parse local flags on parent commands |
|
242 |
if c.Root().TraverseChildren { |
|
243 |
finalCmd, finalArgs, err = c.Root().Traverse(trimmedArgs) |
|
244 |
} else { |
260
|
245 |
// For Root commands that don't specify any value for their Args fields, when we call |
|
246 |
// Find(), if those Root commands don't have any sub-commands, they will accept arguments. |
|
247 |
// However, because we have added the __complete sub-command in the current code path, the |
|
248 |
// call to Find() -> legacyArgs() will return an error if there are any arguments. |
|
249 |
// To avoid this, we first remove the __complete command to get back to having no sub-commands. |
|
250 |
rootCmd := c.Root() |
|
251 |
if len(rootCmd.Commands()) == 1 { |
|
252 |
rootCmd.RemoveCommand(c) |
|
253 |
} |
|
254 |
|
|
255 |
finalCmd, finalArgs, err = rootCmd.Find(trimmedArgs) |
256
|
256 |
} |
|
257 |
if err != nil { |
|
258 |
// Unable to find the real command. E.g., <program> someInvalidCmd <TAB> |
|
259 |
return c, []string{}, ShellCompDirectiveDefault, fmt.Errorf("Unable to find a command for arguments: %v", trimmedArgs) |
|
260 |
} |
|
261 |
finalCmd.ctx = c.ctx |
|
262 |
|
|
263 |
// Check if we are doing flag value completion before parsing the flags. |
|
264 |
// This is important because if we are completing a flag value, we need to also |
|
265 |
// remove the flag name argument from the list of finalArgs or else the parsing |
|
266 |
// could fail due to an invalid value (incomplete) for the flag. |
|
267 |
flag, finalArgs, toComplete, flagErr := checkIfFlagCompletion(finalCmd, finalArgs, toComplete) |
|
268 |
|
|
269 |
// Check if interspersed is false or -- was set on a previous arg. |
|
270 |
// This works by counting the arguments. Normally -- is not counted as arg but |
|
271 |
// if -- was already set or interspersed is false and there is already one arg then |
|
272 |
// the extra added -- is counted as arg. |
|
273 |
flagCompletion := true |
|
274 |
_ = finalCmd.ParseFlags(append(finalArgs, "--")) |
|
275 |
newArgCount := finalCmd.Flags().NArg() |
|
276 |
|
|
277 |
// Parse the flags early so we can check if required flags are set |
|
278 |
if err = finalCmd.ParseFlags(finalArgs); err != nil { |
|
279 |
return finalCmd, []string{}, ShellCompDirectiveDefault, fmt.Errorf("Error while parsing flags from args %v: %s", finalArgs, err.Error()) |
|
280 |
} |
|
281 |
|
|
282 |
realArgCount := finalCmd.Flags().NArg() |
|
283 |
if newArgCount > realArgCount { |
|
284 |
// don't do flag completion (see above) |
|
285 |
flagCompletion = false |
|
286 |
} |
|
287 |
// Error while attempting to parse flags |
|
288 |
if flagErr != nil { |
|
289 |
// If error type is flagCompError and we don't want flagCompletion we should ignore the error |
|
290 |
if _, ok := flagErr.(*flagCompError); !(ok && !flagCompletion) { |
|
291 |
return finalCmd, []string{}, ShellCompDirectiveDefault, flagErr |
|
292 |
} |
|
293 |
} |
|
294 |
|
260
|
295 |
// We only remove the flags from the arguments if DisableFlagParsing is not set. |
|
296 |
// This is important for commands which have requested to do their own flag completion. |
|
297 |
if !finalCmd.DisableFlagParsing { |
|
298 |
finalArgs = finalCmd.Flags().Args() |
|
299 |
} |
|
300 |
|
256
|
301 |
if flag != nil && flagCompletion { |
|
302 |
// Check if we are completing a flag value subject to annotations |
|
303 |
if validExts, present := flag.Annotations[BashCompFilenameExt]; present { |
|
304 |
if len(validExts) != 0 { |
|
305 |
// File completion filtered by extensions |
|
306 |
return finalCmd, validExts, ShellCompDirectiveFilterFileExt, nil |
|
307 |
} |
|
308 |
|
|
309 |
// The annotation requests simple file completion. There is no reason to do |
|
310 |
// that since it is the default behavior anyway. Let's ignore this annotation |
|
311 |
// in case the program also registered a completion function for this flag. |
|
312 |
// Even though it is a mistake on the program's side, let's be nice when we can. |
|
313 |
} |
|
314 |
|
|
315 |
if subDir, present := flag.Annotations[BashCompSubdirsInDir]; present { |
|
316 |
if len(subDir) == 1 { |
|
317 |
// Directory completion from within a directory |
|
318 |
return finalCmd, subDir, ShellCompDirectiveFilterDirs, nil |
|
319 |
} |
|
320 |
// Directory completion |
|
321 |
return finalCmd, []string{}, ShellCompDirectiveFilterDirs, nil |
|
322 |
} |
|
323 |
} |
|
324 |
|
260
|
325 |
var completions []string |
|
326 |
var directive ShellCompDirective |
|
327 |
|
|
328 |
// Enforce flag groups before doing flag completions |
|
329 |
finalCmd.enforceFlagGroupsForCompletion() |
|
330 |
|
|
331 |
// Note that we want to perform flagname completion even if finalCmd.DisableFlagParsing==true; |
|
332 |
// doing this allows for completion of persistent flag names even for commands that disable flag parsing. |
|
333 |
// |
256
|
334 |
// When doing completion of a flag name, as soon as an argument starts with |
|
335 |
// a '-' we know it is a flag. We cannot use isFlagArg() here as it requires |
|
336 |
// the flag name to be complete |
|
337 |
if flag == nil && len(toComplete) > 0 && toComplete[0] == '-' && !strings.Contains(toComplete, "=") && flagCompletion { |
|
338 |
// First check for required flags |
|
339 |
completions = completeRequireFlags(finalCmd, toComplete) |
|
340 |
|
|
341 |
// If we have not found any required flags, only then can we show regular flags |
|
342 |
if len(completions) == 0 { |
|
343 |
doCompleteFlags := func(flag *pflag.Flag) { |
|
344 |
if !flag.Changed || |
|
345 |
strings.Contains(flag.Value.Type(), "Slice") || |
|
346 |
strings.Contains(flag.Value.Type(), "Array") { |
|
347 |
// If the flag is not already present, or if it can be specified multiple times (Array or Slice) |
|
348 |
// we suggest it as a completion |
|
349 |
completions = append(completions, getFlagNameCompletions(flag, toComplete)...) |
|
350 |
} |
|
351 |
} |
|
352 |
|
|
353 |
// We cannot use finalCmd.Flags() because we may not have called ParsedFlags() for commands |
|
354 |
// that have set DisableFlagParsing; it is ParseFlags() that merges the inherited and |
|
355 |
// non-inherited flags. |
|
356 |
finalCmd.InheritedFlags().VisitAll(func(flag *pflag.Flag) { |
|
357 |
doCompleteFlags(flag) |
|
358 |
}) |
|
359 |
finalCmd.NonInheritedFlags().VisitAll(func(flag *pflag.Flag) { |
|
360 |
doCompleteFlags(flag) |
|
361 |
}) |
|
362 |
} |
|
363 |
|
260
|
364 |
directive = ShellCompDirectiveNoFileComp |
256
|
365 |
if len(completions) == 1 && strings.HasSuffix(completions[0], "=") { |
|
366 |
// If there is a single completion, the shell usually adds a space |
|
367 |
// after the completion. We don't want that if the flag ends with an = |
|
368 |
directive = ShellCompDirectiveNoSpace |
|
369 |
} |
|
370 |
|
260
|
371 |
if !finalCmd.DisableFlagParsing { |
|
372 |
// If DisableFlagParsing==false, we have completed the flags as known by Cobra; |
|
373 |
// we can return what we found. |
|
374 |
// If DisableFlagParsing==true, Cobra may not be aware of all flags, so we |
|
375 |
// let the logic continue to see if ValidArgsFunction needs to be called. |
|
376 |
return finalCmd, completions, directive, nil |
|
377 |
} |
|
378 |
} else { |
|
379 |
directive = ShellCompDirectiveDefault |
|
380 |
if flag == nil { |
|
381 |
foundLocalNonPersistentFlag := false |
|
382 |
// If TraverseChildren is true on the root command we don't check for |
|
383 |
// local flags because we can use a local flag on a parent command |
|
384 |
if !finalCmd.Root().TraverseChildren { |
|
385 |
// Check if there are any local, non-persistent flags on the command-line |
|
386 |
localNonPersistentFlags := finalCmd.LocalNonPersistentFlags() |
|
387 |
finalCmd.NonInheritedFlags().VisitAll(func(flag *pflag.Flag) { |
|
388 |
if localNonPersistentFlags.Lookup(flag.Name) != nil && flag.Changed { |
|
389 |
foundLocalNonPersistentFlag = true |
256
|
390 |
} |
260
|
391 |
}) |
256
|
392 |
} |
|
393 |
|
260
|
394 |
// Complete subcommand names, including the help command |
|
395 |
if len(finalArgs) == 0 && !foundLocalNonPersistentFlag { |
|
396 |
// We only complete sub-commands if: |
|
397 |
// - there are no arguments on the command-line and |
|
398 |
// - there are no local, non-persistent flags on the command-line or TraverseChildren is true |
|
399 |
for _, subCmd := range finalCmd.Commands() { |
|
400 |
if subCmd.IsAvailableCommand() || subCmd == finalCmd.helpCommand { |
|
401 |
if strings.HasPrefix(subCmd.Name(), toComplete) { |
|
402 |
completions = append(completions, fmt.Sprintf("%s\t%s", subCmd.Name(), subCmd.Short)) |
256
|
403 |
} |
260
|
404 |
directive = ShellCompDirectiveNoFileComp |
256
|
405 |
} |
|
406 |
} |
|
407 |
} |
|
408 |
|
260
|
409 |
// Complete required flags even without the '-' prefix |
|
410 |
completions = append(completions, completeRequireFlags(finalCmd, toComplete)...) |
|
411 |
|
|
412 |
// Always complete ValidArgs, even if we are completing a subcommand name. |
|
413 |
// This is for commands that have both subcommands and ValidArgs. |
|
414 |
if len(finalCmd.ValidArgs) > 0 { |
|
415 |
if len(finalArgs) == 0 { |
|
416 |
// ValidArgs are only for the first argument |
|
417 |
for _, validArg := range finalCmd.ValidArgs { |
|
418 |
if strings.HasPrefix(validArg, toComplete) { |
|
419 |
completions = append(completions, validArg) |
|
420 |
} |
|
421 |
} |
|
422 |
directive = ShellCompDirectiveNoFileComp |
|
423 |
|
|
424 |
// If no completions were found within commands or ValidArgs, |
|
425 |
// see if there are any ArgAliases that should be completed. |
|
426 |
if len(completions) == 0 { |
|
427 |
for _, argAlias := range finalCmd.ArgAliases { |
|
428 |
if strings.HasPrefix(argAlias, toComplete) { |
|
429 |
completions = append(completions, argAlias) |
|
430 |
} |
|
431 |
} |
|
432 |
} |
|
433 |
} |
|
434 |
|
|
435 |
// If there are ValidArgs specified (even if they don't match), we stop completion. |
|
436 |
// Only one of ValidArgs or ValidArgsFunction can be used for a single command. |
|
437 |
return finalCmd, completions, directive, nil |
|
438 |
} |
|
439 |
|
|
440 |
// Let the logic continue so as to add any ValidArgsFunction completions, |
|
441 |
// even if we already found sub-commands. |
|
442 |
// This is for commands that have subcommands but also specify a ValidArgsFunction. |
256
|
443 |
} |
|
444 |
} |
|
445 |
|
|
446 |
// Find the completion function for the flag or command |
|
447 |
var completionFn func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective) |
|
448 |
if flag != nil && flagCompletion { |
|
449 |
flagCompletionMutex.RLock() |
|
450 |
completionFn = flagCompletionFunctions[flag] |
|
451 |
flagCompletionMutex.RUnlock() |
|
452 |
} else { |
|
453 |
completionFn = finalCmd.ValidArgsFunction |
|
454 |
} |
|
455 |
if completionFn != nil { |
|
456 |
// Go custom completion defined for this flag or command. |
|
457 |
// Call the registered completion function to get the completions. |
|
458 |
var comps []string |
|
459 |
comps, directive = completionFn(finalCmd, finalArgs, toComplete) |
|
460 |
completions = append(completions, comps...) |
|
461 |
} |
|
462 |
|
|
463 |
return finalCmd, completions, directive, nil |
|
464 |
} |
|
465 |
|
|
466 |
func getFlagNameCompletions(flag *pflag.Flag, toComplete string) []string { |
|
467 |
if nonCompletableFlag(flag) { |
|
468 |
return []string{} |
|
469 |
} |
|
470 |
|
|
471 |
var completions []string |
|
472 |
flagName := "--" + flag.Name |
|
473 |
if strings.HasPrefix(flagName, toComplete) { |
|
474 |
// Flag without the = |
|
475 |
completions = append(completions, fmt.Sprintf("%s\t%s", flagName, flag.Usage)) |
|
476 |
|
|
477 |
// Why suggest both long forms: --flag and --flag= ? |
|
478 |
// This forces the user to *always* have to type either an = or a space after the flag name. |
|
479 |
// Let's be nice and avoid making users have to do that. |
|
480 |
// Since boolean flags and shortname flags don't show the = form, let's go that route and never show it. |
|
481 |
// The = form will still work, we just won't suggest it. |
|
482 |
// This also makes the list of suggested flags shorter as we avoid all the = forms. |
|
483 |
// |
|
484 |
// if len(flag.NoOptDefVal) == 0 { |
|
485 |
// // Flag requires a value, so it can be suffixed with = |
|
486 |
// flagName += "=" |
|
487 |
// completions = append(completions, fmt.Sprintf("%s\t%s", flagName, flag.Usage)) |
|
488 |
// } |
|
489 |
} |
|
490 |
|
|
491 |
flagName = "-" + flag.Shorthand |
|
492 |
if len(flag.Shorthand) > 0 && strings.HasPrefix(flagName, toComplete) { |
|
493 |
completions = append(completions, fmt.Sprintf("%s\t%s", flagName, flag.Usage)) |
|
494 |
} |
|
495 |
|
|
496 |
return completions |
|
497 |
} |
|
498 |
|
|
499 |
func completeRequireFlags(finalCmd *Command, toComplete string) []string { |
|
500 |
var completions []string |
|
501 |
|
|
502 |
doCompleteRequiredFlags := func(flag *pflag.Flag) { |
|
503 |
if _, present := flag.Annotations[BashCompOneRequiredFlag]; present { |
|
504 |
if !flag.Changed { |
|
505 |
// If the flag is not already present, we suggest it as a completion |
|
506 |
completions = append(completions, getFlagNameCompletions(flag, toComplete)...) |
|
507 |
} |
|
508 |
} |
|
509 |
} |
|
510 |
|
|
511 |
// We cannot use finalCmd.Flags() because we may not have called ParsedFlags() for commands |
|
512 |
// that have set DisableFlagParsing; it is ParseFlags() that merges the inherited and |
|
513 |
// non-inherited flags. |
|
514 |
finalCmd.InheritedFlags().VisitAll(func(flag *pflag.Flag) { |
|
515 |
doCompleteRequiredFlags(flag) |
|
516 |
}) |
|
517 |
finalCmd.NonInheritedFlags().VisitAll(func(flag *pflag.Flag) { |
|
518 |
doCompleteRequiredFlags(flag) |
|
519 |
}) |
|
520 |
|
|
521 |
return completions |
|
522 |
} |
|
523 |
|
|
524 |
func checkIfFlagCompletion(finalCmd *Command, args []string, lastArg string) (*pflag.Flag, []string, string, error) { |
|
525 |
if finalCmd.DisableFlagParsing { |
|
526 |
// We only do flag completion if we are allowed to parse flags |
|
527 |
// This is important for commands which have requested to do their own flag completion. |
|
528 |
return nil, args, lastArg, nil |
|
529 |
} |
|
530 |
|
|
531 |
var flagName string |
|
532 |
trimmedArgs := args |
|
533 |
flagWithEqual := false |
|
534 |
orgLastArg := lastArg |
|
535 |
|
|
536 |
// When doing completion of a flag name, as soon as an argument starts with |
|
537 |
// a '-' we know it is a flag. We cannot use isFlagArg() here as that function |
|
538 |
// requires the flag name to be complete |
|
539 |
if len(lastArg) > 0 && lastArg[0] == '-' { |
|
540 |
if index := strings.Index(lastArg, "="); index >= 0 { |
|
541 |
// Flag with an = |
|
542 |
if strings.HasPrefix(lastArg[:index], "--") { |
|
543 |
// Flag has full name |
|
544 |
flagName = lastArg[2:index] |
|
545 |
} else { |
|
546 |
// Flag is shorthand |
|
547 |
// We have to get the last shorthand flag name |
|
548 |
// e.g. `-asd` => d to provide the correct completion |
|
549 |
// https://github.com/spf13/cobra/issues/1257 |
|
550 |
flagName = lastArg[index-1 : index] |
|
551 |
} |
|
552 |
lastArg = lastArg[index+1:] |
|
553 |
flagWithEqual = true |
|
554 |
} else { |
|
555 |
// Normal flag completion |
|
556 |
return nil, args, lastArg, nil |
|
557 |
} |
|
558 |
} |
|
559 |
|
|
560 |
if len(flagName) == 0 { |
|
561 |
if len(args) > 0 { |
|
562 |
prevArg := args[len(args)-1] |
|
563 |
if isFlagArg(prevArg) { |
|
564 |
// Only consider the case where the flag does not contain an =. |
|
565 |
// If the flag contains an = it means it has already been fully processed, |
|
566 |
// so we don't need to deal with it here. |
|
567 |
if index := strings.Index(prevArg, "="); index < 0 { |
|
568 |
if strings.HasPrefix(prevArg, "--") { |
|
569 |
// Flag has full name |
|
570 |
flagName = prevArg[2:] |
|
571 |
} else { |
|
572 |
// Flag is shorthand |
|
573 |
// We have to get the last shorthand flag name |
|
574 |
// e.g. `-asd` => d to provide the correct completion |
|
575 |
// https://github.com/spf13/cobra/issues/1257 |
|
576 |
flagName = prevArg[len(prevArg)-1:] |
|
577 |
} |
|
578 |
// Remove the uncompleted flag or else there could be an error created |
|
579 |
// for an invalid value for that flag |
|
580 |
trimmedArgs = args[:len(args)-1] |
|
581 |
} |
|
582 |
} |
|
583 |
} |
|
584 |
} |
|
585 |
|
|
586 |
if len(flagName) == 0 { |
|
587 |
// Not doing flag completion |
|
588 |
return nil, trimmedArgs, lastArg, nil |
|
589 |
} |
|
590 |
|
|
591 |
flag := findFlag(finalCmd, flagName) |
|
592 |
if flag == nil { |
|
593 |
// Flag not supported by this command, the interspersed option might be set so return the original args |
|
594 |
return nil, args, orgLastArg, &flagCompError{subCommand: finalCmd.Name(), flagName: flagName} |
|
595 |
} |
|
596 |
|
|
597 |
if !flagWithEqual { |
|
598 |
if len(flag.NoOptDefVal) != 0 { |
|
599 |
// We had assumed dealing with a two-word flag but the flag is a boolean flag. |
|
600 |
// In that case, there is no value following it, so we are not really doing flag completion. |
|
601 |
// Reset everything to do noun completion. |
|
602 |
trimmedArgs = args |
|
603 |
flag = nil |
|
604 |
} |
|
605 |
} |
|
606 |
|
|
607 |
return flag, trimmedArgs, lastArg, nil |
|
608 |
} |
|
609 |
|
|
610 |
// initDefaultCompletionCmd adds a default 'completion' command to c. |
|
611 |
// This function will do nothing if any of the following is true: |
|
612 |
// 1- the feature has been explicitly disabled by the program, |
|
613 |
// 2- c has no subcommands (to avoid creating one), |
|
614 |
// 3- c already has a 'completion' command provided by the program. |
|
615 |
func (c *Command) initDefaultCompletionCmd() { |
|
616 |
if c.CompletionOptions.DisableDefaultCmd || !c.HasSubCommands() { |
|
617 |
return |
|
618 |
} |
|
619 |
|
|
620 |
for _, cmd := range c.commands { |
|
621 |
if cmd.Name() == compCmdName || cmd.HasAlias(compCmdName) { |
|
622 |
// A completion command is already available |
|
623 |
return |
|
624 |
} |
|
625 |
} |
|
626 |
|
|
627 |
haveNoDescFlag := !c.CompletionOptions.DisableNoDescFlag && !c.CompletionOptions.DisableDescriptions |
|
628 |
|
|
629 |
completionCmd := &Command{ |
|
630 |
Use: compCmdName, |
260
|
631 |
Short: "Generate the autocompletion script for the specified shell", |
|
632 |
Long: fmt.Sprintf(`Generate the autocompletion script for %[1]s for the specified shell. |
256
|
633 |
See each sub-command's help for details on how to use the generated script. |
|
634 |
`, c.Root().Name()), |
|
635 |
Args: NoArgs, |
|
636 |
ValidArgsFunction: NoFileCompletions, |
260
|
637 |
Hidden: c.CompletionOptions.HiddenDefaultCmd, |
256
|
638 |
} |
|
639 |
c.AddCommand(completionCmd) |
|
640 |
|
|
641 |
out := c.OutOrStdout() |
|
642 |
noDesc := c.CompletionOptions.DisableDescriptions |
260
|
643 |
shortDesc := "Generate the autocompletion script for %s" |
256
|
644 |
bash := &Command{ |
|
645 |
Use: "bash", |
|
646 |
Short: fmt.Sprintf(shortDesc, "bash"), |
260
|
647 |
Long: fmt.Sprintf(`Generate the autocompletion script for the bash shell. |
256
|
648 |
|
|
649 |
This script depends on the 'bash-completion' package. |
|
650 |
If it is not installed already, you can install it via your OS's package manager. |
|
651 |
|
|
652 |
To load completions in your current shell session: |
260
|
653 |
|
|
654 |
source <(%[1]s completion bash) |
256
|
655 |
|
|
656 |
To load completions for every new session, execute once: |
260
|
657 |
|
|
658 |
#### Linux: |
|
659 |
|
|
660 |
%[1]s completion bash > /etc/bash_completion.d/%[1]s |
|
661 |
|
|
662 |
#### macOS: |
|
663 |
|
|
664 |
%[1]s completion bash > $(brew --prefix)/etc/bash_completion.d/%[1]s |
256
|
665 |
|
|
666 |
You will need to start a new shell for this setup to take effect. |
260
|
667 |
`, c.Root().Name()), |
256
|
668 |
Args: NoArgs, |
|
669 |
DisableFlagsInUseLine: true, |
|
670 |
ValidArgsFunction: NoFileCompletions, |
|
671 |
RunE: func(cmd *Command, args []string) error { |
|
672 |
return cmd.Root().GenBashCompletionV2(out, !noDesc) |
|
673 |
}, |
|
674 |
} |
|
675 |
if haveNoDescFlag { |
|
676 |
bash.Flags().BoolVar(&noDesc, compCmdNoDescFlagName, compCmdNoDescFlagDefault, compCmdNoDescFlagDesc) |
|
677 |
} |
|
678 |
|
|
679 |
zsh := &Command{ |
|
680 |
Use: "zsh", |
|
681 |
Short: fmt.Sprintf(shortDesc, "zsh"), |
260
|
682 |
Long: fmt.Sprintf(`Generate the autocompletion script for the zsh shell. |
256
|
683 |
|
|
684 |
If shell completion is not already enabled in your environment you will need |
|
685 |
to enable it. You can execute the following once: |
|
686 |
|
260
|
687 |
echo "autoload -U compinit; compinit" >> ~/.zshrc |
|
688 |
|
|
689 |
To load completions in your current shell session: |
|
690 |
|
|
691 |
source <(%[1]s completion zsh); compdef _%[1]s %[1]s |
256
|
692 |
|
|
693 |
To load completions for every new session, execute once: |
260
|
694 |
|
|
695 |
#### Linux: |
|
696 |
|
|
697 |
%[1]s completion zsh > "${fpath[1]}/_%[1]s" |
|
698 |
|
|
699 |
#### macOS: |
|
700 |
|
|
701 |
%[1]s completion zsh > $(brew --prefix)/share/zsh/site-functions/_%[1]s |
256
|
702 |
|
|
703 |
You will need to start a new shell for this setup to take effect. |
|
704 |
`, c.Root().Name()), |
|
705 |
Args: NoArgs, |
|
706 |
ValidArgsFunction: NoFileCompletions, |
|
707 |
RunE: func(cmd *Command, args []string) error { |
|
708 |
if noDesc { |
|
709 |
return cmd.Root().GenZshCompletionNoDesc(out) |
|
710 |
} |
|
711 |
return cmd.Root().GenZshCompletion(out) |
|
712 |
}, |
|
713 |
} |
|
714 |
if haveNoDescFlag { |
|
715 |
zsh.Flags().BoolVar(&noDesc, compCmdNoDescFlagName, compCmdNoDescFlagDefault, compCmdNoDescFlagDesc) |
|
716 |
} |
|
717 |
|
|
718 |
fish := &Command{ |
|
719 |
Use: "fish", |
|
720 |
Short: fmt.Sprintf(shortDesc, "fish"), |
260
|
721 |
Long: fmt.Sprintf(`Generate the autocompletion script for the fish shell. |
256
|
722 |
|
|
723 |
To load completions in your current shell session: |
260
|
724 |
|
|
725 |
%[1]s completion fish | source |
256
|
726 |
|
|
727 |
To load completions for every new session, execute once: |
260
|
728 |
|
|
729 |
%[1]s completion fish > ~/.config/fish/completions/%[1]s.fish |
256
|
730 |
|
|
731 |
You will need to start a new shell for this setup to take effect. |
|
732 |
`, c.Root().Name()), |
|
733 |
Args: NoArgs, |
|
734 |
ValidArgsFunction: NoFileCompletions, |
|
735 |
RunE: func(cmd *Command, args []string) error { |
|
736 |
return cmd.Root().GenFishCompletion(out, !noDesc) |
|
737 |
}, |
|
738 |
} |
|
739 |
if haveNoDescFlag { |
|
740 |
fish.Flags().BoolVar(&noDesc, compCmdNoDescFlagName, compCmdNoDescFlagDefault, compCmdNoDescFlagDesc) |
|
741 |
} |
|
742 |
|
|
743 |
powershell := &Command{ |
|
744 |
Use: "powershell", |
|
745 |
Short: fmt.Sprintf(shortDesc, "powershell"), |
260
|
746 |
Long: fmt.Sprintf(`Generate the autocompletion script for powershell. |
256
|
747 |
|
|
748 |
To load completions in your current shell session: |
260
|
749 |
|
|
750 |
%[1]s completion powershell | Out-String | Invoke-Expression |
256
|
751 |
|
|
752 |
To load completions for every new session, add the output of the above command |
|
753 |
to your powershell profile. |
|
754 |
`, c.Root().Name()), |
|
755 |
Args: NoArgs, |
|
756 |
ValidArgsFunction: NoFileCompletions, |
|
757 |
RunE: func(cmd *Command, args []string) error { |
|
758 |
if noDesc { |
|
759 |
return cmd.Root().GenPowerShellCompletion(out) |
|
760 |
} |
|
761 |
return cmd.Root().GenPowerShellCompletionWithDesc(out) |
|
762 |
|
|
763 |
}, |
|
764 |
} |
|
765 |
if haveNoDescFlag { |
|
766 |
powershell.Flags().BoolVar(&noDesc, compCmdNoDescFlagName, compCmdNoDescFlagDefault, compCmdNoDescFlagDesc) |
|
767 |
} |
|
768 |
|
|
769 |
completionCmd.AddCommand(bash, zsh, fish, powershell) |
|
770 |
} |
|
771 |
|
|
772 |
func findFlag(cmd *Command, name string) *pflag.Flag { |
|
773 |
flagSet := cmd.Flags() |
|
774 |
if len(name) == 1 { |
|
775 |
// First convert the short flag into a long flag |
|
776 |
// as the cmd.Flag() search only accepts long flags |
|
777 |
if short := flagSet.ShorthandLookup(name); short != nil { |
|
778 |
name = short.Name |
|
779 |
} else { |
|
780 |
set := cmd.InheritedFlags() |
|
781 |
if short = set.ShorthandLookup(name); short != nil { |
|
782 |
name = short.Name |
|
783 |
} else { |
|
784 |
return nil |
|
785 |
} |
|
786 |
} |
|
787 |
} |
|
788 |
return cmd.Flag(name) |
|
789 |
} |
|
790 |
|
|
791 |
// CompDebug prints the specified string to the same file as where the |
|
792 |
// completion script prints its logs. |
|
793 |
// Note that completion printouts should never be on stdout as they would |
|
794 |
// be wrongly interpreted as actual completion choices by the completion script. |
|
795 |
func CompDebug(msg string, printToStdErr bool) { |
|
796 |
msg = fmt.Sprintf("[Debug] %s", msg) |
|
797 |
|
|
798 |
// Such logs are only printed when the user has set the environment |
|
799 |
// variable BASH_COMP_DEBUG_FILE to the path of some file to be used. |
|
800 |
if path := os.Getenv("BASH_COMP_DEBUG_FILE"); path != "" { |
|
801 |
f, err := os.OpenFile(path, |
|
802 |
os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644) |
|
803 |
if err == nil { |
|
804 |
defer f.Close() |
|
805 |
WriteStringAndCheck(f, msg) |
|
806 |
} |
|
807 |
} |
|
808 |
|
|
809 |
if printToStdErr { |
|
810 |
// Must print to stderr for this not to be read by the completion script. |
|
811 |
fmt.Fprint(os.Stderr, msg) |
|
812 |
} |
|
813 |
} |
|
814 |
|
|
815 |
// CompDebugln prints the specified string with a newline at the end |
|
816 |
// to the same file as where the completion script prints its logs. |
|
817 |
// Such logs are only printed when the user has set the environment |
|
818 |
// variable BASH_COMP_DEBUG_FILE to the path of some file to be used. |
|
819 |
func CompDebugln(msg string, printToStdErr bool) { |
|
820 |
CompDebug(fmt.Sprintf("%s\n", msg), printToStdErr) |
|
821 |
} |
|
822 |
|
|
823 |
// CompError prints the specified completion message to stderr. |
|
824 |
func CompError(msg string) { |
|
825 |
msg = fmt.Sprintf("[Error] %s", msg) |
|
826 |
CompDebug(msg, true) |
|
827 |
} |
|
828 |
|
|
829 |
// CompErrorln prints the specified completion message to stderr with a newline at the end. |
|
830 |
func CompErrorln(msg string) { |
|
831 |
CompError(fmt.Sprintf("%s\n", msg)) |
|
832 |
} |