diff --git a/testprog/testprog.go b/testprog/testprog.go index c33c078..31c8766 100644 --- a/testprog/testprog.go +++ b/testprog/testprog.go @@ -2,6 +2,7 @@ package main import ( "fmt" + "log" "os" "strings" @@ -211,6 +212,26 @@ var manyCompsCmd = &cobra.Command{ Run: func(cmd *cobra.Command, args []string) {}, } +// ====================================================== +// Command that provide completions containing a space +// ====================================================== +var compWithSpaceCmd = &cobra.Command{ + Use: "space", + Short: "Completions that contain a space", + ValidArgsFunction: func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { + var comps []string + if len(args) == 0 { + comps = []string{"with space", "desc for with space\tDescription for comp with space"} + } + return comps, cobra.ShellCompDirectiveNoFileComp + }, + Run: func(cmd *cobra.Command, args []string) { + if len(args) > 0 && args[0] != "with space" && args[0] != "with space and desc" { + log.Fatal("Got wrong arg") + } + }, +} + func setFlags() { rootCmd.Flags().String("customComp", "", "test custom comp for flags") rootCmd.RegisterFlagCompletionFunc("customComp", func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { @@ -236,6 +257,7 @@ func main() { errorCmd, dashArgCmd, manyCompsCmd, + compWithSpaceCmd, ) prefixCmd.AddCommand( diff --git a/tests/bash/comp-tests.bash b/tests/bash/comp-tests.bash index f894605..d2f3a81 100755 --- a/tests/bash/comp-tests.bash +++ b/tests/bash/comp-tests.bash @@ -212,6 +212,17 @@ _completionTests_timing "testprog manycomps " 0.2 "insert-completions no descs" unset COMP_TYPE +# Test that completions can contain a space. +# We only support this for bash completion v2 +# https://github.com/spf13/cobra/issues/1740 +# https://github.com/spf13/cobra/pull/1743 +if [ "$BASHCOMP_VERSION" = bash2 ]; then + # Disable sorting as it would mistakenly split the completion on the space + BASH_COMP_NO_SORT=1 + _completionTests_verifyCompletion "testprog space w" "with\ space" nofile + unset BASH_COMP_NO_SORT +fi + # Test descriptions of bash v2 if [ "$BASHCOMP_VERSION" = bash2 ]; then