Rename BashCompDirectives to ShellCompDirectives (#1082)

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.

Signed-off-by: Marc Khouzam <marc.khouzam@montreal.ca>
This commit is contained in:
Marc Khouzam 2020-04-06 13:28:44 -04:00 committed by GitHub
parent b80aeb17fc
commit b84ef40338
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
5 changed files with 93 additions and 93 deletions

View File

@ -344,7 +344,7 @@ __%[1]s_handle_word()
__%[1]s_handle_word __%[1]s_handle_word
} }
`, name, CompRequestCmd, BashCompDirectiveError, BashCompDirectiveNoSpace, BashCompDirectiveNoFileComp)) `, name, ShellCompRequestCmd, ShellCompDirectiveError, ShellCompDirectiveNoSpace, ShellCompDirectiveNoFileComp))
} }
func writePostscript(buf *bytes.Buffer, name string) { func writePostscript(buf *bytes.Buffer, name string) {

View File

@ -128,11 +128,11 @@ cmd := &cobra.Command{
RunE: func(cmd *cobra.Command, args []string) { RunE: func(cmd *cobra.Command, args []string) {
RunGet(args[0]) RunGet(args[0])
}, },
ValidArgsFunction: func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.BashCompDirective) { ValidArgsFunction: func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
if len(args) != 0 { if len(args) != 0 {
return nil, cobra.BashCompDirectiveNoFileComp return nil, cobra.ShellCompDirectiveNoFileComp
} }
return getReleasesFromCluster(toComplete), cobra.BashCompDirectiveNoFileComp return getReleasesFromCluster(toComplete), cobra.ShellCompDirectiveNoFileComp
}, },
} }
``` ```
@ -143,20 +143,20 @@ Notice we put the `ValidArgsFunction` on the `status` subcommand. Let's assume t
# helm status [tab][tab] # helm status [tab][tab]
harbor notary rook thanos harbor notary rook thanos
``` ```
You 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` You 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`
```go ```go
// Indicates an error occurred and completions should be ignored. // Indicates an error occurred and completions should be ignored.
BashCompDirectiveError ShellCompDirectiveError
// Indicates that the shell should not add a space after the completion, // Indicates that the shell should not add a space after the completion,
// even if there is a single completion provided. // even if there is a single completion provided.
BashCompDirectiveNoSpace ShellCompDirectiveNoSpace
// Indicates that the shell should not provide file completion even when // Indicates that the shell should not provide file completion even when
// no completion is provided. // no completion is provided.
// This currently does not work for zsh or bash < 4 // This currently does not work for zsh or bash < 4
BashCompDirectiveNoFileComp ShellCompDirectiveNoFileComp
// Indicates that the shell will perform its default behavior after completions // Indicates that the shell will perform its default behavior after completions
// have been provided (this implies !BashCompDirectiveNoSpace && !BashCompDirectiveNoFileComp). // have been provided (this implies !ShellCompDirectiveNoSpace && !ShellCompDirectiveNoFileComp).
BashCompDirectiveDefault ShellCompDirectiveDefault
``` ```
When 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. When 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.
@ -168,7 +168,7 @@ Cobra achieves dynamic completions written in Go through the use of a hidden com
# helm __complete status har<ENTER> # helm __complete status har<ENTER>
harbor harbor
:4 :4
Completion ended with directive: BashCompDirectiveNoFileComp # This is on stderr Completion ended with directive: ShellCompDirectiveNoFileComp # This is on stderr
``` ```
***Important:*** If the noun to complete is empty, you must pass an empty parameter to the `__complete` command: ***Important:*** If the noun to complete is empty, you must pass an empty parameter to the `__complete` command:
```bash ```bash
@ -178,7 +178,7 @@ notary
rook rook
thanos thanos
:4 :4
Completion ended with directive: BashCompDirectiveNoFileComp # This is on stderr Completion ended with directive: ShellCompDirectiveNoFileComp # This is on stderr
``` ```
Calling 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: Calling 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:
```go ```go
@ -307,8 +307,8 @@ To provide a Go function that Cobra will execute when it needs the list of compl
```go ```go
flagName := "output" flagName := "output"
cmd.RegisterFlagCompletionFunc(flagName, func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.BashCompDirective) { cmd.RegisterFlagCompletionFunc(flagName, func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
return []string{"json", "table", "yaml"}, cobra.BashCompDirectiveDefault return []string{"json", "table", "yaml"}, cobra.ShellCompDirectiveDefault
}) })
``` ```
Notice 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: Notice 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:
@ -327,7 +327,7 @@ json
table table
yaml yaml
:4 :4
Completion ended with directive: BashCompDirectiveNoFileComp # This is on stderr Completion ended with directive: ShellCompDirectiveNoFileComp # This is on stderr
``` ```
***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. ***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.

