Skip to content
Myr

Rename BashCompDirectives to ShellCompDirectives (#1082)

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Since the completion directives will be used for all shells, and that these names will be consumed by users, this is a more appropriate name.

authored by Marc Khouzam · committed by GitHub · parent b80aeb1 · Browse files · 5 files+93 added−93 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Trailers

  • Signed-off-by: Marc Khouzam <marc.khouzam@montreal.ca>

Diff stats

5 files+93 added−93 removed

  • other:+93 added−93 removed

5 files+93 added−93 removed

modified:bash_completions.go+1 added-1 removed
342 unmodified lines
343 fi344 __%[1]s_handle_word345}346347`, name, CompRequestCmd, BashCompDirectiveError, BashCompDirectiveNoSpace, BashCompDirectiveNoFileComp))347`, name, ShellCompRequestCmd, ShellCompDirectiveError, ShellCompDirectiveNoSpace, ShellCompDirectiveNoFileComp))348}349350func writePostscript(buf *bytes.Buffer, name string) {351 name = strings.Replace(name, ":", "__", -1)
287 unmodified lines
modified:bash_completions.md+14 added-14 removed
126 unmodified lines
127 Long: status_long,128 RunE: func(cmd *cobra.Command, args []string) {129 RunGet(args[0])130 },131 ValidArgsFunction: func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.BashCompDirective) {131 ValidArgsFunction: func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {132 if len(args) != 0 {133 return nil, cobra.BashCompDirectiveNoFileComp133 return nil, cobra.ShellCompDirectiveNoFileComp134 }135 return getReleasesFromCluster(toComplete), cobra.BashCompDirectiveNoFileComp135 return getReleasesFromCluster(toComplete), cobra.ShellCompDirectiveNoFileComp136 },137}138```139Where `getReleasesFromCluster()` is a Go function that obtains the list of current Helm releases running on the Kubernetes cluster.
2 unmodified lines
142```bash143# helm status [tab][tab]144harbor notary rook thanos145```146You may have noticed the use of `cobra.BashCompDirective`. These directives are bit fields allowing to control some shell completion behaviors for your particular completion. You can combine them with the bit-or operator such as `cobra.BashCompDirectiveNoSpace | cobra.BashCompDirectiveNoFileComp`146You may have noticed the use of `cobra.ShellCompDirective`. These directives are bit fields allowing to control some shell completion behaviors for your particular completion. You can combine them with the bit-or operator such as `cobra.ShellCompDirectiveNoSpace | cobra.ShellCompDirectiveNoFileComp`147```go148// Indicates an error occurred and completions should be ignored.149BashCompDirectiveError149ShellCompDirectiveError150// Indicates that the shell should not add a space after the completion,151// even if there is a single completion provided.152BashCompDirectiveNoSpace152ShellCompDirectiveNoSpace153// Indicates that the shell should not provide file completion even when154// no completion is provided.155// This currently does not work for zsh or bash < 4156BashCompDirectiveNoFileComp156ShellCompDirectiveNoFileComp157// Indicates that the shell will perform its default behavior after completions158// have been provided (this implies !BashCompDirectiveNoSpace && !BashCompDirectiveNoFileComp).159BashCompDirectiveDefault158// have been provided (this implies !ShellCompDirectiveNoSpace && !ShellCompDirectiveNoFileComp).159ShellCompDirectiveDefault160```161162When using the `ValidArgsFunction`, Cobra will call your registered function after having parsed all flags and arguments provided in the command-line. You therefore don't need to do this parsing yourself. For example, when a user calls `helm status --namespace my-rook-ns [tab][tab]`, Cobra will call your registered `ValidArgsFunction` after having parsed the `--namespace` flag, as it would have done when calling the `RunE` function.163
3 unmodified lines
167```bash168# helm __complete status har<ENTER>169harbor170:4171Completion ended with directive: BashCompDirectiveNoFileComp # This is on stderr171Completion ended with directive: ShellCompDirectiveNoFileComp # This is on stderr172```173***Important:*** If the noun to complete is empty, you must pass an empty parameter to the `__complete` command:174```bash175# helm __complete status ""<ENTER>
1 unmodified line
177notary178rook179thanos180:4181Completion ended with directive: BashCompDirectiveNoFileComp # This is on stderr181Completion ended with directive: ShellCompDirectiveNoFileComp # This is on stderr182```183Calling the `__complete` command directly allows you to run the Go debugger to troubleshoot your code. You can also add printouts to your code; Cobra provides the following functions to use for printouts in Go completion code:184```go185// Prints to the completion script debug file (if BASH_COMP_DEBUG_FILE
120 unmodified lines
306To provide a Go function that Cobra will execute when it needs the list of completion choices for a flag, you must register the function in the following manner:307308```go309flagName := "output"310cmd.RegisterFlagCompletionFunc(flagName, func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.BashCompDirective) {311 return []string{"json", "table", "yaml"}, cobra.BashCompDirectiveDefault310cmd.RegisterFlagCompletionFunc(flagName, func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {311 return []string{"json", "table", "yaml"}, cobra.ShellCompDirectiveDefault312})313```314Notice that calling `RegisterFlagCompletionFunc()` is done through the `command` with which the flag is associated. In our example this dynamic completion will give results like so:315
10 unmodified lines
326json327table328yaml329:4330Completion ended with directive: BashCompDirectiveNoFileComp # This is on stderr330Completion ended with directive: ShellCompDirectiveNoFileComp # This is on stderr331```332***Important:*** You should **not** leave traces that print to stdout in your completion code as they will be interpreted as completion choices by the completion script. Instead, use the cobra-provided debugging traces functions mentioned in the above section.333334## 2. Custom completions of flags written in Bash
45 unmodified lines
modified:command.go+1 added-1 removed
58 unmodified lines
59 ValidArgs []string60 // ValidArgsFunction is an optional function that provides valid non-flag arguments for bash completion.61 // It is a dynamic version of using ValidArgs.62 // Only one of ValidArgs and ValidArgsFunction can be used for a command.63 ValidArgsFunction func(cmd *Command, args []string, toComplete string) ([]string, BashCompDirective)63 ValidArgsFunction func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective)6465 // Expected arguments66 Args PositionalArgs67
1567 unmodified lines
modified:custom_completions_test.go+42 added-42 removed
4 unmodified lines
5 "strings"6 "testing"7)89func validArgsFunc(cmd *Command, args []string, toComplete string) ([]string, BashCompDirective) {9func validArgsFunc(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective) {10 if len(args) != 0 {11 return nil, BashCompDirectiveNoFileComp11 return nil, ShellCompDirectiveNoFileComp12 }1314 var completions []string15 for _, comp := range []string{"one", "two"} {16 if strings.HasPrefix(comp, toComplete) {17 completions = append(completions, comp)18 }19 }20 return completions, BashCompDirectiveDefault20 return completions, ShellCompDirectiveDefault21}2223func validArgsFunc2(cmd *Command, args []string, toComplete string) ([]string, BashCompDirective) {23func validArgsFunc2(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective) {24 if len(args) != 0 {25 return nil, BashCompDirectiveNoFileComp25 return nil, ShellCompDirectiveNoFileComp26 }2728 var completions []string29 for _, comp := range []string{"three", "four"} {30 if strings.HasPrefix(comp, toComplete) {31 completions = append(completions, comp)32 }33 }34 return completions, BashCompDirectiveDefault34 return completions, ShellCompDirectiveDefault35}3637func TestValidArgsFuncSingleCmd(t *testing.T) {38 rootCmd := &Command{
2 unmodified lines
41 Run: emptyRun,42 }4344 // Test completing an empty string45 output, err := executeCommand(rootCmd, CompRequestCmd, "")45 output, err := executeCommand(rootCmd, ShellCompRequestCmd, "")46 if err != nil {47 t.Errorf("Unexpected error: %v", err)48 }4950 expected := strings.Join([]string{51 "one",52 "two",53 ":0",54 "Completion ended with directive: BashCompDirectiveDefault", ""}, "\n")54 "Completion ended with directive: ShellCompDirectiveDefault", ""}, "\n")5556 if output != expected {57 t.Errorf("expected: %q, got: %q", expected, output)58 }5960 // Check completing with a prefix61 output, err = executeCommand(rootCmd, CompRequestCmd, "t")61 output, err = executeCommand(rootCmd, ShellCompRequestCmd, "t")62 if err != nil {63 t.Errorf("Unexpected error: %v", err)64 }6566 expected = strings.Join([]string{67 "two",68 ":0",69 "Completion ended with directive: BashCompDirectiveDefault", ""}, "\n")69 "Completion ended with directive: ShellCompDirectiveDefault", ""}, "\n")7071 if output != expected {72 t.Errorf("expected: %q, got: %q", expected, output)73 }
11 unmodified lines
85 Run: emptyRun,86 }8788 // Check completing with wrong number of args89 output, err := executeCommand(rootCmd, CompRequestCmd, "unexpectedArg", "t")89 output, err := executeCommand(rootCmd, ShellCompRequestCmd, "unexpectedArg", "t")90 if err != nil {91 t.Errorf("Unexpected error: %v", err)92 }9394 expected := strings.Join([]string{95 ":4",96 "Completion ended with directive: BashCompDirectiveNoFileComp", ""}, "\n")96 "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")9798 if output != expected {99 t.Errorf("expected: %q, got: %q", expected, output)100 }
13 unmodified lines
114 }115 rootCmd.AddCommand(child1Cmd, child2Cmd)116117 // Test completion of first sub-command with empty argument118 output, err := executeCommand(rootCmd, CompRequestCmd, "child1", "")118 output, err := executeCommand(rootCmd, ShellCompRequestCmd, "child1", "")119 if err != nil {120 t.Errorf("Unexpected error: %v", err)121 }122123 expected := strings.Join([]string{124 "one",125 "two",126 ":0",127 "Completion ended with directive: BashCompDirectiveDefault", ""}, "\n")127 "Completion ended with directive: ShellCompDirectiveDefault", ""}, "\n")128129 if output != expected {130 t.Errorf("expected: %q, got: %q", expected, output)131 }132133 // Test completion of first sub-command with a prefix to complete134 output, err = executeCommand(rootCmd, CompRequestCmd, "child1", "t")134 output, err = executeCommand(rootCmd, ShellCompRequestCmd, "child1", "t")135 if err != nil {136 t.Errorf("Unexpected error: %v", err)137 }138139 expected = strings.Join([]string{140 "two",141 ":0",142 "Completion ended with directive: BashCompDirectiveDefault", ""}, "\n")142 "Completion ended with directive: ShellCompDirectiveDefault", ""}, "\n")143144 if output != expected {145 t.Errorf("expected: %q, got: %q", expected, output)146 }147148 // Check completing with wrong number of args149 output, err = executeCommand(rootCmd, CompRequestCmd, "child1", "unexpectedArg", "t")149 output, err = executeCommand(rootCmd, ShellCompRequestCmd, "child1", "unexpectedArg", "t")150 if err != nil {151 t.Errorf("Unexpected error: %v", err)152 }153154 expected = strings.Join([]string{155 ":4",156 "Completion ended with directive: BashCompDirectiveNoFileComp", ""}, "\n")156 "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")157158 if output != expected {159 t.Errorf("expected: %q, got: %q", expected, output)160 }161162 // Test completion of second sub-command with empty argument163 output, err = executeCommand(rootCmd, CompRequestCmd, "child2", "")163 output, err = executeCommand(rootCmd, ShellCompRequestCmd, "child2", "")164 if err != nil {165 t.Errorf("Unexpected error: %v", err)166 }167168 expected = strings.Join([]string{169 "three",170 "four",171 ":0",172 "Completion ended with directive: BashCompDirectiveDefault", ""}, "\n")172 "Completion ended with directive: ShellCompDirectiveDefault", ""}, "\n")173174 if output != expected {175 t.Errorf("expected: %q, got: %q", expected, output)176 }177178 output, err = executeCommand(rootCmd, CompRequestCmd, "child2", "t")178 output, err = executeCommand(rootCmd, ShellCompRequestCmd, "child2", "t")179 if err != nil {180 t.Errorf("Unexpected error: %v", err)181 }182183 expected = strings.Join([]string{184 "three",185 ":0",186 "Completion ended with directive: BashCompDirectiveDefault", ""}, "\n")186 "Completion ended with directive: ShellCompDirectiveDefault", ""}, "\n")187188 if output != expected {189 t.Errorf("expected: %q, got: %q", expected, output)190 }191192 // Check completing with wrong number of args193 output, err = executeCommand(rootCmd, CompRequestCmd, "child2", "unexpectedArg", "t")193 output, err = executeCommand(rootCmd, ShellCompRequestCmd, "child2", "unexpectedArg", "t")194 if err != nil {195 t.Errorf("Unexpected error: %v", err)196 }197198 expected = strings.Join([]string{199 ":4",200 "Completion ended with directive: BashCompDirectiveNoFileComp", ""}, "\n")200 "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")201202 if output != expected {203 t.Errorf("expected: %q, got: %q", expected, output)204 }
9 unmodified lines
214 }215 rootCmd.AddCommand(child)216217 // Test completion of first sub-command with empty argument218 output, err := executeCommand(rootCmd, CompRequestCmd, "son", "")218 output, err := executeCommand(rootCmd, ShellCompRequestCmd, "son", "")219 if err != nil {220 t.Errorf("Unexpected error: %v", err)221 }222223 expected := strings.Join([]string{224 "one",225 "two",226 ":0",227 "Completion ended with directive: BashCompDirectiveDefault", ""}, "\n")227 "Completion ended with directive: ShellCompDirectiveDefault", ""}, "\n")228229 if output != expected {230 t.Errorf("expected: %q, got: %q", expected, output)231 }232233 // Test completion of first sub-command with a prefix to complete234 output, err = executeCommand(rootCmd, CompRequestCmd, "daughter", "t")234 output, err = executeCommand(rootCmd, ShellCompRequestCmd, "daughter", "t")235 if err != nil {236 t.Errorf("Unexpected error: %v", err)237 }238239 expected = strings.Join([]string{240 "two",241 ":0",242 "Completion ended with directive: BashCompDirectiveDefault", ""}, "\n")242 "Completion ended with directive: ShellCompDirectiveDefault", ""}, "\n")243244 if output != expected {245 t.Errorf("expected: %q, got: %q", expected, output)246 }247248 // Check completing with wrong number of args249 output, err = executeCommand(rootCmd, CompRequestCmd, "son", "unexpectedArg", "t")249 output, err = executeCommand(rootCmd, ShellCompRequestCmd, "son", "unexpectedArg", "t")250 if err != nil {251 t.Errorf("Unexpected error: %v", err)252 }253254 expected = strings.Join([]string{255 ":4",256 "Completion ended with directive: BashCompDirectiveNoFileComp", ""}, "\n")256 "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")257258 if output != expected {259 t.Errorf("expected: %q, got: %q", expected, output)260 }
35 unmodified lines
296 Use: "root",297 Run: emptyRun,298 }299 rootCmd.Flags().IntP("introot", "i", -1, "help message for flag introot")300 rootCmd.RegisterFlagCompletionFunc("introot", func(cmd *Command, args []string, toComplete string) ([]string, BashCompDirective) {300 rootCmd.RegisterFlagCompletionFunc("introot", func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective) {301 completions := []string{}302 for _, comp := range []string{"1", "2", "10"} {303 if strings.HasPrefix(comp, toComplete) {304 completions = append(completions, comp)305 }306 }307 return completions, BashCompDirectiveDefault307 return completions, ShellCompDirectiveDefault308 })309 rootCmd.Flags().String("filename", "", "Enter a filename")310 rootCmd.RegisterFlagCompletionFunc("filename", func(cmd *Command, args []string, toComplete string) ([]string, BashCompDirective) {310 rootCmd.RegisterFlagCompletionFunc("filename", func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective) {311 completions := []string{}312 for _, comp := range []string{"file.yaml", "myfile.json", "file.xml"} {313 if strings.HasPrefix(comp, toComplete) {314 completions = append(completions, comp)315 }316 }317 return completions, BashCompDirectiveNoSpace | BashCompDirectiveNoFileComp317 return completions, ShellCompDirectiveNoSpace | ShellCompDirectiveNoFileComp318 })319320 // Test completing an empty string321 output, err := executeCommand(rootCmd, CompRequestCmd, "--introot", "")321 output, err := executeCommand(rootCmd, ShellCompRequestCmd, "--introot", "")322 if err != nil {323 t.Errorf("Unexpected error: %v", err)324 }325
1 unmodified line
327 "1",328 "2",329 "10",330 ":0",331 "Completion ended with directive: BashCompDirectiveDefault", ""}, "\n")331 "Completion ended with directive: ShellCompDirectiveDefault", ""}, "\n")332333 if output != expected {334 t.Errorf("expected: %q, got: %q", expected, output)335 }336337 // Check completing with a prefix338 output, err = executeCommand(rootCmd, CompRequestCmd, "--introot", "1")338 output, err = executeCommand(rootCmd, ShellCompRequestCmd, "--introot", "1")339 if err != nil {340 t.Errorf("Unexpected error: %v", err)341 }342343 expected = strings.Join([]string{344 "1",345 "10",346 ":0",347 "Completion ended with directive: BashCompDirectiveDefault", ""}, "\n")347 "Completion ended with directive: ShellCompDirectiveDefault", ""}, "\n")348349 if output != expected {350 t.Errorf("expected: %q, got: %q", expected, output)351 }352353 // Test completing an empty string354 output, err = executeCommand(rootCmd, CompRequestCmd, "--filename", "")354 output, err = executeCommand(rootCmd, ShellCompRequestCmd, "--filename", "")355 if err != nil {356 t.Errorf("Unexpected error: %v", err)357 }358
1 unmodified line
360 "file.yaml",361 "myfile.json",362 "file.xml",363 ":6",364 "Completion ended with directive: BashCompDirectiveNoSpace, BashCompDirectiveNoFileComp", ""}, "\n")364 "Completion ended with directive: ShellCompDirectiveNoSpace, ShellCompDirectiveNoFileComp", ""}, "\n")365366 if output != expected {367 t.Errorf("expected: %q, got: %q", expected, output)368 }369370 // Check completing with a prefix371 output, err = executeCommand(rootCmd, CompRequestCmd, "--filename", "f")371 output, err = executeCommand(rootCmd, ShellCompRequestCmd, "--filename", "f")372 if err != nil {373 t.Errorf("Unexpected error: %v", err)374 }375376 expected = strings.Join([]string{377 "file.yaml",378 "file.xml",379 ":6",380 "Completion ended with directive: BashCompDirectiveNoSpace, BashCompDirectiveNoFileComp", ""}, "\n")380 "Completion ended with directive: ShellCompDirectiveNoSpace, ShellCompDirectiveNoFileComp", ""}, "\n")381382 if output != expected {383 t.Errorf("expected: %q, got: %q", expected, output)384 }
1 unmodified line
modified:custom_completions.go+35 added-35 removed
7 unmodified lines
89 "github.com/spf13/pflag"10)1112// CompRequestCmd is the name of the hidden command that is used to request12// ShellCompRequestCmd is the name of the hidden command that is used to request13// completion results from the program. It is used by the shell completion script.14const CompRequestCmd = "__complete"14const ShellCompRequestCmd = "__complete"1516// Global map of flag completion functions.17var flagCompletionFunctions = map[*pflag.Flag]func(cmd *Command, args []string, toComplete string) ([]string, BashCompDirective){}17var flagCompletionFunctions = map[*pflag.Flag]func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective){}1819// BashCompDirective is a bit map representing the different behaviors the shell19// ShellCompDirective is a bit map representing the different behaviors the shell20// can be instructed to have once completions have been provided.21type BashCompDirective int21type ShellCompDirective int2223const (24 // BashCompDirectiveError indicates an error occurred and completions should be ignored.25 BashCompDirectiveError BashCompDirective = 1 << iota24 // ShellCompDirectiveError indicates an error occurred and completions should be ignored.25 ShellCompDirectiveError ShellCompDirective = 1 << iota2627 // BashCompDirectiveNoSpace indicates that the shell should not add a space27 // ShellCompDirectiveNoSpace indicates that the shell should not add a space28 // after the completion even if there is a single completion provided.29 BashCompDirectiveNoSpace29 ShellCompDirectiveNoSpace3031 // BashCompDirectiveNoFileComp indicates that the shell should not provide31 // ShellCompDirectiveNoFileComp indicates that the shell should not provide32 // file completion even when no completion is provided.33 // This currently does not work for zsh or bash < 434 BashCompDirectiveNoFileComp34 ShellCompDirectiveNoFileComp3536 // BashCompDirectiveDefault indicates to let the shell perform its default36 // ShellCompDirectiveDefault indicates to let the shell perform its default37 // behavior after completions have been provided.38 BashCompDirectiveDefault BashCompDirective = 038 ShellCompDirectiveDefault ShellCompDirective = 039)4041// RegisterFlagCompletionFunc should be called to register a function to provide completion for a flag.42func (c *Command) RegisterFlagCompletionFunc(flagName string, f func(cmd *Command, args []string, toComplete string) ([]string, BashCompDirective)) error {42func (c *Command) RegisterFlagCompletionFunc(flagName string, f func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective)) error {43 flag := c.Flag(flagName)44 if flag == nil {45 return fmt.Errorf("RegisterFlagCompletionFunc: flag '%s' does not exist", flagName)46 }
4 unmodified lines
51 return nil52}5354// Returns a string listing the different directive enabled in the specified parameter55func (d BashCompDirective) string() string {55func (d ShellCompDirective) string() string {56 var directives []string57 if d&BashCompDirectiveError != 0 {58 directives = append(directives, "BashCompDirectiveError")57 if d&ShellCompDirectiveError != 0 {58 directives = append(directives, "ShellCompDirectiveError")59 }60 if d&BashCompDirectiveNoSpace != 0 {61 directives = append(directives, "BashCompDirectiveNoSpace")60 if d&ShellCompDirectiveNoSpace != 0 {61 directives = append(directives, "ShellCompDirectiveNoSpace")62 }63 if d&BashCompDirectiveNoFileComp != 0 {64 directives = append(directives, "BashCompDirectiveNoFileComp")63 if d&ShellCompDirectiveNoFileComp != 0 {64 directives = append(directives, "ShellCompDirectiveNoFileComp")65 }66 if len(directives) == 0 {67 directives = append(directives, "BashCompDirectiveDefault")67 directives = append(directives, "ShellCompDirectiveDefault")68 }6970 if d > BashCompDirectiveError+BashCompDirectiveNoSpace+BashCompDirectiveNoFileComp {71 return fmt.Sprintf("ERROR: unexpected BashCompDirective value: %d", d)70 if d > ShellCompDirectiveError+ShellCompDirectiveNoSpace+ShellCompDirectiveNoFileComp {71 return fmt.Sprintf("ERROR: unexpected ShellCompDirective value: %d", d)72 }73 return strings.Join(directives, ", ")74}7576// Adds a special hidden command that can be used to request custom completions.77func (c *Command) initCompleteCmd(args []string) {78 completeCmd := &Command{79 Use: fmt.Sprintf("%s [command-line]", CompRequestCmd),79 Use: fmt.Sprintf("%s [command-line]", ShellCompRequestCmd),80 DisableFlagsInUseLine: true,81 Hidden: true,82 DisableFlagParsing: true,83 Args: MinimumNArgs(1),84 Short: "Request shell completion choices for the specified command-line",85 Long: fmt.Sprintf("%[2]s is a special command that is used by the shell completion logic\n%[1]s",86 "to request completion choices for the specified command-line.", CompRequestCmd),86 "to request completion choices for the specified command-line.", ShellCompRequestCmd),87 Run: func(cmd *Command, args []string) {88 finalCmd, completions, directive, err := cmd.getCompletions(args)89 if err != nil {90 CompErrorln(err.Error())
6 unmodified lines
97 // Print each possible completion to stdout for the completion script to consume.98 fmt.Fprintln(finalCmd.OutOrStdout(), comp)99 }100101 if directive > BashCompDirectiveError+BashCompDirectiveNoSpace+BashCompDirectiveNoFileComp {102 directive = BashCompDirectiveDefault101 if directive > ShellCompDirectiveError+ShellCompDirectiveNoSpace+ShellCompDirectiveNoFileComp {102 directive = ShellCompDirectiveDefault103 }104105 // As the last printout, print the completion directive for the completion script to parse.106 // The directive integer must be that last character following a single colon (:).
6 unmodified lines
113 },114 }115 c.AddCommand(completeCmd)116 subCmd, _, err := c.Find(args)117 if err != nil || subCmd.Name() != CompRequestCmd {117 if err != nil || subCmd.Name() != ShellCompRequestCmd {118 // Only create this special command if it is actually being called.119 // This reduces possible side-effects of creating such a command;120 // for example, having this command would cause problems to a121 // cobra program that only consists of the root command, since this
1 unmodified line
123 c.RemoveCommand(completeCmd)124 }125}126127func (c *Command) getCompletions(args []string) (*Command, []string, BashCompDirective, error) {127func (c *Command) getCompletions(args []string) (*Command, []string, ShellCompDirective, error) {128 var completions []string129130 // The last argument, which is not completely typed by the user,131 // should not be part of the list of arguments
3 unmodified lines
135 // Find the real command for which completion must be performed136 finalCmd, finalArgs, err := c.Root().Find(trimmedArgs)137 if err != nil {138 // Unable to find the real command. E.g., <program> someInvalidCmd <TAB>139 return c, completions, BashCompDirectiveDefault, fmt.Errorf("Unable to find a command for arguments: %v", trimmedArgs)139 return c, completions, ShellCompDirectiveDefault, fmt.Errorf("Unable to find a command for arguments: %v", trimmedArgs)140 }141142 var flag *pflag.Flag143 if !finalCmd.DisableFlagParsing {
1 unmodified line
145 // This is important for commands which have requested to do their own flag completion.146 flag, finalArgs, toComplete, err = checkIfFlagCompletion(finalCmd, finalArgs, toComplete)147 if err != nil {148 // Error while attempting to parse flags149 return finalCmd, completions, BashCompDirectiveDefault, err149 return finalCmd, completions, ShellCompDirectiveDefault, err150 }151 }152153 // Parse the flags and extract the arguments to prepare for calling the completion function154 if err = finalCmd.ParseFlags(finalArgs); err != nil {155 return finalCmd, completions, BashCompDirectiveDefault, fmt.Errorf("Error while parsing flags from args %v: %s", finalArgs, err.Error())155 return finalCmd, completions, ShellCompDirectiveDefault, fmt.Errorf("Error while parsing flags from args %v: %s", finalArgs, err.Error())156 }157158 // We only remove the flags from the arguments if DisableFlagParsing is not set.159 // This is important for commands which have requested to do their own flag completion.
1 unmodified line
161 finalArgs = finalCmd.Flags().Args()162 }163164 // Find the completion function for the flag or command165 var completionFn func(cmd *Command, args []string, toComplete string) ([]string, BashCompDirective)165 var completionFn func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective)166 if flag != nil {167 completionFn = flagCompletionFunctions[flag]168 } else {169 completionFn = finalCmd.ValidArgsFunction170 }171 if completionFn == nil {172 // Go custom completion not supported/needed for this flag or command173 return finalCmd, completions, BashCompDirectiveDefault, nil173 return finalCmd, completions, ShellCompDirectiveDefault, nil174 }175176 // Call the registered completion function to get the completions177 comps, directive := completionFn(finalCmd, finalArgs, toComplete)
122 unmodified lines