View File

@ -60,7 +60,7 @@ type Command struct {
// ValidArgsFunction is an optional function that provides valid non-flag arguments for bash completion. // ValidArgsFunction is an optional function that provides valid non-flag arguments for bash completion.
// It is a dynamic version of using ValidArgs. // It is a dynamic version of using ValidArgs.
// Only one of ValidArgs and ValidArgsFunction can be used for a command. // Only one of ValidArgs and ValidArgsFunction can be used for a command.
ValidArgsFunction func(cmd *Command, args []string, toComplete string) ([]string, BashCompDirective) ValidArgsFunction func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective)
// Expected arguments // Expected arguments
Args PositionalArgs Args PositionalArgs

View File

@ -9,37 +9,37 @@ import (
"github.com/spf13/pflag" "github.com/spf13/pflag"
) )
// CompRequestCmd is the name of the hidden command that is used to request // ShellCompRequestCmd is the name of the hidden command that is used to request
// completion results from the program. It is used by the shell completion script. // completion results from the program. It is used by the shell completion script.
const CompRequestCmd = "__complete" const ShellCompRequestCmd = "__complete"
// Global map of flag completion functions. // Global map of flag completion functions.
var flagCompletionFunctions = map[*pflag.Flag]func(cmd *Command, args []string, toComplete string) ([]string, BashCompDirective){} var flagCompletionFunctions = map[*pflag.Flag]func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective){}
// BashCompDirective is a bit map representing the different behaviors the shell // ShellCompDirective is a bit map representing the different behaviors the shell
// can be instructed to have once completions have been provided. // can be instructed to have once completions have been provided.
type BashCompDirective int type ShellCompDirective int
const ( const (
// BashCompDirectiveError indicates an error occurred and completions should be ignored. // ShellCompDirectiveError indicates an error occurred and completions should be ignored.
BashCompDirectiveError BashCompDirective = 1 << iota ShellCompDirectiveError ShellCompDirective = 1 << iota
// BashCompDirectiveNoSpace indicates that the shell should not add a space // ShellCompDirectiveNoSpace indicates that the shell should not add a space
// after the completion even if there is a single completion provided. // after the completion even if there is a single completion provided.
BashCompDirectiveNoSpace ShellCompDirectiveNoSpace
// BashCompDirectiveNoFileComp indicates that the shell should not provide // ShellCompDirectiveNoFileComp indicates that the shell should not provide
// file completion even when no completion is provided. // file completion even when no completion is provided.
// This currently does not work for zsh or bash < 4 // This currently does not work for zsh or bash < 4
BashCompDirectiveNoFileComp ShellCompDirectiveNoFileComp
// BashCompDirectiveDefault indicates to let the shell perform its default // ShellCompDirectiveDefault indicates to let the shell perform its default
// behavior after completions have been provided. // behavior after completions have been provided.
BashCompDirectiveDefault BashCompDirective = 0 ShellCompDirectiveDefault ShellCompDirective = 0
) )
// RegisterFlagCompletionFunc should be called to register a function to provide completion for a flag. // RegisterFlagCompletionFunc should be called to register a function to provide completion for a flag.
func (c *Command) RegisterFlagCompletionFunc(flagName string, f func(cmd *Command, args []string, toComplete string) ([]string, BashCompDirective)) error { func (c *Command) RegisterFlagCompletionFunc(flagName string, f func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective)) error {
flag := c.Flag(flagName) flag := c.Flag(flagName)
if flag == nil { if flag == nil {
return fmt.Errorf("RegisterFlagCompletionFunc: flag '%s' does not exist", flagName) return fmt.Errorf("RegisterFlagCompletionFunc: flag '%s' does not exist", flagName)
@ -52,23 +52,23 @@ func (c *Command) RegisterFlagCompletionFunc(flagName string, f func(cmd *Comman
} }
// Returns a string listing the different directive enabled in the specified parameter // Returns a string listing the different directive enabled in the specified parameter
func (d BashCompDirective) string() string { func (d ShellCompDirective) string() string {
var directives []string var directives []string
if d&BashCompDirectiveError != 0 { if d&ShellCompDirectiveError != 0 {
directives = append(directives, "BashCompDirectiveError") directives = append(directives, "ShellCompDirectiveError")
} }
if d&BashCompDirectiveNoSpace != 0 { if d&ShellCompDirectiveNoSpace != 0 {
directives = append(directives, "BashCompDirectiveNoSpace") directives = append(directives, "ShellCompDirectiveNoSpace")
} }
if d&BashCompDirectiveNoFileComp != 0 { if d&ShellCompDirectiveNoFileComp != 0 {
directives = append(directives, "BashCompDirectiveNoFileComp") directives = append(directives, "ShellCompDirectiveNoFileComp")
} }
if len(directives) == 0 { if len(directives) == 0 {
directives = append(directives, "BashCompDirectiveDefault") directives = append(directives, "ShellCompDirectiveDefault")
} }
if d > BashCompDirectiveError+BashCompDirectiveNoSpace+BashCompDirectiveNoFileComp { if d > ShellCompDirectiveError+ShellCompDirectiveNoSpace+ShellCompDirectiveNoFileComp {
return fmt.Sprintf("ERROR: unexpected BashCompDirective value: %d", d) return fmt.Sprintf("ERROR: unexpected ShellCompDirective value: %d", d)
} }
return strings.Join(directives, ", ") return strings.Join(directives, ", ")
} }
@ -76,14 +76,14 @@ func (d BashCompDirective) string() string {
// Adds a special hidden command that can be used to request custom completions. // Adds a special hidden command that can be used to request custom completions.
func (c *Command) initCompleteCmd(args []string) { func (c *Command) initCompleteCmd(args []string) {
completeCmd := &Command{ completeCmd := &Command{
Use: fmt.Sprintf("%s [command-line]", CompRequestCmd), Use: fmt.Sprintf("%s [command-line]", ShellCompRequestCmd),
DisableFlagsInUseLine: true, DisableFlagsInUseLine: true,
Hidden: true, Hidden: true,
DisableFlagParsing: true, DisableFlagParsing: true,
Args: MinimumNArgs(1), Args: MinimumNArgs(1),
Short: "Request shell completion choices for the specified command-line", Short: "Request shell completion choices for the specified command-line",
Long: fmt.Sprintf("%[2]s is a special command that is used by the shell completion logic\n%[1]s", Long: fmt.Sprintf("%[2]s is a special command that is used by the shell completion logic\n%[1]s",
"to request completion choices for the specified command-line.", CompRequestCmd), "to request completion choices for the specified command-line.", ShellCompRequestCmd),
Run: func(cmd *Command, args []string) { Run: func(cmd *Command, args []string) {
finalCmd, completions, directive, err := cmd.getCompletions(args) finalCmd, completions, directive, err := cmd.getCompletions(args)
if err != nil { if err != nil {
@ -98,8 +98,8 @@ func (c *Command) initCompleteCmd(args []string) {
fmt.Fprintln(finalCmd.OutOrStdout(), comp) fmt.Fprintln(finalCmd.OutOrStdout(), comp)
} }
if directive > BashCompDirectiveError+BashCompDirectiveNoSpace+BashCompDirectiveNoFileComp { if directive > ShellCompDirectiveError+ShellCompDirectiveNoSpace+ShellCompDirectiveNoFileComp {
directive = BashCompDirectiveDefault directive = ShellCompDirectiveDefault
} }
// As the last printout, print the completion directive for the completion script to parse. // As the last printout, print the completion directive for the completion script to parse.
@ -114,7 +114,7 @@ func (c *Command) initCompleteCmd(args []string) {
} }
c.AddCommand(completeCmd) c.AddCommand(completeCmd)
subCmd, _, err := c.Find(args) subCmd, _, err := c.Find(args)
if err != nil || subCmd.Name() != CompRequestCmd { if err != nil || subCmd.Name() != ShellCompRequestCmd {
// Only create this special command if it is actually being called. // Only create this special command if it is actually being called.
// This reduces possible side-effects of creating such a command; // This reduces possible side-effects of creating such a command;
// for example, having this command would cause problems to a // for example, having this command would cause problems to a
@ -124,7 +124,7 @@ func (c *Command) initCompleteCmd(args []string) {
} }
} }
func (c *Command) getCompletions(args []string) (*Command, []string, BashCompDirective, error) { func (c *Command) getCompletions(args []string) (*Command, []string, ShellCompDirective, error) {
var completions []string var completions []string
// The last argument, which is not completely typed by the user, // The last argument, which is not completely typed by the user,
@ -136,7 +136,7 @@ func (c *Command) getCompletions(args []string) (*Command, []string, BashCompDir
finalCmd, finalArgs, err := c.Root().Find(trimmedArgs) finalCmd, finalArgs, err := c.Root().Find(trimmedArgs)
if err != nil { if err != nil {
// Unable to find the real command. E.g., <program> someInvalidCmd <TAB> // Unable to find the real command. E.g., <program> someInvalidCmd <TAB>
return c, completions, BashCompDirectiveDefault, fmt.Errorf("Unable to find a command for arguments: %v", trimmedArgs) return c, completions, ShellCompDirectiveDefault, fmt.Errorf("Unable to find a command for arguments: %v", trimmedArgs)
} }
var flag *pflag.Flag var flag *pflag.Flag
@ -146,13 +146,13 @@ func (c *Command) getCompletions(args []string) (*Command, []string, BashCompDir
flag, finalArgs, toComplete, err = checkIfFlagCompletion(finalCmd, finalArgs, toComplete) flag, finalArgs, toComplete, err = checkIfFlagCompletion(finalCmd, finalArgs, toComplete)
if err != nil { if err != nil {
// Error while attempting to parse flags // Error while attempting to parse flags
return finalCmd, completions, BashCompDirectiveDefault, err return finalCmd, completions, ShellCompDirectiveDefault, err
} }
} }
// Parse the flags and extract the arguments to prepare for calling the completion function // Parse the flags and extract the arguments to prepare for calling the completion function
if err = finalCmd.ParseFlags(finalArgs); err != nil { if err = finalCmd.ParseFlags(finalArgs); err != nil {
return finalCmd, completions, BashCompDirectiveDefault, fmt.Errorf("Error while parsing flags from args %v: %s", finalArgs, err.Error()) return finalCmd, completions, ShellCompDirectiveDefault, fmt.Errorf("Error while parsing flags from args %v: %s", finalArgs, err.Error())
} }
// We only remove the flags from the arguments if DisableFlagParsing is not set. // We only remove the flags from the arguments if DisableFlagParsing is not set.
@ -162,7 +162,7 @@ func (c *Command) getCompletions(args []string) (*Command, []string, BashCompDir
} }
// Find the completion function for the flag or command // Find the completion function for the flag or command
var completionFn func(cmd *Command, args []string, toComplete string) ([]string, BashCompDirective) var completionFn func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective)
if flag != nil { if flag != nil {
completionFn = flagCompletionFunctions[flag] completionFn = flagCompletionFunctions[flag]
} else { } else {
@ -170,7 +170,7 @@ func (c *Command) getCompletions(args []string) (*Command, []string, BashCompDir
} }
if completionFn == nil { if completionFn == nil {
// Go custom completion not supported/needed for this flag or command // Go custom completion not supported/needed for this flag or command
return finalCmd, completions, BashCompDirectiveDefault, nil return finalCmd, completions, ShellCompDirectiveDefault, nil
} }
// Call the registered completion function to get the completions // Call the registered completion function to get the completions

View File

@ -6,9 +6,9 @@ import (
"testing" "testing"
) )
func validArgsFunc(cmd *Command, args []string, toComplete string) ([]string, BashCompDirective) { func validArgsFunc(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective) {
if len(args) != 0 { if len(args) != 0 {
return nil, BashCompDirectiveNoFileComp return nil, ShellCompDirectiveNoFileComp
} }
var completions []string var completions []string
@ -17,12 +17,12 @@ func validArgsFunc(cmd *Command, args []string, toComplete string) ([]string, Ba
completions = append(completions, comp) completions = append(completions, comp)
} }
} }
return completions, BashCompDirectiveDefault return completions, ShellCompDirectiveDefault
} }
func validArgsFunc2(cmd *Command, args []string, toComplete string) ([]string, BashCompDirective) { func validArgsFunc2(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective) {
if len(args) != 0 { if len(args) != 0 {
return nil, BashCompDirectiveNoFileComp return nil, ShellCompDirectiveNoFileComp
} }
var completions []string var completions []string
@ -31,7 +31,7 @@ func validArgsFunc2(cmd *Command, args []string, toComplete string) ([]string, B
completions = append(completions, comp) completions = append(completions, comp)
} }
} }
return completions, BashCompDirectiveDefault return completions, ShellCompDirectiveDefault
} }
func TestValidArgsFuncSingleCmd(t *testing.T) { func TestValidArgsFuncSingleCmd(t *testing.T) {
@ -42,7 +42,7 @@ func TestValidArgsFuncSingleCmd(t *testing.T) {
} }
// Test completing an empty string // Test completing an empty string
output, err := executeCommand(rootCmd, CompRequestCmd, "") output, err := executeCommand(rootCmd, ShellCompRequestCmd, "")
if err != nil { if err != nil {
t.Errorf("Unexpected error: %v", err) t.Errorf("Unexpected error: %v", err)
} }
@ -51,14 +51,14 @@ func TestValidArgsFuncSingleCmd(t *testing.T) {
"one", "one",
"two", "two",
":0", ":0",
"Completion ended with directive: BashCompDirectiveDefault", ""}, "\n") "Completion ended with directive: ShellCompDirectiveDefault", ""}, "\n")
if output != expected { if output != expected {
t.Errorf("expected: %q, got: %q", expected, output) t.Errorf("expected: %q, got: %q", expected, output)
} }
// Check completing with a prefix // Check completing with a prefix
output, err = executeCommand(rootCmd, CompRequestCmd, "t") output, err = executeCommand(rootCmd, ShellCompRequestCmd, "t")
if err != nil { if err != nil {
t.Errorf("Unexpected error: %v", err) t.Errorf("Unexpected error: %v", err)
} }
@ -66,7 +66,7 @@ func TestValidArgsFuncSingleCmd(t *testing.T) {
expected = strings.Join([]string{ expected = strings.Join([]string{
"two", "two",
":0", ":0",
"Completion ended with directive: BashCompDirectiveDefault", ""}, "\n") "Completion ended with directive: ShellCompDirectiveDefault", ""}, "\n")
if output != expected { if output != expected {
t.Errorf("expected: %q, got: %q", expected, output) t.Errorf("expected: %q, got: %q", expected, output)
@ -86,14 +86,14 @@ func TestValidArgsFuncSingleCmdInvalidArg(t *testing.T) {
} }
// Check completing with wrong number of args // Check completing with wrong number of args
output, err := executeCommand(rootCmd, CompRequestCmd, "unexpectedArg", "t") output, err := executeCommand(rootCmd, ShellCompRequestCmd, "unexpectedArg", "t")
if err != nil { if err != nil {
t.Errorf("Unexpected error: %v", err) t.Errorf("Unexpected error: %v", err)
} }
expected := strings.Join([]string{ expected := strings.Join([]string{
":4", ":4",
"Completion ended with directive: BashCompDirectiveNoFileComp", ""}, "\n") "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")
if output != expected { if output != expected {
t.Errorf("expected: %q, got: %q", expected, output) t.Errorf("expected: %q, got: %q", expected, output)
@ -115,7 +115,7 @@ func TestValidArgsFuncChildCmds(t *testing.T) {
rootCmd.AddCommand(child1Cmd, child2Cmd) rootCmd.AddCommand(child1Cmd, child2Cmd)
// Test completion of first sub-command with empty argument // Test completion of first sub-command with empty argument
output, err := executeCommand(rootCmd, CompRequestCmd, "child1", "") output, err := executeCommand(rootCmd, ShellCompRequestCmd, "child1", "")
if err != nil { if err != nil {
t.Errorf("Unexpected error: %v", err) t.Errorf("Unexpected error: %v", err)
} }
@ -124,14 +124,14 @@ func TestValidArgsFuncChildCmds(t *testing.T) {
"one", "one",
"two", "two",
":0", ":0",
"Completion ended with directive: BashCompDirectiveDefault", ""}, "\n") "Completion ended with directive: ShellCompDirectiveDefault", ""}, "\n")
if output != expected { if output != expected {
t.Errorf("expected: %q, got: %q", expected, output) t.Errorf("expected: %q, got: %q", expected, output)
} }
// Test completion of first sub-command with a prefix to complete // Test completion of first sub-command with a prefix to complete
output, err = executeCommand(rootCmd, CompRequestCmd, "child1", "t") output, err = executeCommand(rootCmd, ShellCompRequestCmd, "child1", "t")
if err != nil { if err != nil {
t.Errorf("Unexpected error: %v", err) t.Errorf("Unexpected error: %v", err)
} }
@ -139,28 +139,28 @@ func TestValidArgsFuncChildCmds(t *testing.T) {
expected = strings.Join([]string{ expected = strings.Join([]string{
"two", "two",
":0", ":0",
"Completion ended with directive: BashCompDirectiveDefault", ""}, "\n") "Completion ended with directive: ShellCompDirectiveDefault", ""}, "\n")
if output != expected { if output != expected {
t.Errorf("expected: %q, got: %q", expected, output) t.Errorf("expected: %q, got: %q", expected, output)
} }
// Check completing with wrong number of args // Check completing with wrong number of args
output, err = executeCommand(rootCmd, CompRequestCmd, "child1", "unexpectedArg", "t") output, err = executeCommand(rootCmd, ShellCompRequestCmd, "child1", "unexpectedArg", "t")
if err != nil { if err != nil {
t.Errorf("Unexpected error: %v", err) t.Errorf("Unexpected error: %v", err)
} }
expected = strings.Join([]string{ expected = strings.Join([]string{
":4", ":4",
"Completion ended with directive: BashCompDirectiveNoFileComp", ""}, "\n") "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")
if output != expected { if output != expected {
t.Errorf("expected: %q, got: %q", expected, output) t.Errorf("expected: %q, got: %q", expected, output)
} }
// Test completion of second sub-command with empty argument // Test completion of second sub-command with empty argument
output, err = executeCommand(rootCmd, CompRequestCmd, "child2", "") output, err = executeCommand(rootCmd, ShellCompRequestCmd, "child2", "")
if err != nil { if err != nil {
t.Errorf("Unexpected error: %v", err) t.Errorf("Unexpected error: %v", err)
} }
@ -169,13 +169,13 @@ func TestValidArgsFuncChildCmds(t *testing.T) {
"three", "three",
"four", "four",
":0", ":0",
"Completion ended with directive: BashCompDirectiveDefault", ""}, "\n") "Completion ended with directive: ShellCompDirectiveDefault", ""}, "\n")
if output != expected { if output != expected {
t.Errorf("expected: %q, got: %q", expected, output) t.Errorf("expected: %q, got: %q", expected, output)
} }
output, err = executeCommand(rootCmd, CompRequestCmd, "child2", "t") output, err = executeCommand(rootCmd, ShellCompRequestCmd, "child2", "t")
if err != nil { if err != nil {
t.Errorf("Unexpected error: %v", err) t.Errorf("Unexpected error: %v", err)
} }
@ -183,21 +183,21 @@ func TestValidArgsFuncChildCmds(t *testing.T) {
expected = strings.Join([]string{ expected = strings.Join([]string{
"three", "three",
":0", ":0",
"Completion ended with directive: BashCompDirectiveDefault", ""}, "\n") "Completion ended with directive: ShellCompDirectiveDefault", ""}, "\n")
if output != expected { if output != expected {
t.Errorf("expected: %q, got: %q", expected, output) t.Errorf("expected: %q, got: %q", expected, output)
} }
// Check completing with wrong number of args // Check completing with wrong number of args
output, err = executeCommand(rootCmd, CompRequestCmd, "child2", "unexpectedArg", "t") output, err = executeCommand(rootCmd, ShellCompRequestCmd, "child2", "unexpectedArg", "t")
if err != nil { if err != nil {
t.Errorf("Unexpected error: %v", err) t.Errorf("Unexpected error: %v", err)
} }
expected = strings.Join([]string{ expected = strings.Join([]string{
":4", ":4",
"Completion ended with directive: BashCompDirectiveNoFileComp", ""}, "\n") "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")
if output != expected { if output != expected {
t.Errorf("expected: %q, got: %q", expected, output) t.Errorf("expected: %q, got: %q", expected, output)
@ -215,7 +215,7 @@ func TestValidArgsFuncAliases(t *testing.T) {
rootCmd.AddCommand(child) rootCmd.AddCommand(child)
// Test completion of first sub-command with empty argument // Test completion of first sub-command with empty argument
output, err := executeCommand(rootCmd, CompRequestCmd, "son", "") output, err := executeCommand(rootCmd, ShellCompRequestCmd, "son", "")
if err != nil { if err != nil {
t.Errorf("Unexpected error: %v", err) t.Errorf("Unexpected error: %v", err)
} }
@ -224,14 +224,14 @@ func TestValidArgsFuncAliases(t *testing.T) {
"one", "one",
"two", "two",
":0", ":0",
"Completion ended with directive: BashCompDirectiveDefault", ""}, "\n") "Completion ended with directive: ShellCompDirectiveDefault", ""}, "\n")
if output != expected { if output != expected {
t.Errorf("expected: %q, got: %q", expected, output) t.Errorf("expected: %q, got: %q", expected, output)
} }
// Test completion of first sub-command with a prefix to complete // Test completion of first sub-command with a prefix to complete
output, err = executeCommand(rootCmd, CompRequestCmd, "daughter", "t") output, err = executeCommand(rootCmd, ShellCompRequestCmd, "daughter", "t")
if err != nil { if err != nil {
t.Errorf("Unexpected error: %v", err) t.Errorf("Unexpected error: %v", err)
} }
@ -239,21 +239,21 @@ func TestValidArgsFuncAliases(t *testing.T) {
expected = strings.Join([]string{ expected = strings.Join([]string{
"two", "two",
":0", ":0",
"Completion ended with directive: BashCompDirectiveDefault", ""}, "\n") "Completion ended with directive: ShellCompDirectiveDefault", ""}, "\n")
if output != expected { if output != expected {
t.Errorf("expected: %q, got: %q", expected, output) t.Errorf("expected: %q, got: %q", expected, output)
} }
// Check completing with wrong number of args // Check completing with wrong number of args
output, err = executeCommand(rootCmd, CompRequestCmd, "son", "unexpectedArg", "t") output, err = executeCommand(rootCmd, ShellCompRequestCmd, "son", "unexpectedArg", "t")
if err != nil { if err != nil {
t.Errorf("Unexpected error: %v", err) t.Errorf("Unexpected error: %v", err)
} }
expected = strings.Join([]string{ expected = strings.Join([]string{
":4", ":4",
"Completion ended with directive: BashCompDirectiveNoFileComp", ""}, "\n") "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")
if output != expected { if output != expected {
t.Errorf("expected: %q, got: %q", expected, output) t.Errorf("expected: %q, got: %q", expected, output)
@ -297,28 +297,28 @@ func TestFlagCompletionInGo(t *testing.T) {
Run: emptyRun, Run: emptyRun,
} }
rootCmd.Flags().IntP("introot", "i", -1, "help message for flag introot") rootCmd.Flags().IntP("introot", "i", -1, "help message for flag introot")
rootCmd.RegisterFlagCompletionFunc("introot", func(cmd *Command, args []string, toComplete string) ([]string, BashCompDirective) { rootCmd.RegisterFlagCompletionFunc("introot", func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective) {
completions := []string{} completions := []string{}
for _, comp := range []string{"1", "2", "10"} { for _, comp := range []string{"1", "2", "10"} {
if strings.HasPrefix(comp, toComplete) { if strings.HasPrefix(comp, toComplete) {
completions = append(completions, comp) completions = append(completions, comp)
} }
} }
return completions, BashCompDirectiveDefault return completions, ShellCompDirectiveDefault
}) })
rootCmd.Flags().String("filename", "", "Enter a filename") rootCmd.Flags().String("filename", "", "Enter a filename")
rootCmd.RegisterFlagCompletionFunc("filename", func(cmd *Command, args []string, toComplete string) ([]string, BashCompDirective) { rootCmd.RegisterFlagCompletionFunc("filename", func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective) {
completions := []string{} completions := []string{}
for _, comp := range []string{"file.yaml", "myfile.json", "file.xml"} { for _, comp := range []string{"file.yaml", "myfile.json", "file.xml"} {
if strings.HasPrefix(comp, toComplete) { if strings.HasPrefix(comp, toComplete) {
completions = append(completions, comp) completions = append(completions, comp)
} }
} }
return completions, BashCompDirectiveNoSpace | BashCompDirectiveNoFileComp return completions, ShellCompDirectiveNoSpace | ShellCompDirectiveNoFileComp
}) })
// Test completing an empty string // Test completing an empty string
output, err := executeCommand(rootCmd, CompRequestCmd, "--introot", "") output, err := executeCommand(rootCmd, ShellCompRequestCmd, "--introot", "")
if err != nil { if err != nil {
t.Errorf("Unexpected error: %v", err) t.Errorf("Unexpected error: %v", err)
} }
@ -328,14 +328,14 @@ func TestFlagCompletionInGo(t *testing.T) {
"2", "2",
"10", "10",
":0", ":0",
"Completion ended with directive: BashCompDirectiveDefault", ""}, "\n") "Completion ended with directive: ShellCompDirectiveDefault", ""}, "\n")
if output != expected { if output != expected {
t.Errorf("expected: %q, got: %q", expected, output) t.Errorf("expected: %q, got: %q", expected, output)
} }
// Check completing with a prefix // Check completing with a prefix
output, err = executeCommand(rootCmd, CompRequestCmd, "--introot", "1") output, err = executeCommand(rootCmd, ShellCompRequestCmd, "--introot", "1")
if err != nil { if err != nil {
t.Errorf("Unexpected error: %v", err) t.Errorf("Unexpected error: %v", err)
} }
@ -344,14 +344,14 @@ func TestFlagCompletionInGo(t *testing.T) {
"1", "1",
"10", "10",
":0", ":0",
"Completion ended with directive: BashCompDirectiveDefault", ""}, "\n") "Completion ended with directive: ShellCompDirectiveDefault", ""}, "\n")
if output != expected { if output != expected {
t.Errorf("expected: %q, got: %q", expected, output) t.Errorf("expected: %q, got: %q", expected, output)
} }
// Test completing an empty string // Test completing an empty string
output, err = executeCommand(rootCmd, CompRequestCmd, "--filename", "") output, err = executeCommand(rootCmd, ShellCompRequestCmd, "--filename", "")
if err != nil { if err != nil {
t.Errorf("Unexpected error: %v", err) t.Errorf("Unexpected error: %v", err)
} }
@ -361,14 +361,14 @@ func TestFlagCompletionInGo(t *testing.T) {
"myfile.json", "myfile.json",
"file.xml", "file.xml",
":6", ":6",
"Completion ended with directive: BashCompDirectiveNoSpace, BashCompDirectiveNoFileComp", ""}, "\n") "Completion ended with directive: ShellCompDirectiveNoSpace, ShellCompDirectiveNoFileComp", ""}, "\n")
if output != expected { if output != expected {
t.Errorf("expected: %q, got: %q", expected, output) t.Errorf("expected: %q, got: %q", expected, output)
} }
// Check completing with a prefix // Check completing with a prefix
output, err = executeCommand(rootCmd, CompRequestCmd, "--filename", "f") output, err = executeCommand(rootCmd, ShellCompRequestCmd, "--filename", "f")
if err != nil { if err != nil {
t.Errorf("Unexpected error: %v", err) t.Errorf("Unexpected error: %v", err)
} }
@ -377,7 +377,7 @@ func TestFlagCompletionInGo(t *testing.T) {
"file.yaml", "file.yaml",
"file.xml", "file.xml",
":6", ":6",
"Completion ended with directive: BashCompDirectiveNoSpace, BashCompDirectiveNoFileComp", ""}, "\n") "Completion ended with directive: ShellCompDirectiveNoSpace, ShellCompDirectiveNoFileComp", ""}, "\n")
if output != expected { if output != expected {
t.Errorf("expected: %q, got: %q", expected, output) t.Errorf("expected: %q, got: %q", expected, output)