Create 'completion' command automatically (#1192)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Make it easier for programs to provide shell completion by creating the 'completion' command automatically. If a 'completion' command is already provided by the program, Cobra will use that one instead.
authored by Marc Khouzam · committed by GitHub · parent ded486a · Browse files · 6 files·+2923 added−2520 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
6 files+2923 added−2520 removed
- other:+2923 added−2520 removed
Provenance
- Commit
b312f0a- Tree
1613b15- Author
Marc Khouzam <marc.khouzam@montreal.ca>- Committer
GitHub <noreply@github.com>- Parent
ded486a
6 files changed+2923 added−2520 removed
modified:command.go+6 added-2 removed
166 unmodified lines167 168 //FParseErrWhitelist flag parse errors to be ignored169 FParseErrWhitelist FParseErrWhitelist170 171+ // CompletionOptions is a set of options to control the handling of shell completion172+ CompletionOptions CompletionOptions173+174 // commandsAreSorted defines, if command slice are sorted or not.175 commandsAreSorted bool176 // commandCalledAs is the name or alias value used to call this command.177 commandCalledAs struct {738 unmodified lines916 if preExecHookFn != nil {917 preExecHookFn(c)918 }919 917- // initialize help as the last point possible to allow for user918- // overriding920+ // initialize help at the last point to allow for user overriding921 c.InitDefaultHelpCmd()922+ // initialize completion at the last point to allow for user overriding923+ c.initDefaultCompletionCmd()924 925 args := c.args926 927 // Workaround FAIL with "go test -v" or "cobra.test -test.v", see #155743 unmodified linesadded:completions_test.go+2160 added
1+package cobra2+3+import (4+ "bytes"5+ "strings"6+ "testing"7+)8+9+func validArgsFunc(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective) {10+ if len(args) != 0 {11+ return nil, ShellCompDirectiveNoFileComp12+ }13+14+ var completions []string15+ for _, comp := range []string{"one\tThe first", "two\tThe second"} {16+ if strings.HasPrefix(comp, toComplete) {17+ completions = append(completions, comp)18+ }19+ }20+ return completions, ShellCompDirectiveDefault21+}22+23+func validArgsFunc2(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective) {24+ if len(args) != 0 {25+ return nil, ShellCompDirectiveNoFileComp26+ }27+28+ var completions []string29+ for _, comp := range []string{"three\tThe third", "four\tThe fourth"} {30+ if strings.HasPrefix(comp, toComplete) {31+ completions = append(completions, comp)32+ }33+ }34+ return completions, ShellCompDirectiveDefault35+}36+37+func TestCmdNameCompletionInGo(t *testing.T) {38+ rootCmd := &Command{39+ Use: "root",40+ Run: emptyRun,41+ }42+ childCmd1 := &Command{43+ Use: "firstChild",44+ Short: "First command",45+ Run: emptyRun,46+ }47+ childCmd2 := &Command{48+ Use: "secondChild",49+ Run: emptyRun,50+ }51+ hiddenCmd := &Command{52+ Use: "testHidden",53+ Hidden: true, // Not completed54+ Run: emptyRun,55+ }56+ deprecatedCmd := &Command{57+ Use: "testDeprecated",58+ Deprecated: "deprecated", // Not completed59+ Run: emptyRun,60+ }61+ aliasedCmd := &Command{62+ Use: "aliased",63+ Short: "A command with aliases",64+ Aliases: []string{"testAlias", "testSynonym"}, // Not completed65+ Run: emptyRun,66+ }67+68+ rootCmd.AddCommand(childCmd1, childCmd2, hiddenCmd, deprecatedCmd, aliasedCmd)69+70+ // Test that sub-command names are completed71+ output, err := executeCommand(rootCmd, ShellCompNoDescRequestCmd, "")72+ if err != nil {73+ t.Errorf("Unexpected error: %v", err)74+ }75+76+ expected := strings.Join([]string{77+ "aliased",78+ "completion",79+ "firstChild",80+ "help",81+ "secondChild",82+ ":4",83+ "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")84+85+ if output != expected {86+ t.Errorf("expected: %q, got: %q", expected, output)87+ }88+89+ // Test that sub-command names are completed with prefix90+ output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "s")91+ if err != nil {92+ t.Errorf("Unexpected error: %v", err)93+ }94+95+ expected = strings.Join([]string{96+ "secondChild",97+ ":4",98+ "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")99+100+ if output != expected {101+ t.Errorf("expected: %q, got: %q", expected, output)102+ }103+104+ // Test that even with no valid sub-command matches, hidden, deprecated and105+ // aliases are not completed106+ output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "test")107+ if err != nil {108+ t.Errorf("Unexpected error: %v", err)109+ }110+111+ expected = strings.Join([]string{112+ ":4",113+ "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")114+115+ if output != expected {116+ t.Errorf("expected: %q, got: %q", expected, output)117+ }118+119+ // Test that sub-command names are completed with description120+ output, err = executeCommand(rootCmd, ShellCompRequestCmd, "")121+ if err != nil {122+ t.Errorf("Unexpected error: %v", err)123+ }124+125+ expected = strings.Join([]string{126+ "aliased\tA command with aliases",127+ "completion\tgenerate the autocompletion script for the specified shell",128+ "firstChild\tFirst command",129+ "help\tHelp about any command",130+ "secondChild",131+ ":4",132+ "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")133+134+ if output != expected {135+ t.Errorf("expected: %q, got: %q", expected, output)136+ }137+}138+139+func TestNoCmdNameCompletionInGo(t *testing.T) {140+ rootCmd := &Command{141+ Use: "root",142+ Run: emptyRun,143+ }144+ rootCmd.Flags().String("localroot", "", "local root flag")145+146+ childCmd1 := &Command{147+ Use: "childCmd1",148+ Short: "First command",149+ Args: MinimumNArgs(0),150+ Run: emptyRun,151+ }152+ rootCmd.AddCommand(childCmd1)153+ childCmd1.PersistentFlags().StringP("persistent", "p", "", "persistent flag")154+ persistentFlag := childCmd1.PersistentFlags().Lookup("persistent")155+ childCmd1.Flags().StringP("nonPersistent", "n", "", "non-persistent flag")156+ nonPersistentFlag := childCmd1.Flags().Lookup("nonPersistent")157+158+ childCmd2 := &Command{159+ Use: "childCmd2",160+ Run: emptyRun,161+ }162+ childCmd1.AddCommand(childCmd2)163+164+ // Test that sub-command names are not completed if there is an argument already165+ output, err := executeCommand(rootCmd, ShellCompNoDescRequestCmd, "childCmd1", "arg1", "")166+ if err != nil {167+ t.Errorf("Unexpected error: %v", err)168+ }169+170+ expected := strings.Join([]string{171+ ":0",172+ "Completion ended with directive: ShellCompDirectiveDefault", ""}, "\n")173+174+ if output != expected {175+ t.Errorf("expected: %q, got: %q", expected, output)176+ }177+178+ // Test that sub-command names are not completed if a local non-persistent flag is present179+ output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "childCmd1", "--nonPersistent", "value", "")180+ if err != nil {181+ t.Errorf("Unexpected error: %v", err)182+ }183+ // Reset the flag for the next command184+ nonPersistentFlag.Changed = false185+186+ expected = strings.Join([]string{187+ ":0",188+ "Completion ended with directive: ShellCompDirectiveDefault", ""}, "\n")189+190+ if output != expected {191+ t.Errorf("expected: %q, got: %q", expected, output)192+ }193+194+ // Test that sub-command names are completed if a local non-persistent flag is present and TraverseChildren is set to true195+ // set TraverseChildren to true on the root cmd196+ rootCmd.TraverseChildren = true197+198+ output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "--localroot", "value", "")199+ if err != nil {200+ t.Errorf("Unexpected error: %v", err)201+ }202+ // Reset TraverseChildren for next command203+ rootCmd.TraverseChildren = false204+205+ expected = strings.Join([]string{206+ "childCmd1",207+ "completion",208+ "help",209+ ":4",210+ "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")211+212+ if output != expected {213+ t.Errorf("expected: %q, got: %q", expected, output)214+ }215+216+ // Test that sub-command names from a child cmd are completed if a local non-persistent flag is present217+ // and TraverseChildren is set to true on the root cmd218+ rootCmd.TraverseChildren = true219+220+ output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "--localroot", "value", "childCmd1", "--nonPersistent", "value", "")221+ if err != nil {222+ t.Errorf("Unexpected error: %v", err)223+ }224+ // Reset TraverseChildren for next command225+ rootCmd.TraverseChildren = false226+ // Reset the flag for the next command227+ nonPersistentFlag.Changed = false228+229+ expected = strings.Join([]string{230+ "childCmd2",231+ ":4",232+ "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")233+234+ if output != expected {235+ t.Errorf("expected: %q, got: %q", expected, output)236+ }237+238+ // Test that we don't use Traverse when we shouldn't.239+ // This command should not return a completion since the command line is invalid without TraverseChildren.240+ output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "--localroot", "value", "childCmd1", "")241+ if err != nil {242+ t.Errorf("Unexpected error: %v", err)243+ }244+245+ expected = strings.Join([]string{246+ ":0",247+ "Completion ended with directive: ShellCompDirectiveDefault", ""}, "\n")248+249+ if output != expected {250+ t.Errorf("expected: %q, got: %q", expected, output)251+ }252+253+ // Test that sub-command names are not completed if a local non-persistent short flag is present254+ output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "childCmd1", "-n", "value", "")255+ if err != nil {256+ t.Errorf("Unexpected error: %v", err)257+ }258+ // Reset the flag for the next command259+ nonPersistentFlag.Changed = false260+261+ expected = strings.Join([]string{262+ ":0",263+ "Completion ended with directive: ShellCompDirectiveDefault", ""}, "\n")264+265+ if output != expected {266+ t.Errorf("expected: %q, got: %q", expected, output)267+ }268+269+ // Test that sub-command names are completed with a persistent flag270+ output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "childCmd1", "--persistent", "value", "")271+ if err != nil {272+ t.Errorf("Unexpected error: %v", err)273+ }274+ // Reset the flag for the next command275+ persistentFlag.Changed = false276+277+ expected = strings.Join([]string{278+ "childCmd2",279+ ":4",280+ "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")281+282+ if output != expected {283+ t.Errorf("expected: %q, got: %q", expected, output)284+ }285+286+ // Test that sub-command names are completed with a persistent short flag287+ output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "childCmd1", "-p", "value", "")288+ if err != nil {289+ t.Errorf("Unexpected error: %v", err)290+ }291+ // Reset the flag for the next command292+ persistentFlag.Changed = false293+294+ expected = strings.Join([]string{295+ "childCmd2",296+ ":4",297+ "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")298+299+ if output != expected {300+ t.Errorf("expected: %q, got: %q", expected, output)301+ }302+}303+304+func TestValidArgsCompletionInGo(t *testing.T) {305+ rootCmd := &Command{306+ Use: "root",307+ ValidArgs: []string{"one", "two", "three"},308+ Args: MinimumNArgs(1),309+ }310+311+ // Test that validArgs are completed312+ output, err := executeCommand(rootCmd, ShellCompNoDescRequestCmd, "")313+ if err != nil {314+ t.Errorf("Unexpected error: %v", err)315+ }316+317+ expected := strings.Join([]string{318+ "one",319+ "two",320+ "three",321+ ":4",322+ "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")323+324+ if output != expected {325+ t.Errorf("expected: %q, got: %q", expected, output)326+ }327+328+ // Test that validArgs are completed with prefix329+ output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "o")330+ if err != nil {331+ t.Errorf("Unexpected error: %v", err)332+ }333+334+ expected = strings.Join([]string{335+ "one",336+ ":4",337+ "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")338+339+ if output != expected {340+ t.Errorf("expected: %q, got: %q", expected, output)341+ }342+343+ // Test that validArgs don't repeat344+ output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "one", "")345+ if err != nil {346+ t.Errorf("Unexpected error: %v", err)347+ }348+349+ expected = strings.Join([]string{350+ ":0",351+ "Completion ended with directive: ShellCompDirectiveDefault", ""}, "\n")352+353+ if output != expected {354+ t.Errorf("expected: %q, got: %q", expected, output)355+ }356+}357+358+func TestValidArgsAndCmdCompletionInGo(t *testing.T) {359+ rootCmd := &Command{360+ Use: "root",361+ ValidArgs: []string{"one", "two"},362+ Run: emptyRun,363+ }364+365+ childCmd := &Command{366+ Use: "thechild",367+ Run: emptyRun,368+ }369+370+ rootCmd.AddCommand(childCmd)371+372+ // Test that both sub-commands and validArgs are completed373+ output, err := executeCommand(rootCmd, ShellCompNoDescRequestCmd, "")374+ if err != nil {375+ t.Errorf("Unexpected error: %v", err)376+ }377+378+ expected := strings.Join([]string{379+ "completion",380+ "help",381+ "thechild",382+ "one",383+ "two",384+ ":4",385+ "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")386+387+ if output != expected {388+ t.Errorf("expected: %q, got: %q", expected, output)389+ }390+391+ // Test that both sub-commands and validArgs are completed with prefix392+ output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "t")393+ if err != nil {394+ t.Errorf("Unexpected error: %v", err)395+ }396+397+ expected = strings.Join([]string{398+ "thechild",399+ "two",400+ ":4",401+ "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")402+403+ if output != expected {404+ t.Errorf("expected: %q, got: %q", expected, output)405+ }406+}407+408+func TestValidArgsFuncAndCmdCompletionInGo(t *testing.T) {409+ rootCmd := &Command{410+ Use: "root",411+ ValidArgsFunction: validArgsFunc,412+ Run: emptyRun,413+ }414+415+ childCmd := &Command{416+ Use: "thechild",417+ Short: "The child command",418+ Run: emptyRun,419+ }420+421+ rootCmd.AddCommand(childCmd)422+423+ // Test that both sub-commands and validArgsFunction are completed424+ output, err := executeCommand(rootCmd, ShellCompNoDescRequestCmd, "")425+ if err != nil {426+ t.Errorf("Unexpected error: %v", err)427+ }428+429+ expected := strings.Join([]string{430+ "completion",431+ "help",432+ "thechild",433+ "one",434+ "two",435+ ":0",436+ "Completion ended with directive: ShellCompDirectiveDefault", ""}, "\n")437+438+ if output != expected {439+ t.Errorf("expected: %q, got: %q", expected, output)440+ }441+442+ // Test that both sub-commands and validArgs are completed with prefix443+ output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "t")444+ if err != nil {445+ t.Errorf("Unexpected error: %v", err)446+ }447+448+ expected = strings.Join([]string{449+ "thechild",450+ "two",451+ ":0",452+ "Completion ended with directive: ShellCompDirectiveDefault", ""}, "\n")453+454+ if output != expected {455+ t.Errorf("expected: %q, got: %q", expected, output)456+ }457+458+ // Test that both sub-commands and validArgs are completed with description459+ output, err = executeCommand(rootCmd, ShellCompRequestCmd, "t")460+ if err != nil {461+ t.Errorf("Unexpected error: %v", err)462+ }463+464+ expected = strings.Join([]string{465+ "thechild\tThe child command",466+ "two\tThe second",467+ ":0",468+ "Completion ended with directive: ShellCompDirectiveDefault", ""}, "\n")469+470+ if output != expected {471+ t.Errorf("expected: %q, got: %q", expected, output)472+ }473+}474+475+func TestFlagNameCompletionInGo(t *testing.T) {476+ rootCmd := &Command{477+ Use: "root",478+ Run: emptyRun,479+ }480+ childCmd := &Command{481+ Use: "childCmd",482+ Run: emptyRun,483+ }484+ rootCmd.AddCommand(childCmd)485+486+ rootCmd.Flags().IntP("first", "f", -1, "first flag")487+ rootCmd.PersistentFlags().BoolP("second", "s", false, "second flag")488+ childCmd.Flags().String("subFlag", "", "sub flag")489+490+ // Test that flag names are not shown if the user has not given the '-' prefix491+ output, err := executeCommand(rootCmd, ShellCompNoDescRequestCmd, "")492+ if err != nil {493+ t.Errorf("Unexpected error: %v", err)494+ }495+496+ expected := strings.Join([]string{497+ "childCmd",498+ "completion",499+ "help",500+ ":4",501+ "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")502+503+ if output != expected {504+ t.Errorf("expected: %q, got: %q", expected, output)505+ }506+507+ // Test that flag names are completed508+ output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "-")509+ if err != nil {510+ t.Errorf("Unexpected error: %v", err)511+ }512+513+ expected = strings.Join([]string{514+ "--first",515+ "-f",516+ "--second",517+ "-s",518+ ":4",519+ "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")520+521+ if output != expected {522+ t.Errorf("expected: %q, got: %q", expected, output)523+ }524+525+ // Test that flag names are completed when a prefix is given526+ output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "--f")527+ if err != nil {528+ t.Errorf("Unexpected error: %v", err)529+ }530+531+ expected = strings.Join([]string{532+ "--first",533+ ":4",534+ "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")535+536+ if output != expected {537+ t.Errorf("expected: %q, got: %q", expected, output)538+ }539+540+ // Test that flag names are completed in a sub-cmd541+ output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "childCmd", "-")542+ if err != nil {543+ t.Errorf("Unexpected error: %v", err)544+ }545+546+ expected = strings.Join([]string{547+ "--second",548+ "-s",549+ "--subFlag",550+ ":4",551+ "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")552+553+ if output != expected {554+ t.Errorf("expected: %q, got: %q", expected, output)555+ }556+}557+558+func TestFlagNameCompletionInGoWithDesc(t *testing.T) {559+ rootCmd := &Command{560+ Use: "root",561+ Run: emptyRun,562+ }563+ childCmd := &Command{564+ Use: "childCmd",565+ Short: "first command",566+ Run: emptyRun,567+ }568+ rootCmd.AddCommand(childCmd)569+570+ rootCmd.Flags().IntP("first", "f", -1, "first flag\nlonger description for flag")571+ rootCmd.PersistentFlags().BoolP("second", "s", false, "second flag")572+ childCmd.Flags().String("subFlag", "", "sub flag")573+574+ // Test that flag names are not shown if the user has not given the '-' prefix575+ output, err := executeCommand(rootCmd, ShellCompRequestCmd, "")576+ if err != nil {577+ t.Errorf("Unexpected error: %v", err)578+ }579+580+ expected := strings.Join([]string{581+ "childCmd\tfirst command",582+ "completion\tgenerate the autocompletion script for the specified shell",583+ "help\tHelp about any command",584+ ":4",585+ "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")586+587+ if output != expected {588+ t.Errorf("expected: %q, got: %q", expected, output)589+ }590+591+ // Test that flag names are completed592+ output, err = executeCommand(rootCmd, ShellCompRequestCmd, "-")593+ if err != nil {594+ t.Errorf("Unexpected error: %v", err)595+ }596+597+ expected = strings.Join([]string{598+ "--first\tfirst flag",599+ "-f\tfirst flag",600+ "--second\tsecond flag",601+ "-s\tsecond flag",602+ ":4",603+ "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")604+605+ if output != expected {606+ t.Errorf("expected: %q, got: %q", expected, output)607+ }608+609+ // Test that flag names are completed when a prefix is given610+ output, err = executeCommand(rootCmd, ShellCompRequestCmd, "--f")611+ if err != nil {612+ t.Errorf("Unexpected error: %v", err)613+ }614+615+ expected = strings.Join([]string{616+ "--first\tfirst flag",617+ ":4",618+ "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")619+620+ if output != expected {621+ t.Errorf("expected: %q, got: %q", expected, output)622+ }623+624+ // Test that flag names are completed in a sub-cmd625+ output, err = executeCommand(rootCmd, ShellCompRequestCmd, "childCmd", "-")626+ if err != nil {627+ t.Errorf("Unexpected error: %v", err)628+ }629+630+ expected = strings.Join([]string{631+ "--second\tsecond flag",632+ "-s\tsecond flag",633+ "--subFlag\tsub flag",634+ ":4",635+ "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")636+637+ if output != expected {638+ t.Errorf("expected: %q, got: %q", expected, output)639+ }640+}641+642+func TestFlagNameCompletionRepeat(t *testing.T) {643+ rootCmd := &Command{644+ Use: "root",645+ Run: emptyRun,646+ }647+ childCmd := &Command{648+ Use: "childCmd",649+ Short: "first command",650+ Run: emptyRun,651+ }652+ rootCmd.AddCommand(childCmd)653+654+ rootCmd.Flags().IntP("first", "f", -1, "first flag")655+ firstFlag := rootCmd.Flags().Lookup("first")656+ rootCmd.Flags().BoolP("second", "s", false, "second flag")657+ secondFlag := rootCmd.Flags().Lookup("second")658+ rootCmd.Flags().StringArrayP("array", "a", nil, "array flag")659+ arrayFlag := rootCmd.Flags().Lookup("array")660+ rootCmd.Flags().IntSliceP("slice", "l", nil, "slice flag")661+ sliceFlag := rootCmd.Flags().Lookup("slice")662+ rootCmd.Flags().BoolSliceP("bslice", "b", nil, "bool slice flag")663+ bsliceFlag := rootCmd.Flags().Lookup("bslice")664+665+ // Test that flag names are not repeated unless they are an array or slice666+ output, err := executeCommand(rootCmd, ShellCompNoDescRequestCmd, "--first", "1", "--")667+ if err != nil {668+ t.Errorf("Unexpected error: %v", err)669+ }670+ // Reset the flag for the next command671+ firstFlag.Changed = false672+673+ expected := strings.Join([]string{674+ "--array",675+ "--bslice",676+ "--second",677+ "--slice",678+ ":4",679+ "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")680+681+ if output != expected {682+ t.Errorf("expected: %q, got: %q", expected, output)683+ }684+685+ // Test that flag names are not repeated unless they are an array or slice686+ output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "--first", "1", "--second=false", "--")687+ if err != nil {688+ t.Errorf("Unexpected error: %v", err)689+ }690+ // Reset the flag for the next command691+ firstFlag.Changed = false692+ secondFlag.Changed = false693+694+ expected = strings.Join([]string{695+ "--array",696+ "--bslice",697+ "--slice",698+ ":4",699+ "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")700+701+ if output != expected {702+ t.Errorf("expected: %q, got: %q", expected, output)703+ }704+705+ // Test that flag names are not repeated unless they are an array or slice706+ output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "--slice", "1", "--slice=2", "--array", "val", "--bslice", "true", "--")707+ if err != nil {708+ t.Errorf("Unexpected error: %v", err)709+ }710+ // Reset the flag for the next command711+ sliceFlag.Changed = false712+ arrayFlag.Changed = false713+ bsliceFlag.Changed = false714+715+ expected = strings.Join([]string{716+ "--array",717+ "--bslice",718+ "--first",719+ "--second",720+ "--slice",721+ ":4",722+ "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")723+724+ if output != expected {725+ t.Errorf("expected: %q, got: %q", expected, output)726+ }727+728+ // Test that flag names are not repeated unless they are an array or slice, using shortname729+ output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "-l", "1", "-l=2", "-a", "val", "-")730+ if err != nil {731+ t.Errorf("Unexpected error: %v", err)732+ }733+ // Reset the flag for the next command734+ sliceFlag.Changed = false735+ arrayFlag.Changed = false736+737+ expected = strings.Join([]string{738+ "--array",739+ "-a",740+ "--bslice",741+ "-b",742+ "--first",743+ "-f",744+ "--second",745+ "-s",746+ "--slice",747+ "-l",748+ ":4",749+ "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")750+751+ if output != expected {752+ t.Errorf("expected: %q, got: %q", expected, output)753+ }754+755+ // Test that flag names are not repeated unless they are an array or slice, using shortname with prefix756+ output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "-l", "1", "-l=2", "-a", "val", "-a")757+ if err != nil {758+ t.Errorf("Unexpected error: %v", err)759+ }760+ // Reset the flag for the next command761+ sliceFlag.Changed = false762+ arrayFlag.Changed = false763+764+ expected = strings.Join([]string{765+ "-a",766+ ":4",767+ "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")768+769+ if output != expected {770+ t.Errorf("expected: %q, got: %q", expected, output)771+ }772+}773+774+func TestRequiredFlagNameCompletionInGo(t *testing.T) {775+ rootCmd := &Command{776+ Use: "root",777+ ValidArgs: []string{"realArg"},778+ Run: emptyRun,779+ }780+ childCmd := &Command{781+ Use: "childCmd",782+ ValidArgsFunction: func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective) {783+ return []string{"subArg"}, ShellCompDirectiveNoFileComp784+ },785+ Run: emptyRun,786+ }787+ rootCmd.AddCommand(childCmd)788+789+ rootCmd.Flags().IntP("requiredFlag", "r", -1, "required flag")790+ assertNoErr(t, rootCmd.MarkFlagRequired("requiredFlag"))791+ requiredFlag := rootCmd.Flags().Lookup("requiredFlag")792+793+ rootCmd.PersistentFlags().IntP("requiredPersistent", "p", -1, "required persistent")794+ assertNoErr(t, rootCmd.MarkPersistentFlagRequired("requiredPersistent"))795+ requiredPersistent := rootCmd.PersistentFlags().Lookup("requiredPersistent")796+797+ rootCmd.Flags().StringP("release", "R", "", "Release name")798+799+ childCmd.Flags().BoolP("subRequired", "s", false, "sub required flag")800+ assertNoErr(t, childCmd.MarkFlagRequired("subRequired"))801+ childCmd.Flags().BoolP("subNotRequired", "n", false, "sub not required flag")802+803+ // Test that a required flag is suggested even without the - prefix804+ output, err := executeCommand(rootCmd, ShellCompNoDescRequestCmd, "")805+ if err != nil {806+ t.Errorf("Unexpected error: %v", err)807+ }808+809+ expected := strings.Join([]string{810+ "childCmd",811+ "completion",812+ "help",813+ "--requiredFlag",814+ "-r",815+ "--requiredPersistent",816+ "-p",817+ "realArg",818+ ":4",819+ "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")820+821+ if output != expected {822+ t.Errorf("expected: %q, got: %q", expected, output)823+ }824+825+ // Test that a required flag is suggested without other flags when using the '-' prefix826+ output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "-")827+ if err != nil {828+ t.Errorf("Unexpected error: %v", err)829+ }830+831+ expected = strings.Join([]string{832+ "--requiredFlag",833+ "-r",834+ "--requiredPersistent",835+ "-p",836+ ":4",837+ "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")838+839+ if output != expected {840+ t.Errorf("expected: %q, got: %q", expected, output)841+ }842+843+ // Test that if no required flag matches, the normal flags are suggested844+ output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "--relea")845+ if err != nil {846+ t.Errorf("Unexpected error: %v", err)847+ }848+849+ expected = strings.Join([]string{850+ "--release",851+ ":4",852+ "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")853+854+ if output != expected {855+ t.Errorf("expected: %q, got: %q", expected, output)856+ }857+858+ // Test required flags for sub-commands859+ output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "childCmd", "")860+ if err != nil {861+ t.Errorf("Unexpected error: %v", err)862+ }863+864+ expected = strings.Join([]string{865+ "--requiredPersistent",866+ "-p",867+ "--subRequired",868+ "-s",869+ "subArg",870+ ":4",871+ "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")872+873+ if output != expected {874+ t.Errorf("expected: %q, got: %q", expected, output)875+ }876+877+ output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "childCmd", "-")878+ if err != nil {879+ t.Errorf("Unexpected error: %v", err)880+ }881+882+ expected = strings.Join([]string{883+ "--requiredPersistent",884+ "-p",885+ "--subRequired",886+ "-s",887+ ":4",888+ "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")889+890+ if output != expected {891+ t.Errorf("expected: %q, got: %q", expected, output)892+ }893+894+ output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "childCmd", "--subNot")895+ if err != nil {896+ t.Errorf("Unexpected error: %v", err)897+ }898+899+ expected = strings.Join([]string{900+ "--subNotRequired",901+ ":4",902+ "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")903+904+ if output != expected {905+ t.Errorf("expected: %q, got: %q", expected, output)906+ }907+908+ // Test that when a required flag is present, it is not suggested anymore909+ output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "--requiredFlag", "1", "")910+ if err != nil {911+ t.Errorf("Unexpected error: %v", err)912+ }913+ // Reset the flag for the next command914+ requiredFlag.Changed = false915+916+ expected = strings.Join([]string{917+ "--requiredPersistent",918+ "-p",919+ "realArg",920+ ":4",921+ "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")922+923+ if output != expected {924+ t.Errorf("expected: %q, got: %q", expected, output)925+ }926+927+ // Test that when a persistent required flag is present, it is not suggested anymore928+ output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "--requiredPersistent", "1", "")929+ if err != nil {930+ t.Errorf("Unexpected error: %v", err)931+ }932+ // Reset the flag for the next command933+ requiredPersistent.Changed = false934+935+ expected = strings.Join([]string{936+ "childCmd",937+ "completion",938+ "help",939+ "--requiredFlag",940+ "-r",941+ "realArg",942+ ":4",943+ "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")944+945+ if output != expected {946+ t.Errorf("expected: %q, got: %q", expected, output)947+ }948+949+ // Test that when all required flags are present, normal completion is done950+ output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "--requiredFlag", "1", "--requiredPersistent", "1", "")951+ if err != nil {952+ t.Errorf("Unexpected error: %v", err)953+ }954+ // Reset the flags for the next command955+ requiredFlag.Changed = false956+ requiredPersistent.Changed = false957+958+ expected = strings.Join([]string{959+ "realArg",960+ ":4",961+ "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")962+963+ if output != expected {964+ t.Errorf("expected: %q, got: %q", expected, output)965+ }966+}967+968+func TestFlagFileExtFilterCompletionInGo(t *testing.T) {969+ rootCmd := &Command{970+ Use: "root",971+ Run: emptyRun,972+ }973+974+ // No extensions. Should be ignored.975+ rootCmd.Flags().StringP("file", "f", "", "file flag")976+ assertNoErr(t, rootCmd.MarkFlagFilename("file"))977+978+ // Single extension979+ rootCmd.Flags().StringP("log", "l", "", "log flag")980+ assertNoErr(t, rootCmd.MarkFlagFilename("log", "log"))981+982+ // Multiple extensions983+ rootCmd.Flags().StringP("yaml", "y", "", "yaml flag")984+ assertNoErr(t, rootCmd.MarkFlagFilename("yaml", "yaml", "yml"))985+986+ // Directly using annotation987+ rootCmd.Flags().StringP("text", "t", "", "text flag")988+ assertNoErr(t, rootCmd.Flags().SetAnnotation("text", BashCompFilenameExt, []string{"txt"}))989+990+ // Test that the completion logic returns the proper info for the completion991+ // script to handle the file filtering992+ output, err := executeCommand(rootCmd, ShellCompNoDescRequestCmd, "--file", "")993+ if err != nil {994+ t.Errorf("Unexpected error: %v", err)995+ }996+997+ expected := strings.Join([]string{998+ ":0",999+ "Completion ended with directive: ShellCompDirectiveDefault", ""}, "\n")1000+1001+ if output != expected {1002+ t.Errorf("expected: %q, got: %q", expected, output)1003+ }1004+1005+ output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "--log", "")1006+ if err != nil {1007+ t.Errorf("Unexpected error: %v", err)1008+ }1009+1010+ expected = strings.Join([]string{1011+ "log",1012+ ":8",1013+ "Completion ended with directive: ShellCompDirectiveFilterFileExt", ""}, "\n")1014+1015+ if output != expected {1016+ t.Errorf("expected: %q, got: %q", expected, output)1017+ }1018+1019+ output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "--yaml", "")1020+ if err != nil {1021+ t.Errorf("Unexpected error: %v", err)1022+ }1023+1024+ expected = strings.Join([]string{1025+ "yaml", "yml",1026+ ":8",1027+ "Completion ended with directive: ShellCompDirectiveFilterFileExt", ""}, "\n")1028+1029+ if output != expected {1030+ t.Errorf("expected: %q, got: %q", expected, output)1031+ }1032+1033+ output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "--yaml=")1034+ if err != nil {1035+ t.Errorf("Unexpected error: %v", err)1036+ }1037+1038+ expected = strings.Join([]string{1039+ "yaml", "yml",1040+ ":8",1041+ "Completion ended with directive: ShellCompDirectiveFilterFileExt", ""}, "\n")1042+1043+ if output != expected {1044+ t.Errorf("expected: %q, got: %q", expected, output)1045+ }1046+1047+ output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "-y", "")1048+ if err != nil {1049+ t.Errorf("Unexpected error: %v", err)1050+ }1051+1052+ expected = strings.Join([]string{1053+ "yaml", "yml",1054+ ":8",1055+ "Completion ended with directive: ShellCompDirectiveFilterFileExt", ""}, "\n")1056+1057+ if output != expected {1058+ t.Errorf("expected: %q, got: %q", expected, output)1059+ }1060+1061+ output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "-y=")1062+ if err != nil {1063+ t.Errorf("Unexpected error: %v", err)1064+ }1065+1066+ expected = strings.Join([]string{1067+ "yaml", "yml",1068+ ":8",1069+ "Completion ended with directive: ShellCompDirectiveFilterFileExt", ""}, "\n")1070+1071+ if output != expected {1072+ t.Errorf("expected: %q, got: %q", expected, output)1073+ }1074+1075+ output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "--text", "")1076+ if err != nil {1077+ t.Errorf("Unexpected error: %v", err)1078+ }1079+1080+ expected = strings.Join([]string{1081+ "txt",1082+ ":8",1083+ "Completion ended with directive: ShellCompDirectiveFilterFileExt", ""}, "\n")1084+1085+ if output != expected {1086+ t.Errorf("expected: %q, got: %q", expected, output)1087+ }1088+}1089+1090+func TestFlagDirFilterCompletionInGo(t *testing.T) {1091+ rootCmd := &Command{1092+ Use: "root",1093+ Run: emptyRun,1094+ }1095+1096+ // Filter directories1097+ rootCmd.Flags().StringP("dir", "d", "", "dir flag")1098+ assertNoErr(t, rootCmd.MarkFlagDirname("dir"))1099+1100+ // Filter directories within a directory1101+ rootCmd.Flags().StringP("subdir", "s", "", "subdir")1102+ assertNoErr(t, rootCmd.Flags().SetAnnotation("subdir", BashCompSubdirsInDir, []string{"themes"}))1103+1104+ // Multiple directory specification get ignored1105+ rootCmd.Flags().StringP("manydir", "m", "", "manydir")1106+ assertNoErr(t, rootCmd.Flags().SetAnnotation("manydir", BashCompSubdirsInDir, []string{"themes", "colors"}))1107+1108+ // Test that the completion logic returns the proper info for the completion1109+ // script to handle the directory filtering1110+ output, err := executeCommand(rootCmd, ShellCompNoDescRequestCmd, "--dir", "")1111+ if err != nil {1112+ t.Errorf("Unexpected error: %v", err)1113+ }1114+1115+ expected := strings.Join([]string{1116+ ":16",1117+ "Completion ended with directive: ShellCompDirectiveFilterDirs", ""}, "\n")1118+1119+ if output != expected {1120+ t.Errorf("expected: %q, got: %q", expected, output)1121+ }1122+1123+ output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "-d", "")1124+ if err != nil {1125+ t.Errorf("Unexpected error: %v", err)1126+ }1127+1128+ expected = strings.Join([]string{1129+ ":16",1130+ "Completion ended with directive: ShellCompDirectiveFilterDirs", ""}, "\n")1131+1132+ if output != expected {1133+ t.Errorf("expected: %q, got: %q", expected, output)1134+ }1135+1136+ output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "--subdir", "")1137+ if err != nil {1138+ t.Errorf("Unexpected error: %v", err)1139+ }1140+1141+ expected = strings.Join([]string{1142+ "themes",1143+ ":16",1144+ "Completion ended with directive: ShellCompDirectiveFilterDirs", ""}, "\n")1145+1146+ if output != expected {1147+ t.Errorf("expected: %q, got: %q", expected, output)1148+ }1149+1150+ output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "--subdir=")1151+ if err != nil {1152+ t.Errorf("Unexpected error: %v", err)1153+ }1154+1155+ expected = strings.Join([]string{1156+ "themes",1157+ ":16",1158+ "Completion ended with directive: ShellCompDirectiveFilterDirs", ""}, "\n")1159+1160+ if output != expected {1161+ t.Errorf("expected: %q, got: %q", expected, output)1162+ }1163+1164+ output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "-s", "")1165+ if err != nil {1166+ t.Errorf("Unexpected error: %v", err)1167+ }1168+1169+ expected = strings.Join([]string{1170+ "themes",1171+ ":16",1172+ "Completion ended with directive: ShellCompDirectiveFilterDirs", ""}, "\n")1173+1174+ if output != expected {1175+ t.Errorf("expected: %q, got: %q", expected, output)1176+ }1177+1178+ output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "-s=")1179+ if err != nil {1180+ t.Errorf("Unexpected error: %v", err)1181+ }1182+1183+ expected = strings.Join([]string{1184+ "themes",1185+ ":16",1186+ "Completion ended with directive: ShellCompDirectiveFilterDirs", ""}, "\n")1187+1188+ if output != expected {1189+ t.Errorf("expected: %q, got: %q", expected, output)1190+ }1191+1192+ output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "--manydir", "")1193+ if err != nil {1194+ t.Errorf("Unexpected error: %v", err)1195+ }1196+1197+ expected = strings.Join([]string{1198+ ":16",1199+ "Completion ended with directive: ShellCompDirectiveFilterDirs", ""}, "\n")1200+1201+ if output != expected {1202+ t.Errorf("expected: %q, got: %q", expected, output)1203+ }1204+}1205+1206+func TestValidArgsFuncSingleCmd(t *testing.T) {1207+ rootCmd := &Command{1208+ Use: "root",1209+ ValidArgsFunction: validArgsFunc,1210+ Run: emptyRun,1211+ }1212+1213+ // Test completing an empty string1214+ output, err := executeCommand(rootCmd, ShellCompNoDescRequestCmd, "")1215+ if err != nil {1216+ t.Errorf("Unexpected error: %v", err)1217+ }1218+1219+ expected := strings.Join([]string{1220+ "one",1221+ "two",1222+ ":0",1223+ "Completion ended with directive: ShellCompDirectiveDefault", ""}, "\n")1224+1225+ if output != expected {1226+ t.Errorf("expected: %q, got: %q", expected, output)1227+ }1228+1229+ // Check completing with a prefix1230+ output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "t")1231+ if err != nil {1232+ t.Errorf("Unexpected error: %v", err)1233+ }1234+1235+ expected = strings.Join([]string{1236+ "two",1237+ ":0",1238+ "Completion ended with directive: ShellCompDirectiveDefault", ""}, "\n")1239+1240+ if output != expected {1241+ t.Errorf("expected: %q, got: %q", expected, output)1242+ }1243+}1244+1245+func TestValidArgsFuncSingleCmdInvalidArg(t *testing.T) {1246+ rootCmd := &Command{1247+ Use: "root",1248+ // If we don't specify a value for Args, this test fails.1249+ // This is only true for a root command without any subcommands, and is caused1250+ // by the fact that the __complete command becomes a subcommand when there should not be one.1251+ // The problem is in the implementation of legacyArgs().1252+ Args: MinimumNArgs(1),1253+ ValidArgsFunction: validArgsFunc,1254+ Run: emptyRun,1255+ }1256+1257+ // Check completing with wrong number of args1258+ output, err := executeCommand(rootCmd, ShellCompNoDescRequestCmd, "unexpectedArg", "t")1259+ if err != nil {1260+ t.Errorf("Unexpected error: %v", err)1261+ }1262+1263+ expected := strings.Join([]string{1264+ ":4",1265+ "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")1266+1267+ if output != expected {1268+ t.Errorf("expected: %q, got: %q", expected, output)1269+ }1270+}1271+1272+func TestValidArgsFuncChildCmds(t *testing.T) {1273+ rootCmd := &Command{Use: "root", Args: NoArgs, Run: emptyRun}1274+ child1Cmd := &Command{1275+ Use: "child1",1276+ ValidArgsFunction: validArgsFunc,1277+ Run: emptyRun,1278+ }1279+ child2Cmd := &Command{1280+ Use: "child2",1281+ ValidArgsFunction: validArgsFunc2,1282+ Run: emptyRun,1283+ }1284+ rootCmd.AddCommand(child1Cmd, child2Cmd)1285+1286+ // Test completion of first sub-command with empty argument1287+ output, err := executeCommand(rootCmd, ShellCompNoDescRequestCmd, "child1", "")1288+ if err != nil {1289+ t.Errorf("Unexpected error: %v", err)1290+ }1291+1292+ expected := strings.Join([]string{1293+ "one",1294+ "two",1295+ ":0",1296+ "Completion ended with directive: ShellCompDirectiveDefault", ""}, "\n")1297+1298+ if output != expected {1299+ t.Errorf("expected: %q, got: %q", expected, output)1300+ }1301+1302+ // Test completion of first sub-command with a prefix to complete1303+ output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "child1", "t")1304+ if err != nil {1305+ t.Errorf("Unexpected error: %v", err)1306+ }1307+1308+ expected = strings.Join([]string{1309+ "two",1310+ ":0",1311+ "Completion ended with directive: ShellCompDirectiveDefault", ""}, "\n")1312+1313+ if output != expected {1314+ t.Errorf("expected: %q, got: %q", expected, output)1315+ }1316+1317+ // Check completing with wrong number of args1318+ output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "child1", "unexpectedArg", "t")1319+ if err != nil {1320+ t.Errorf("Unexpected error: %v", err)1321+ }1322+1323+ expected = strings.Join([]string{1324+ ":4",1325+ "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")1326+1327+ if output != expected {1328+ t.Errorf("expected: %q, got: %q", expected, output)1329+ }1330+1331+ // Test completion of second sub-command with empty argument1332+ output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "child2", "")1333+ if err != nil {1334+ t.Errorf("Unexpected error: %v", err)1335+ }1336+1337+ expected = strings.Join([]string{1338+ "three",1339+ "four",1340+ ":0",1341+ "Completion ended with directive: ShellCompDirectiveDefault", ""}, "\n")1342+1343+ if output != expected {1344+ t.Errorf("expected: %q, got: %q", expected, output)1345+ }1346+1347+ output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "child2", "t")1348+ if err != nil {1349+ t.Errorf("Unexpected error: %v", err)1350+ }1351+1352+ expected = strings.Join([]string{1353+ "three",1354+ ":0",1355+ "Completion ended with directive: ShellCompDirectiveDefault", ""}, "\n")1356+1357+ if output != expected {1358+ t.Errorf("expected: %q, got: %q", expected, output)1359+ }1360+1361+ // Check completing with wrong number of args1362+ output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "child2", "unexpectedArg", "t")1363+ if err != nil {1364+ t.Errorf("Unexpected error: %v", err)1365+ }1366+1367+ expected = strings.Join([]string{1368+ ":4",1369+ "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")1370+1371+ if output != expected {1372+ t.Errorf("expected: %q, got: %q", expected, output)1373+ }1374+}1375+1376+func TestValidArgsFuncAliases(t *testing.T) {1377+ rootCmd := &Command{Use: "root", Args: NoArgs, Run: emptyRun}1378+ child := &Command{1379+ Use: "child",1380+ Aliases: []string{"son", "daughter"},1381+ ValidArgsFunction: validArgsFunc,1382+ Run: emptyRun,1383+ }1384+ rootCmd.AddCommand(child)1385+1386+ // Test completion of first sub-command with empty argument1387+ output, err := executeCommand(rootCmd, ShellCompNoDescRequestCmd, "son", "")1388+ if err != nil {1389+ t.Errorf("Unexpected error: %v", err)1390+ }1391+1392+ expected := strings.Join([]string{1393+ "one",1394+ "two",1395+ ":0",1396+ "Completion ended with directive: ShellCompDirectiveDefault", ""}, "\n")1397+1398+ if output != expected {1399+ t.Errorf("expected: %q, got: %q", expected, output)1400+ }1401+1402+ // Test completion of first sub-command with a prefix to complete1403+ output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "daughter", "t")1404+ if err != nil {1405+ t.Errorf("Unexpected error: %v", err)1406+ }1407+1408+ expected = strings.Join([]string{1409+ "two",1410+ ":0",1411+ "Completion ended with directive: ShellCompDirectiveDefault", ""}, "\n")1412+1413+ if output != expected {1414+ t.Errorf("expected: %q, got: %q", expected, output)1415+ }1416+1417+ // Check completing with wrong number of args1418+ output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "son", "unexpectedArg", "t")1419+ if err != nil {1420+ t.Errorf("Unexpected error: %v", err)1421+ }1422+1423+ expected = strings.Join([]string{1424+ ":4",1425+ "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")1426+1427+ if output != expected {1428+ t.Errorf("expected: %q, got: %q", expected, output)1429+ }1430+}1431+1432+func TestValidArgsFuncInBashScript(t *testing.T) {1433+ rootCmd := &Command{Use: "root", Args: NoArgs, Run: emptyRun}1434+ child := &Command{1435+ Use: "child",1436+ ValidArgsFunction: validArgsFunc,1437+ Run: emptyRun,1438+ }1439+ rootCmd.AddCommand(child)1440+1441+ buf := new(bytes.Buffer)1442+ assertNoErr(t, rootCmd.GenBashCompletion(buf))1443+ output := buf.String()1444+1445+ check(t, output, "has_completion_function=1")1446+}1447+1448+func TestNoValidArgsFuncInBashScript(t *testing.T) {1449+ rootCmd := &Command{Use: "root", Args: NoArgs, Run: emptyRun}1450+ child := &Command{1451+ Use: "child",1452+ Run: emptyRun,1453+ }1454+ rootCmd.AddCommand(child)1455+1456+ buf := new(bytes.Buffer)1457+ assertNoErr(t, rootCmd.GenBashCompletion(buf))1458+ output := buf.String()1459+1460+ checkOmit(t, output, "has_completion_function=1")1461+}1462+1463+func TestCompleteCmdInBashScript(t *testing.T) {1464+ rootCmd := &Command{Use: "root", Args: NoArgs, Run: emptyRun}1465+ child := &Command{1466+ Use: "child",1467+ ValidArgsFunction: validArgsFunc,1468+ Run: emptyRun,1469+ }1470+ rootCmd.AddCommand(child)1471+1472+ buf := new(bytes.Buffer)1473+ assertNoErr(t, rootCmd.GenBashCompletion(buf))1474+ output := buf.String()1475+1476+ check(t, output, ShellCompNoDescRequestCmd)1477+}1478+1479+func TestCompleteNoDesCmdInZshScript(t *testing.T) {1480+ rootCmd := &Command{Use: "root", Args: NoArgs, Run: emptyRun}1481+ child := &Command{1482+ Use: "child",1483+ ValidArgsFunction: validArgsFunc,1484+ Run: emptyRun,1485+ }1486+ rootCmd.AddCommand(child)1487+1488+ buf := new(bytes.Buffer)1489+ assertNoErr(t, rootCmd.GenZshCompletionNoDesc(buf))1490+ output := buf.String()1491+1492+ check(t, output, ShellCompNoDescRequestCmd)1493+}1494+1495+func TestCompleteCmdInZshScript(t *testing.T) {1496+ rootCmd := &Command{Use: "root", Args: NoArgs, Run: emptyRun}1497+ child := &Command{1498+ Use: "child",1499+ ValidArgsFunction: validArgsFunc,1500+ Run: emptyRun,1501+ }1502+ rootCmd.AddCommand(child)1503+1504+ buf := new(bytes.Buffer)1505+ assertNoErr(t, rootCmd.GenZshCompletion(buf))1506+ output := buf.String()1507+1508+ check(t, output, ShellCompRequestCmd)1509+ checkOmit(t, output, ShellCompNoDescRequestCmd)1510+}1511+1512+func TestFlagCompletionInGo(t *testing.T) {1513+ rootCmd := &Command{1514+ Use: "root",1515+ Run: emptyRun,1516+ }1517+ rootCmd.Flags().IntP("introot", "i", -1, "help message for flag introot")1518+ assertNoErr(t, rootCmd.RegisterFlagCompletionFunc("introot", func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective) {1519+ completions := []string{}1520+ for _, comp := range []string{"1\tThe first", "2\tThe second", "10\tThe tenth"} {1521+ if strings.HasPrefix(comp, toComplete) {1522+ completions = append(completions, comp)1523+ }1524+ }1525+ return completions, ShellCompDirectiveDefault1526+ }))1527+ rootCmd.Flags().String("filename", "", "Enter a filename")1528+ assertNoErr(t, rootCmd.RegisterFlagCompletionFunc("filename", func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective) {1529+ completions := []string{}1530+ for _, comp := range []string{"file.yaml\tYAML format", "myfile.json\tJSON format", "file.xml\tXML format"} {1531+ if strings.HasPrefix(comp, toComplete) {1532+ completions = append(completions, comp)1533+ }1534+ }1535+ return completions, ShellCompDirectiveNoSpace | ShellCompDirectiveNoFileComp1536+ }))1537+1538+ // Test completing an empty string1539+ output, err := executeCommand(rootCmd, ShellCompNoDescRequestCmd, "--introot", "")1540+ if err != nil {1541+ t.Errorf("Unexpected error: %v", err)1542+ }1543+1544+ expected := strings.Join([]string{1545+ "1",1546+ "2",1547+ "10",1548+ ":0",1549+ "Completion ended with directive: ShellCompDirectiveDefault", ""}, "\n")1550+1551+ if output != expected {1552+ t.Errorf("expected: %q, got: %q", expected, output)1553+ }1554+1555+ // Check completing with a prefix1556+ output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "--introot", "1")1557+ if err != nil {1558+ t.Errorf("Unexpected error: %v", err)1559+ }1560+1561+ expected = strings.Join([]string{1562+ "1",1563+ "10",1564+ ":0",1565+ "Completion ended with directive: ShellCompDirectiveDefault", ""}, "\n")1566+1567+ if output != expected {1568+ t.Errorf("expected: %q, got: %q", expected, output)1569+ }1570+1571+ // Test completing an empty string1572+ output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "--filename", "")1573+ if err != nil {1574+ t.Errorf("Unexpected error: %v", err)1575+ }1576+1577+ expected = strings.Join([]string{1578+ "file.yaml",1579+ "myfile.json",1580+ "file.xml",1581+ ":6",1582+ "Completion ended with directive: ShellCompDirectiveNoSpace, ShellCompDirectiveNoFileComp", ""}, "\n")1583+1584+ if output != expected {1585+ t.Errorf("expected: %q, got: %q", expected, output)1586+ }1587+1588+ // Check completing with a prefix1589+ output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "--filename", "f")1590+ if err != nil {1591+ t.Errorf("Unexpected error: %v", err)1592+ }1593+1594+ expected = strings.Join([]string{1595+ "file.yaml",1596+ "file.xml",1597+ ":6",1598+ "Completion ended with directive: ShellCompDirectiveNoSpace, ShellCompDirectiveNoFileComp", ""}, "\n")1599+1600+ if output != expected {1601+ t.Errorf("expected: %q, got: %q", expected, output)1602+ }1603+}1604+1605+func TestValidArgsFuncChildCmdsWithDesc(t *testing.T) {1606+ rootCmd := &Command{Use: "root", Args: NoArgs, Run: emptyRun}1607+ child1Cmd := &Command{1608+ Use: "child1",1609+ ValidArgsFunction: validArgsFunc,1610+ Run: emptyRun,1611+ }1612+ child2Cmd := &Command{1613+ Use: "child2",1614+ ValidArgsFunction: validArgsFunc2,1615+ Run: emptyRun,1616+ }1617+ rootCmd.AddCommand(child1Cmd, child2Cmd)1618+1619+ // Test completion of first sub-command with empty argument1620+ output, err := executeCommand(rootCmd, ShellCompRequestCmd, "child1", "")1621+ if err != nil {1622+ t.Errorf("Unexpected error: %v", err)1623+ }1624+1625+ expected := strings.Join([]string{1626+ "one\tThe first",1627+ "two\tThe second",1628+ ":0",1629+ "Completion ended with directive: ShellCompDirectiveDefault", ""}, "\n")1630+1631+ if output != expected {1632+ t.Errorf("expected: %q, got: %q", expected, output)1633+ }1634+1635+ // Test completion of first sub-command with a prefix to complete1636+ output, err = executeCommand(rootCmd, ShellCompRequestCmd, "child1", "t")1637+ if err != nil {1638+ t.Errorf("Unexpected error: %v", err)1639+ }1640+1641+ expected = strings.Join([]string{1642+ "two\tThe second",1643+ ":0",1644+ "Completion ended with directive: ShellCompDirectiveDefault", ""}, "\n")1645+1646+ if output != expected {1647+ t.Errorf("expected: %q, got: %q", expected, output)1648+ }1649+1650+ // Check completing with wrong number of args1651+ output, err = executeCommand(rootCmd, ShellCompRequestCmd, "child1", "unexpectedArg", "t")1652+ if err != nil {1653+ t.Errorf("Unexpected error: %v", err)1654+ }1655+1656+ expected = strings.Join([]string{1657+ ":4",1658+ "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")1659+1660+ if output != expected {1661+ t.Errorf("expected: %q, got: %q", expected, output)1662+ }1663+1664+ // Test completion of second sub-command with empty argument1665+ output, err = executeCommand(rootCmd, ShellCompRequestCmd, "child2", "")1666+ if err != nil {1667+ t.Errorf("Unexpected error: %v", err)1668+ }1669+1670+ expected = strings.Join([]string{1671+ "three\tThe third",1672+ "four\tThe fourth",1673+ ":0",1674+ "Completion ended with directive: ShellCompDirectiveDefault", ""}, "\n")1675+1676+ if output != expected {1677+ t.Errorf("expected: %q, got: %q", expected, output)1678+ }1679+1680+ output, err = executeCommand(rootCmd, ShellCompRequestCmd, "child2", "t")1681+ if err != nil {1682+ t.Errorf("Unexpected error: %v", err)1683+ }1684+1685+ expected = strings.Join([]string{1686+ "three\tThe third",1687+ ":0",1688+ "Completion ended with directive: ShellCompDirectiveDefault", ""}, "\n")1689+1690+ if output != expected {1691+ t.Errorf("expected: %q, got: %q", expected, output)1692+ }1693+1694+ // Check completing with wrong number of args1695+ output, err = executeCommand(rootCmd, ShellCompRequestCmd, "child2", "unexpectedArg", "t")1696+ if err != nil {1697+ t.Errorf("Unexpected error: %v", err)1698+ }1699+1700+ expected = strings.Join([]string{1701+ ":4",1702+ "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")1703+1704+ if output != expected {1705+ t.Errorf("expected: %q, got: %q", expected, output)1706+ }1707+}1708+1709+func TestFlagCompletionInGoWithDesc(t *testing.T) {1710+ rootCmd := &Command{1711+ Use: "root",1712+ Run: emptyRun,1713+ }1714+ rootCmd.Flags().IntP("introot", "i", -1, "help message for flag introot")1715+ assertNoErr(t, rootCmd.RegisterFlagCompletionFunc("introot", func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective) {1716+ completions := []string{}1717+ for _, comp := range []string{"1\tThe first", "2\tThe second", "10\tThe tenth"} {1718+ if strings.HasPrefix(comp, toComplete) {1719+ completions = append(completions, comp)1720+ }1721+ }1722+ return completions, ShellCompDirectiveDefault1723+ }))1724+ rootCmd.Flags().String("filename", "", "Enter a filename")1725+ assertNoErr(t, rootCmd.RegisterFlagCompletionFunc("filename", func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective) {1726+ completions := []string{}1727+ for _, comp := range []string{"file.yaml\tYAML format", "myfile.json\tJSON format", "file.xml\tXML format"} {1728+ if strings.HasPrefix(comp, toComplete) {1729+ completions = append(completions, comp)1730+ }1731+ }1732+ return completions, ShellCompDirectiveNoSpace | ShellCompDirectiveNoFileComp1733+ }))1734+1735+ // Test completing an empty string1736+ output, err := executeCommand(rootCmd, ShellCompRequestCmd, "--introot", "")1737+ if err != nil {1738+ t.Errorf("Unexpected error: %v", err)1739+ }1740+1741+ expected := strings.Join([]string{1742+ "1\tThe first",1743+ "2\tThe second",1744+ "10\tThe tenth",1745+ ":0",1746+ "Completion ended with directive: ShellCompDirectiveDefault", ""}, "\n")1747+1748+ if output != expected {1749+ t.Errorf("expected: %q, got: %q", expected, output)1750+ }1751+1752+ // Check completing with a prefix1753+ output, err = executeCommand(rootCmd, ShellCompRequestCmd, "--introot", "1")1754+ if err != nil {1755+ t.Errorf("Unexpected error: %v", err)1756+ }1757+1758+ expected = strings.Join([]string{1759+ "1\tThe first",1760+ "10\tThe tenth",1761+ ":0",1762+ "Completion ended with directive: ShellCompDirectiveDefault", ""}, "\n")1763+1764+ if output != expected {1765+ t.Errorf("expected: %q, got: %q", expected, output)1766+ }1767+1768+ // Test completing an empty string1769+ output, err = executeCommand(rootCmd, ShellCompRequestCmd, "--filename", "")1770+ if err != nil {1771+ t.Errorf("Unexpected error: %v", err)1772+ }1773+1774+ expected = strings.Join([]string{1775+ "file.yaml\tYAML format",1776+ "myfile.json\tJSON format",1777+ "file.xml\tXML format",1778+ ":6",1779+ "Completion ended with directive: ShellCompDirectiveNoSpace, ShellCompDirectiveNoFileComp", ""}, "\n")1780+1781+ if output != expected {1782+ t.Errorf("expected: %q, got: %q", expected, output)1783+ }1784+1785+ // Check completing with a prefix1786+ output, err = executeCommand(rootCmd, ShellCompRequestCmd, "--filename", "f")1787+ if err != nil {1788+ t.Errorf("Unexpected error: %v", err)1789+ }1790+1791+ expected = strings.Join([]string{1792+ "file.yaml\tYAML format",1793+ "file.xml\tXML format",1794+ ":6",1795+ "Completion ended with directive: ShellCompDirectiveNoSpace, ShellCompDirectiveNoFileComp", ""}, "\n")1796+1797+ if output != expected {1798+ t.Errorf("expected: %q, got: %q", expected, output)1799+ }1800+}1801+1802+func TestValidArgsNotValidArgsFunc(t *testing.T) {1803+ rootCmd := &Command{1804+ Use: "root",1805+ ValidArgs: []string{"one", "two"},1806+ ValidArgsFunction: func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective) {1807+ return []string{"three", "four"}, ShellCompDirectiveNoFileComp1808+ },1809+ Run: emptyRun,1810+ }1811+1812+ // Test that if both ValidArgs and ValidArgsFunction are present1813+ // only ValidArgs is considered1814+ output, err := executeCommand(rootCmd, ShellCompNoDescRequestCmd, "")1815+ if err != nil {1816+ t.Errorf("Unexpected error: %v", err)1817+ }1818+1819+ expected := strings.Join([]string{1820+ "one",1821+ "two",1822+ ":4",1823+ "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")1824+1825+ if output != expected {1826+ t.Errorf("expected: %q, got: %q", expected, output)1827+ }1828+1829+ // Check completing with a prefix1830+ output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "t")1831+ if err != nil {1832+ t.Errorf("Unexpected error: %v", err)1833+ }1834+1835+ expected = strings.Join([]string{1836+ "two",1837+ ":4",1838+ "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")1839+1840+ if output != expected {1841+ t.Errorf("expected: %q, got: %q", expected, output)1842+ }1843+}1844+1845+func TestArgAliasesCompletionInGo(t *testing.T) {1846+ rootCmd := &Command{1847+ Use: "root",1848+ Args: OnlyValidArgs,1849+ ValidArgs: []string{"one", "two", "three"},1850+ ArgAliases: []string{"un", "deux", "trois"},1851+ Run: emptyRun,1852+ }1853+1854+ // Test that argaliases are not completed when there are validargs that match1855+ output, err := executeCommand(rootCmd, ShellCompNoDescRequestCmd, "")1856+ if err != nil {1857+ t.Errorf("Unexpected error: %v", err)1858+ }1859+1860+ expected := strings.Join([]string{1861+ "one",1862+ "two",1863+ "three",1864+ ":4",1865+ "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")1866+1867+ if output != expected {1868+ t.Errorf("expected: %q, got: %q", expected, output)1869+ }1870+1871+ // Test that argaliases are not completed when there are validargs that match using a prefix1872+ output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "t")1873+ if err != nil {1874+ t.Errorf("Unexpected error: %v", err)1875+ }1876+1877+ expected = strings.Join([]string{1878+ "two",1879+ "three",1880+ ":4",1881+ "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")1882+1883+ if output != expected {1884+ t.Errorf("expected: %q, got: %q", expected, output)1885+ }1886+1887+ // Test that argaliases are completed when there are no validargs that match1888+ output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "tr")1889+ if err != nil {1890+ t.Errorf("Unexpected error: %v", err)1891+ }1892+1893+ expected = strings.Join([]string{1894+ "trois",1895+ ":4",1896+ "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")1897+1898+ if output != expected {1899+ t.Errorf("expected: %q, got: %q", expected, output)1900+ }1901+}1902+1903+func TestCompleteHelp(t *testing.T) {1904+ rootCmd := &Command{Use: "root", Args: NoArgs, Run: emptyRun}1905+ child1Cmd := &Command{1906+ Use: "child1",1907+ Run: emptyRun,1908+ }1909+ child2Cmd := &Command{1910+ Use: "child2",1911+ Run: emptyRun,1912+ }1913+ rootCmd.AddCommand(child1Cmd, child2Cmd)1914+1915+ child3Cmd := &Command{1916+ Use: "child3",1917+ Run: emptyRun,1918+ }1919+ child1Cmd.AddCommand(child3Cmd)1920+1921+ // Test that completion includes the help command1922+ output, err := executeCommand(rootCmd, ShellCompNoDescRequestCmd, "")1923+ if err != nil {1924+ t.Errorf("Unexpected error: %v", err)1925+ }1926+1927+ expected := strings.Join([]string{1928+ "child1",1929+ "child2",1930+ "completion",1931+ "help",1932+ ":4",1933+ "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")1934+1935+ if output != expected {1936+ t.Errorf("expected: %q, got: %q", expected, output)1937+ }1938+1939+ // Test sub-commands are completed on first level of help command1940+ output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "help", "")1941+ if err != nil {1942+ t.Errorf("Unexpected error: %v", err)1943+ }1944+1945+ expected = strings.Join([]string{1946+ "child1",1947+ "child2",1948+ "completion",1949+ "help", // "<program> help help" is a valid command, so should be completed1950+ ":4",1951+ "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")1952+1953+ if output != expected {1954+ t.Errorf("expected: %q, got: %q", expected, output)1955+ }1956+1957+ // Test sub-commands are completed on first level of help command1958+ output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "help", "child1", "")1959+ if err != nil {1960+ t.Errorf("Unexpected error: %v", err)1961+ }1962+1963+ expected = strings.Join([]string{1964+ "child3",1965+ ":4",1966+ "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")1967+1968+ if output != expected {1969+ t.Errorf("expected: %q, got: %q", expected, output)1970+ }1971+}1972+1973+func removeCompCmd(rootCmd *Command) {1974+ // Remove completion command for the next test1975+ for _, cmd := range rootCmd.commands {1976+ if cmd.Name() == compCmdName {1977+ rootCmd.RemoveCommand(cmd)1978+ return1979+ }1980+ }1981+}1982+1983+func TestDefaultCompletionCmd(t *testing.T) {1984+ rootCmd := &Command{1985+ Use: "root",1986+ Args: NoArgs,1987+ Run: emptyRun,1988+ }1989+1990+ // Test that no completion command is created if there are not other sub-commands1991+ assertNoErr(t, rootCmd.Execute())1992+ for _, cmd := range rootCmd.commands {1993+ if cmd.Name() == compCmdName {1994+ t.Errorf("Should not have a 'completion' command when there are no other sub-commands of root")1995+ break1996+ }1997+ }1998+1999+ subCmd := &Command{2000+ Use: "sub",2001+ Run: emptyRun,2002+ }2003+ rootCmd.AddCommand(subCmd)2004+2005+ // Test that a completion command is created if there are other sub-commands2006+ found := false2007+ assertNoErr(t, rootCmd.Execute())2008+ for _, cmd := range rootCmd.commands {2009+ if cmd.Name() == compCmdName {2010+ found = true2011+ break2012+ }2013+ }2014+ if !found {2015+ t.Errorf("Should have a 'completion' command when there are other sub-commands of root")2016+ }2017+ // Remove completion command for the next test2018+ removeCompCmd(rootCmd)2019+2020+ // Test that the default completion command can be disabled2021+ rootCmd.CompletionOptions.DisableDefaultCmd = true2022+ assertNoErr(t, rootCmd.Execute())2023+ for _, cmd := range rootCmd.commands {2024+ if cmd.Name() == compCmdName {2025+ t.Errorf("Should not have a 'completion' command when the feature is disabled")2026+ break2027+ }2028+ }2029+ // Re-enable for next test2030+ rootCmd.CompletionOptions.DisableDefaultCmd = false2031+2032+ // Test that completion descriptions are enabled by default2033+ output, err := executeCommand(rootCmd, compCmdName, "zsh")2034+ if err != nil {2035+ t.Errorf("Unexpected error: %v", err)2036+ }2037+2038+ check(t, output, ShellCompRequestCmd)2039+ checkOmit(t, output, ShellCompNoDescRequestCmd)2040+ // Remove completion command for the next test2041+ removeCompCmd(rootCmd)2042+2043+ // Test that completion descriptions can be disabled completely2044+ rootCmd.CompletionOptions.DisableDescriptions = true2045+ output, err = executeCommand(rootCmd, compCmdName, "zsh")2046+ if err != nil {2047+ t.Errorf("Unexpected error: %v", err)2048+ }2049+2050+ check(t, output, ShellCompNoDescRequestCmd)2051+ // Re-enable for next test2052+ rootCmd.CompletionOptions.DisableDescriptions = false2053+ // Remove completion command for the next test2054+ removeCompCmd(rootCmd)2055+2056+ var compCmd *Command2057+ // Test that the --no-descriptions flag is present for the relevant shells only2058+ assertNoErr(t, rootCmd.Execute())2059+ for _, shell := range []string{"fish", "powershell", "zsh"} {2060+ if compCmd, _, err = rootCmd.Find([]string{compCmdName, shell}); err != nil {2061+ t.Errorf("Unexpected error: %v", err)2062+ }2063+ if flag := compCmd.Flags().Lookup(compCmdNoDescFlagName); flag == nil {2064+ t.Errorf("Missing --%s flag for %s shell", compCmdNoDescFlagName, shell)2065+ }2066+ }2067+ for _, shell := range []string{"bash"} {2068+ if compCmd, _, err = rootCmd.Find([]string{compCmdName, shell}); err != nil {2069+ t.Errorf("Unexpected error: %v", err)2070+ }2071+ if flag := compCmd.Flags().Lookup(compCmdNoDescFlagName); flag != nil {2072+ t.Errorf("Unexpected --%s flag for %s shell", compCmdNoDescFlagName, shell)2073+ }2074+ }2075+ // Remove completion command for the next test2076+ removeCompCmd(rootCmd)2077+2078+ // Test that the '--no-descriptions' flag can be disabled2079+ rootCmd.CompletionOptions.DisableNoDescFlag = true2080+ assertNoErr(t, rootCmd.Execute())2081+ for _, shell := range []string{"fish", "zsh", "bash", "powershell"} {2082+ if compCmd, _, err = rootCmd.Find([]string{compCmdName, shell}); err != nil {2083+ t.Errorf("Unexpected error: %v", err)2084+ }2085+ if flag := compCmd.Flags().Lookup(compCmdNoDescFlagName); flag != nil {2086+ t.Errorf("Unexpected --%s flag for %s shell", compCmdNoDescFlagName, shell)2087+ }2088+ }2089+ // Re-enable for next test2090+ rootCmd.CompletionOptions.DisableNoDescFlag = false2091+ // Remove completion command for the next test2092+ removeCompCmd(rootCmd)2093+2094+ // Test that the '--no-descriptions' flag is disabled when descriptions are disabled2095+ rootCmd.CompletionOptions.DisableDescriptions = true2096+ assertNoErr(t, rootCmd.Execute())2097+ for _, shell := range []string{"fish", "zsh", "bash", "powershell"} {2098+ if compCmd, _, err = rootCmd.Find([]string{compCmdName, shell}); err != nil {2099+ t.Errorf("Unexpected error: %v", err)2100+ }2101+ if flag := compCmd.Flags().Lookup(compCmdNoDescFlagName); flag != nil {2102+ t.Errorf("Unexpected --%s flag for %s shell", compCmdNoDescFlagName, shell)2103+ }2104+ }2105+ // Re-enable for next test2106+ rootCmd.CompletionOptions.DisableDescriptions = false2107+ // Remove completion command for the next test2108+ removeCompCmd(rootCmd)2109+}2110+2111+func TestCompleteCompletion(t *testing.T) {2112+ rootCmd := &Command{Use: "root", Args: NoArgs, Run: emptyRun}2113+ subCmd := &Command{2114+ Use: "sub",2115+ Run: emptyRun,2116+ }2117+ rootCmd.AddCommand(subCmd)2118+2119+ // Test sub-commands of the completion command2120+ output, err := executeCommand(rootCmd, ShellCompNoDescRequestCmd, "completion", "")2121+ if err != nil {2122+ t.Errorf("Unexpected error: %v", err)2123+ }2124+2125+ expected := strings.Join([]string{2126+ "bash",2127+ "fish",2128+ "powershell",2129+ "zsh",2130+ ":4",2131+ "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")2132+2133+ if output != expected {2134+ t.Errorf("expected: %q, got: %q", expected, output)2135+ }2136+2137+ // Test there are no completions for the sub-commands of the completion command2138+ var compCmd *Command2139+ for _, cmd := range rootCmd.Commands() {2140+ if cmd.Name() == compCmdName {2141+ compCmd = cmd2142+ break2143+ }2144+ }2145+2146+ for _, shell := range compCmd.Commands() {2147+ output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, compCmdName, shell.Name(), "")2148+ if err != nil {2149+ t.Errorf("Unexpected error: %v", err)2150+ }2151+2152+ expected = strings.Join([]string{2153+ ":4",2154+ "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")2155+2156+ if output != expected {2157+ t.Errorf("expected: %q, got: %q", expected, output)2158+ }2159+ }2160+}added:completions.go+727 added
1+package cobra2+3+import (4+ "fmt"5+ "os"6+ "strings"7+8+ "github.com/spf13/pflag"9+)10+11+const (12+ // 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 scripts.14+ ShellCompRequestCmd = "__complete"15+ // ShellCompNoDescRequestCmd is the name of the hidden command that is used to request16+ // completion results without their description. It is used by the shell completion scripts.17+ ShellCompNoDescRequestCmd = "__completeNoDesc"18+)19+20+// Global map of flag completion functions.21+var flagCompletionFunctions = map[*pflag.Flag]func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective){}22+23+// ShellCompDirective is a bit map representing the different behaviors the shell24+// can be instructed to have once completions have been provided.25+type ShellCompDirective int26+27+const (28+ // ShellCompDirectiveError indicates an error occurred and completions should be ignored.29+ ShellCompDirectiveError ShellCompDirective = 1 << iota30+31+ // ShellCompDirectiveNoSpace indicates that the shell should not add a space32+ // after the completion even if there is a single completion provided.33+ ShellCompDirectiveNoSpace34+35+ // ShellCompDirectiveNoFileComp indicates that the shell should not provide36+ // file completion even when no completion is provided.37+ // This currently does not work for zsh or bash < 438+ ShellCompDirectiveNoFileComp39+40+ // ShellCompDirectiveFilterFileExt indicates that the provided completions41+ // should be used as file extension filters.42+ // For flags, using Command.MarkFlagFilename() and Command.MarkPersistentFlagFilename()43+ // is a shortcut to using this directive explicitly. The BashCompFilenameExt44+ // annotation can also be used to obtain the same behavior for flags.45+ ShellCompDirectiveFilterFileExt46+47+ // ShellCompDirectiveFilterDirs indicates that only directory names should48+ // be provided in file completion. To request directory names within another49+ // directory, the returned completions should specify the directory within50+ // which to search. The BashCompSubdirsInDir annotation can be used to51+ // obtain the same behavior but only for flags.52+ ShellCompDirectiveFilterDirs53+54+ // ===========================================================================55+56+ // All directives using iota should be above this one.57+ // For internal use.58+ shellCompDirectiveMaxValue59+60+ // ShellCompDirectiveDefault indicates to let the shell perform its default61+ // behavior after completions have been provided.62+ // This one must be last to avoid messing up the iota count.63+ ShellCompDirectiveDefault ShellCompDirective = 064+)65+66+const (67+ // Constants for the completion command68+ compCmdName = "completion"69+ compCmdNoDescFlagName = "no-descriptions"70+ compCmdNoDescFlagDesc = "disable completion descriptions"71+ compCmdNoDescFlagDefault = false72+)73+74+// CompletionOptions are the options to control shell completion75+type CompletionOptions struct {76+ // DisableDefaultCmd prevents Cobra from creating a default 'completion' command77+ DisableDefaultCmd bool78+ // DisableNoDescFlag prevents Cobra from creating the '--no-descriptions' flag79+ // for shells that support completion descriptions80+ DisableNoDescFlag bool81+ // DisableDescriptions turns off all completion descriptions for shells82+ // that support them83+ DisableDescriptions bool84+}85+86+// NoFileCompletions can be used to disable file completion for commands that should87+// not trigger file completions.88+func NoFileCompletions(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective) {89+ return nil, ShellCompDirectiveNoFileComp90+}91+92+// RegisterFlagCompletionFunc should be called to register a function to provide completion for a flag.93+func (c *Command) RegisterFlagCompletionFunc(flagName string, f func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective)) error {94+ flag := c.Flag(flagName)95+ if flag == nil {96+ return fmt.Errorf("RegisterFlagCompletionFunc: flag '%s' does not exist", flagName)97+ }98+ if _, exists := flagCompletionFunctions[flag]; exists {99+ return fmt.Errorf("RegisterFlagCompletionFunc: flag '%s' already registered", flagName)100+ }101+ flagCompletionFunctions[flag] = f102+ return nil103+}104+105+// Returns a string listing the different directive enabled in the specified parameter106+func (d ShellCompDirective) string() string {107+ var directives []string108+ if d&ShellCompDirectiveError != 0 {109+ directives = append(directives, "ShellCompDirectiveError")110+ }111+ if d&ShellCompDirectiveNoSpace != 0 {112+ directives = append(directives, "ShellCompDirectiveNoSpace")113+ }114+ if d&ShellCompDirectiveNoFileComp != 0 {115+ directives = append(directives, "ShellCompDirectiveNoFileComp")116+ }117+ if d&ShellCompDirectiveFilterFileExt != 0 {118+ directives = append(directives, "ShellCompDirectiveFilterFileExt")119+ }120+ if d&ShellCompDirectiveFilterDirs != 0 {121+ directives = append(directives, "ShellCompDirectiveFilterDirs")122+ }123+ if len(directives) == 0 {124+ directives = append(directives, "ShellCompDirectiveDefault")125+ }126+127+ if d >= shellCompDirectiveMaxValue {128+ return fmt.Sprintf("ERROR: unexpected ShellCompDirective value: %d", d)129+ }130+ return strings.Join(directives, ", ")131+}132+133+// Adds a special hidden command that can be used to request custom completions.134+func (c *Command) initCompleteCmd(args []string) {135+ completeCmd := &Command{136+ Use: fmt.Sprintf("%s [command-line]", ShellCompRequestCmd),137+ Aliases: []string{ShellCompNoDescRequestCmd},138+ DisableFlagsInUseLine: true,139+ Hidden: true,140+ DisableFlagParsing: true,141+ Args: MinimumNArgs(1),142+ Short: "Request shell completion choices for the specified command-line",143+ Long: fmt.Sprintf("%[2]s is a special command that is used by the shell completion logic\n%[1]s",144+ "to request completion choices for the specified command-line.", ShellCompRequestCmd),145+ Run: func(cmd *Command, args []string) {146+ finalCmd, completions, directive, err := cmd.getCompletions(args)147+ if err != nil {148+ CompErrorln(err.Error())149+ // Keep going for multiple reasons:150+ // 1- There could be some valid completions even though there was an error151+ // 2- Even without completions, we need to print the directive152+ }153+154+ noDescriptions := (cmd.CalledAs() == ShellCompNoDescRequestCmd)155+ for _, comp := range completions {156+ if noDescriptions {157+ // Remove any description that may be included following a tab character.158+ comp = strings.Split(comp, "\t")[0]159+ }160+161+ // Make sure we only write the first line to the output.162+ // This is needed if a description contains a linebreak.163+ // Otherwise the shell scripts will interpret the other lines as new flags164+ // and could therefore provide a wrong completion.165+ comp = strings.Split(comp, "\n")[0]166+167+ // Finally trim the completion. This is especially important to get rid168+ // of a trailing tab when there are no description following it.169+ // For example, a sub-command without a description should not be completed170+ // with a tab at the end (or else zsh will show a -- following it171+ // although there is no description).172+ comp = strings.TrimSpace(comp)173+174+ // Print each possible completion to stdout for the completion script to consume.175+ fmt.Fprintln(finalCmd.OutOrStdout(), comp)176+ }177+178+ if directive >= shellCompDirectiveMaxValue {179+ directive = ShellCompDirectiveDefault180+ }181+182+ // As the last printout, print the completion directive for the completion script to parse.183+ // The directive integer must be that last character following a single colon (:).184+ // The completion script expects :<directive>185+ fmt.Fprintf(finalCmd.OutOrStdout(), ":%d\n", directive)186+187+ // Print some helpful info to stderr for the user to understand.188+ // Output from stderr must be ignored by the completion script.189+ fmt.Fprintf(finalCmd.ErrOrStderr(), "Completion ended with directive: %s\n", directive.string())190+ },191+ }192+ c.AddCommand(completeCmd)193+ subCmd, _, err := c.Find(args)194+ if err != nil || subCmd.Name() != ShellCompRequestCmd {195+ // Only create this special command if it is actually being called.196+ // This reduces possible side-effects of creating such a command;197+ // for example, having this command would cause problems to a198+ // cobra program that only consists of the root command, since this199+ // command would cause the root command to suddenly have a subcommand.200+ c.RemoveCommand(completeCmd)201+ }202+}203+204+func (c *Command) getCompletions(args []string) (*Command, []string, ShellCompDirective, error) {205+ // The last argument, which is not completely typed by the user,206+ // should not be part of the list of arguments207+ toComplete := args[len(args)-1]208+ trimmedArgs := args[:len(args)-1]209+210+ var finalCmd *Command211+ var finalArgs []string212+ var err error213+ // Find the real command for which completion must be performed214+ // check if we need to traverse here to parse local flags on parent commands215+ if c.Root().TraverseChildren {216+ finalCmd, finalArgs, err = c.Root().Traverse(trimmedArgs)217+ } else {218+ finalCmd, finalArgs, err = c.Root().Find(trimmedArgs)219+ }220+ if err != nil {221+ // Unable to find the real command. E.g., <program> someInvalidCmd <TAB>222+ return c, []string{}, ShellCompDirectiveDefault, fmt.Errorf("Unable to find a command for arguments: %v", trimmedArgs)223+ }224+225+ // Check if we are doing flag value completion before parsing the flags.226+ // This is important because if we are completing a flag value, we need to also227+ // remove the flag name argument from the list of finalArgs or else the parsing228+ // could fail due to an invalid value (incomplete) for the flag.229+ flag, finalArgs, toComplete, err := checkIfFlagCompletion(finalCmd, finalArgs, toComplete)230+ if err != nil {231+ // Error while attempting to parse flags232+ return finalCmd, []string{}, ShellCompDirectiveDefault, err233+ }234+235+ // Parse the flags early so we can check if required flags are set236+ if err = finalCmd.ParseFlags(finalArgs); err != nil {237+ return finalCmd, []string{}, ShellCompDirectiveDefault, fmt.Errorf("Error while parsing flags from args %v: %s", finalArgs, err.Error())238+ }239+240+ if flag != nil {241+ // Check if we are completing a flag value subject to annotations242+ if validExts, present := flag.Annotations[BashCompFilenameExt]; present {243+ if len(validExts) != 0 {244+ // File completion filtered by extensions245+ return finalCmd, validExts, ShellCompDirectiveFilterFileExt, nil246+ }247+248+ // The annotation requests simple file completion. There is no reason to do249+ // that since it is the default behavior anyway. Let's ignore this annotation250+ // in case the program also registered a completion function for this flag.251+ // Even though it is a mistake on the program's side, let's be nice when we can.252+ }253+254+ if subDir, present := flag.Annotations[BashCompSubdirsInDir]; present {255+ if len(subDir) == 1 {256+ // Directory completion from within a directory257+ return finalCmd, subDir, ShellCompDirectiveFilterDirs, nil258+ }259+ // Directory completion260+ return finalCmd, []string{}, ShellCompDirectiveFilterDirs, nil261+ }262+ }263+264+ // When doing completion of a flag name, as soon as an argument starts with265+ // a '-' we know it is a flag. We cannot use isFlagArg() here as it requires266+ // the flag name to be complete267+ if flag == nil && len(toComplete) > 0 && toComplete[0] == '-' && !strings.Contains(toComplete, "=") {268+ var completions []string269+270+ // First check for required flags271+ completions = completeRequireFlags(finalCmd, toComplete)272+273+ // If we have not found any required flags, only then can we show regular flags274+ if len(completions) == 0 {275+ doCompleteFlags := func(flag *pflag.Flag) {276+ if !flag.Changed ||277+ strings.Contains(flag.Value.Type(), "Slice") ||278+ strings.Contains(flag.Value.Type(), "Array") {279+ // If the flag is not already present, or if it can be specified multiple times (Array or Slice)280+ // we suggest it as a completion281+ completions = append(completions, getFlagNameCompletions(flag, toComplete)...)282+ }283+ }284+285+ // We cannot use finalCmd.Flags() because we may not have called ParsedFlags() for commands286+ // that have set DisableFlagParsing; it is ParseFlags() that merges the inherited and287+ // non-inherited flags.288+ finalCmd.InheritedFlags().VisitAll(func(flag *pflag.Flag) {289+ doCompleteFlags(flag)290+ })291+ finalCmd.NonInheritedFlags().VisitAll(func(flag *pflag.Flag) {292+ doCompleteFlags(flag)293+ })294+ }295+296+ directive := ShellCompDirectiveNoFileComp297+ if len(completions) == 1 && strings.HasSuffix(completions[0], "=") {298+ // If there is a single completion, the shell usually adds a space299+ // after the completion. We don't want that if the flag ends with an =300+ directive = ShellCompDirectiveNoSpace301+ }302+ return finalCmd, completions, directive, nil303+ }304+305+ // We only remove the flags from the arguments if DisableFlagParsing is not set.306+ // This is important for commands which have requested to do their own flag completion.307+ if !finalCmd.DisableFlagParsing {308+ finalArgs = finalCmd.Flags().Args()309+ }310+311+ var completions []string312+ directive := ShellCompDirectiveDefault313+ if flag == nil {314+ foundLocalNonPersistentFlag := false315+ // If TraverseChildren is true on the root command we don't check for316+ // local flags because we can use a local flag on a parent command317+ if !finalCmd.Root().TraverseChildren {318+ // Check if there are any local, non-persistent flags on the command-line319+ localNonPersistentFlags := finalCmd.LocalNonPersistentFlags()320+ finalCmd.NonInheritedFlags().VisitAll(func(flag *pflag.Flag) {321+ if localNonPersistentFlags.Lookup(flag.Name) != nil && flag.Changed {322+ foundLocalNonPersistentFlag = true323+ }324+ })325+ }326+327+ // Complete subcommand names, including the help command328+ if len(finalArgs) == 0 && !foundLocalNonPersistentFlag {329+ // We only complete sub-commands if:330+ // - there are no arguments on the command-line and331+ // - there are no local, non-peristent flag on the command-line or TraverseChildren is true332+ for _, subCmd := range finalCmd.Commands() {333+ if subCmd.IsAvailableCommand() || subCmd == finalCmd.helpCommand {334+ if strings.HasPrefix(subCmd.Name(), toComplete) {335+ completions = append(completions, fmt.Sprintf("%s\t%s", subCmd.Name(), subCmd.Short))336+ }337+ directive = ShellCompDirectiveNoFileComp338+ }339+ }340+ }341+342+ // Complete required flags even without the '-' prefix343+ completions = append(completions, completeRequireFlags(finalCmd, toComplete)...)344+345+ // Always complete ValidArgs, even if we are completing a subcommand name.346+ // This is for commands that have both subcommands and ValidArgs.347+ if len(finalCmd.ValidArgs) > 0 {348+ if len(finalArgs) == 0 {349+ // ValidArgs are only for the first argument350+ for _, validArg := range finalCmd.ValidArgs {351+ if strings.HasPrefix(validArg, toComplete) {352+ completions = append(completions, validArg)353+ }354+ }355+ directive = ShellCompDirectiveNoFileComp356+357+ // If no completions were found within commands or ValidArgs,358+ // see if there are any ArgAliases that should be completed.359+ if len(completions) == 0 {360+ for _, argAlias := range finalCmd.ArgAliases {361+ if strings.HasPrefix(argAlias, toComplete) {362+ completions = append(completions, argAlias)363+ }364+ }365+ }366+ }367+368+ // If there are ValidArgs specified (even if they don't match), we stop completion.369+ // Only one of ValidArgs or ValidArgsFunction can be used for a single command.370+ return finalCmd, completions, directive, nil371+ }372+373+ // Let the logic continue so as to add any ValidArgsFunction completions,374+ // even if we already found sub-commands.375+ // This is for commands that have subcommands but also specify a ValidArgsFunction.376+ }377+378+ // Find the completion function for the flag or command379+ var completionFn func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective)380+ if flag != nil {381+ completionFn = flagCompletionFunctions[flag]382+ } else {383+ completionFn = finalCmd.ValidArgsFunction384+ }385+ if completionFn != nil {386+ // Go custom completion defined for this flag or command.387+ // Call the registered completion function to get the completions.388+ var comps []string389+ comps, directive = completionFn(finalCmd, finalArgs, toComplete)390+ completions = append(completions, comps...)391+ }392+393+ return finalCmd, completions, directive, nil394+}395+396+func getFlagNameCompletions(flag *pflag.Flag, toComplete string) []string {397+ if nonCompletableFlag(flag) {398+ return []string{}399+ }400+401+ var completions []string402+ flagName := "--" + flag.Name403+ if strings.HasPrefix(flagName, toComplete) {404+ // Flag without the =405+ completions = append(completions, fmt.Sprintf("%s\t%s", flagName, flag.Usage))406+407+ // Why suggest both long forms: --flag and --flag= ?408+ // This forces the user to *always* have to type either an = or a space after the flag name.409+ // Let's be nice and avoid making users have to do that.410+ // Since boolean flags and shortname flags don't show the = form, let's go that route and never show it.411+ // The = form will still work, we just won't suggest it.412+ // This also makes the list of suggested flags shorter as we avoid all the = forms.413+ //414+ // if len(flag.NoOptDefVal) == 0 {415+ // // Flag requires a value, so it can be suffixed with =416+ // flagName += "="417+ // completions = append(completions, fmt.Sprintf("%s\t%s", flagName, flag.Usage))418+ // }419+ }420+421+ flagName = "-" + flag.Shorthand422+ if len(flag.Shorthand) > 0 && strings.HasPrefix(flagName, toComplete) {423+ completions = append(completions, fmt.Sprintf("%s\t%s", flagName, flag.Usage))424+ }425+426+ return completions427+}428+429+func completeRequireFlags(finalCmd *Command, toComplete string) []string {430+ var completions []string431+432+ doCompleteRequiredFlags := func(flag *pflag.Flag) {433+ if _, present := flag.Annotations[BashCompOneRequiredFlag]; present {434+ if !flag.Changed {435+ // If the flag is not already present, we suggest it as a completion436+ completions = append(completions, getFlagNameCompletions(flag, toComplete)...)437+ }438+ }439+ }440+441+ // We cannot use finalCmd.Flags() because we may not have called ParsedFlags() for commands442+ // that have set DisableFlagParsing; it is ParseFlags() that merges the inherited and443+ // non-inherited flags.444+ finalCmd.InheritedFlags().VisitAll(func(flag *pflag.Flag) {445+ doCompleteRequiredFlags(flag)446+ })447+ finalCmd.NonInheritedFlags().VisitAll(func(flag *pflag.Flag) {448+ doCompleteRequiredFlags(flag)449+ })450+451+ return completions452+}453+454+func checkIfFlagCompletion(finalCmd *Command, args []string, lastArg string) (*pflag.Flag, []string, string, error) {455+ if finalCmd.DisableFlagParsing {456+ // We only do flag completion if we are allowed to parse flags457+ // This is important for commands which have requested to do their own flag completion.458+ return nil, args, lastArg, nil459+ }460+461+ var flagName string462+ trimmedArgs := args463+ flagWithEqual := false464+465+ // When doing completion of a flag name, as soon as an argument starts with466+ // a '-' we know it is a flag. We cannot use isFlagArg() here as that function467+ // requires the flag name to be complete468+ if len(lastArg) > 0 && lastArg[0] == '-' {469+ if index := strings.Index(lastArg, "="); index >= 0 {470+ // Flag with an =471+ flagName = strings.TrimLeft(lastArg[:index], "-")472+ lastArg = lastArg[index+1:]473+ flagWithEqual = true474+ } else {475+ // Normal flag completion476+ return nil, args, lastArg, nil477+ }478+ }479+480+ if len(flagName) == 0 {481+ if len(args) > 0 {482+ prevArg := args[len(args)-1]483+ if isFlagArg(prevArg) {484+ // Only consider the case where the flag does not contain an =.485+ // If the flag contains an = it means it has already been fully processed,486+ // so we don't need to deal with it here.487+ if index := strings.Index(prevArg, "="); index < 0 {488+ flagName = strings.TrimLeft(prevArg, "-")489+490+ // Remove the uncompleted flag or else there could be an error created491+ // for an invalid value for that flag492+ trimmedArgs = args[:len(args)-1]493+ }494+ }495+ }496+ }497+498+ if len(flagName) == 0 {499+ // Not doing flag completion500+ return nil, trimmedArgs, lastArg, nil501+ }502+503+ flag := findFlag(finalCmd, flagName)504+ if flag == nil {505+ // Flag not supported by this command, nothing to complete506+ err := fmt.Errorf("Subcommand '%s' does not support flag '%s'", finalCmd.Name(), flagName)507+ return nil, nil, "", err508+ }509+510+ if !flagWithEqual {511+ if len(flag.NoOptDefVal) != 0 {512+ // We had assumed dealing with a two-word flag but the flag is a boolean flag.513+ // In that case, there is no value following it, so we are not really doing flag completion.514+ // Reset everything to do noun completion.515+ trimmedArgs = args516+ flag = nil517+ }518+ }519+520+ return flag, trimmedArgs, lastArg, nil521+}522+523+// initDefaultCompletionCmd adds a default 'completion' command to c.524+// This function will do nothing if any of the following is true:525+// 1- the feature has been explicitly disabled by the program,526+// 2- c has no subcommands (to avoid creating one),527+// 3- c already has a 'completion' command provided by the program.528+func (c *Command) initDefaultCompletionCmd() {529+ if c.CompletionOptions.DisableDefaultCmd || !c.HasSubCommands() {530+ return531+ }532+533+ for _, cmd := range c.commands {534+ if cmd.Name() == compCmdName || cmd.HasAlias(compCmdName) {535+ // A completion command is already available536+ return537+ }538+ }539+540+ haveNoDescFlag := !c.CompletionOptions.DisableNoDescFlag && !c.CompletionOptions.DisableDescriptions541+542+ completionCmd := &Command{543+ Use: compCmdName,544+ Short: "generate the autocompletion script for the specified shell",545+ Long: fmt.Sprintf(`546+Generate the autocompletion script for %[1]s for the specified shell.547+See each sub-command's help for details on how to use the generated script.548+`, c.Root().Name()),549+ Args: NoArgs,550+ ValidArgsFunction: NoFileCompletions,551+ }552+ c.AddCommand(completionCmd)553+554+ out := c.OutOrStdout()555+ noDesc := c.CompletionOptions.DisableDescriptions556+ shortDesc := "generate the autocompletion script for %s"557+ bash := &Command{558+ Use: "bash",559+ Short: fmt.Sprintf(shortDesc, "bash"),560+ Long: fmt.Sprintf(`561+Generate the autocompletion script for the bash shell.562+563+This script depends on the 'bash-completion' package.564+If it is not installed already, you can install it via your OS's package manager.565+566+To load completions in your current shell session:567+$ source <(%[1]s completion bash)568+569+To load completions for every new session, execute once:570+Linux:571+ $ %[1]s completion bash > /etc/bash_completion.d/%[1]s572+MacOS:573+ $ %[1]s completion bash > /usr/local/etc/bash_completion.d/%[1]s574+575+You will need to start a new shell for this setup to take effect.576+ `, c.Root().Name()),577+ Args: NoArgs,578+ DisableFlagsInUseLine: true,579+ ValidArgsFunction: NoFileCompletions,580+ RunE: func(cmd *Command, args []string) error {581+ return cmd.Root().GenBashCompletion(out)582+ },583+ }584+585+ zsh := &Command{586+ Use: "zsh",587+ Short: fmt.Sprintf(shortDesc, "zsh"),588+ Long: fmt.Sprintf(`589+Generate the autocompletion script for the zsh shell.590+591+If shell completion is not already enabled in your environment you will need592+to enable it. You can execute the following once:593+594+$ echo "autoload -U compinit; compinit" >> ~/.zshrc595+596+To load completions for every new session, execute once:597+$ %[1]s completion zsh > "${fpath[1]}/_%[1]s"598+599+You will need to start a new shell for this setup to take effect.600+`, c.Root().Name()),601+ Args: NoArgs,602+ ValidArgsFunction: NoFileCompletions,603+ RunE: func(cmd *Command, args []string) error {604+ if noDesc {605+ return cmd.Root().GenZshCompletionNoDesc(out)606+ }607+ return cmd.Root().GenZshCompletion(out)608+ },609+ }610+ if haveNoDescFlag {611+ zsh.Flags().BoolVar(&noDesc, compCmdNoDescFlagName, compCmdNoDescFlagDefault, compCmdNoDescFlagDesc)612+ }613+614+ fish := &Command{615+ Use: "fish",616+ Short: fmt.Sprintf(shortDesc, "fish"),617+ Long: fmt.Sprintf(`618+Generate the autocompletion script for the fish shell.619+620+To load completions in your current shell session:621+$ %[1]s completion fish | source622+623+To load completions for every new session, execute once:624+$ %[1]s completion fish > ~/.config/fish/completions/%[1]s.fish625+626+You will need to start a new shell for this setup to take effect.627+`, c.Root().Name()),628+ Args: NoArgs,629+ ValidArgsFunction: NoFileCompletions,630+ RunE: func(cmd *Command, args []string) error {631+ return cmd.Root().GenFishCompletion(out, !noDesc)632+ },633+ }634+ if haveNoDescFlag {635+ fish.Flags().BoolVar(&noDesc, compCmdNoDescFlagName, compCmdNoDescFlagDefault, compCmdNoDescFlagDesc)636+ }637+638+ powershell := &Command{639+ Use: "powershell",640+ Short: fmt.Sprintf(shortDesc, "powershell"),641+ Long: fmt.Sprintf(`642+Generate the autocompletion script for powershell.643+644+To load completions in your current shell session:645+PS C:\> %[1]s completion powershell | Out-String | Invoke-Expression646+647+To load completions for every new session, add the output of the above command648+to your powershell profile.649+`, c.Root().Name()),650+ Args: NoArgs,651+ ValidArgsFunction: NoFileCompletions,652+ RunE: func(cmd *Command, args []string) error {653+ if noDesc {654+ return cmd.Root().GenPowerShellCompletion(out)655+ }656+ return cmd.Root().GenPowerShellCompletionWithDesc(out)657+658+ },659+ }660+ if haveNoDescFlag {661+ powershell.Flags().BoolVar(&noDesc, compCmdNoDescFlagName, compCmdNoDescFlagDefault, compCmdNoDescFlagDesc)662+ }663+664+ completionCmd.AddCommand(bash, zsh, fish, powershell)665+}666+667+func findFlag(cmd *Command, name string) *pflag.Flag {668+ flagSet := cmd.Flags()669+ if len(name) == 1 {670+ // First convert the short flag into a long flag671+ // as the cmd.Flag() search only accepts long flags672+ if short := flagSet.ShorthandLookup(name); short != nil {673+ name = short.Name674+ } else {675+ set := cmd.InheritedFlags()676+ if short = set.ShorthandLookup(name); short != nil {677+ name = short.Name678+ } else {679+ return nil680+ }681+ }682+ }683+ return cmd.Flag(name)684+}685+686+// CompDebug prints the specified string to the same file as where the687+// completion script prints its logs.688+// Note that completion printouts should never be on stdout as they would689+// be wrongly interpreted as actual completion choices by the completion script.690+func CompDebug(msg string, printToStdErr bool) {691+ msg = fmt.Sprintf("[Debug] %s", msg)692+693+ // Such logs are only printed when the user has set the environment694+ // variable BASH_COMP_DEBUG_FILE to the path of some file to be used.695+ if path := os.Getenv("BASH_COMP_DEBUG_FILE"); path != "" {696+ f, err := os.OpenFile(path,697+ os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)698+ if err == nil {699+ defer f.Close()700+ WriteStringAndCheck(f, msg)701+ }702+ }703+704+ if printToStdErr {705+ // Must print to stderr for this not to be read by the completion script.706+ fmt.Fprint(os.Stderr, msg)707+ }708+}709+710+// CompDebugln prints the specified string with a newline at the end711+// to the same file as where the completion script prints its logs.712+// Such logs are only printed when the user has set the environment713+// variable BASH_COMP_DEBUG_FILE to the path of some file to be used.714+func CompDebugln(msg string, printToStdErr bool) {715+ CompDebug(fmt.Sprintf("%s\n", msg), printToStdErr)716+}717+718+// CompError prints the specified completion message to stderr.719+func CompError(msg string) {720+ msg = fmt.Sprintf("[Error] %s", msg)721+ CompDebug(msg, true)722+}723+724+// CompErrorln prints the specified completion message to stderr with a newline at the end.725+func CompErrorln(msg string) {726+ CompError(fmt.Sprintf("%s\n", msg))727+}deleted:custom_completions_test.go-1960 removed
1-package cobra2-3-import (4- "bytes"5- "strings"6- "testing"7-)8-9-func validArgsFunc(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective) {10- if len(args) != 0 {11- return nil, ShellCompDirectiveNoFileComp12- }13-14- var completions []string15- for _, comp := range []string{"one\tThe first", "two\tThe second"} {16- if strings.HasPrefix(comp, toComplete) {17- completions = append(completions, comp)18- }19- }20- return completions, ShellCompDirectiveDefault21-}22-23-func validArgsFunc2(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective) {24- if len(args) != 0 {25- return nil, ShellCompDirectiveNoFileComp26- }27-28- var completions []string29- for _, comp := range []string{"three\tThe third", "four\tThe fourth"} {30- if strings.HasPrefix(comp, toComplete) {31- completions = append(completions, comp)32- }33- }34- return completions, ShellCompDirectiveDefault35-}36-37-func TestCmdNameCompletionInGo(t *testing.T) {38- rootCmd := &Command{39- Use: "root",40- Run: emptyRun,41- }42- childCmd1 := &Command{43- Use: "firstChild",44- Short: "First command",45- Run: emptyRun,46- }47- childCmd2 := &Command{48- Use: "secondChild",49- Run: emptyRun,50- }51- hiddenCmd := &Command{52- Use: "testHidden",53- Hidden: true, // Not completed54- Run: emptyRun,55- }56- deprecatedCmd := &Command{57- Use: "testDeprecated",58- Deprecated: "deprecated", // Not completed59- Run: emptyRun,60- }61- aliasedCmd := &Command{62- Use: "aliased",63- Short: "A command with aliases",64- Aliases: []string{"testAlias", "testSynonym"}, // Not completed65- Run: emptyRun,66- }67-68- rootCmd.AddCommand(childCmd1, childCmd2, hiddenCmd, deprecatedCmd, aliasedCmd)69-70- // Test that sub-command names are completed71- output, err := executeCommand(rootCmd, ShellCompNoDescRequestCmd, "")72- if err != nil {73- t.Errorf("Unexpected error: %v", err)74- }75-76- expected := strings.Join([]string{77- "aliased",78- "firstChild",79- "help",80- "secondChild",81- ":4",82- "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")83-84- if output != expected {85- t.Errorf("expected: %q, got: %q", expected, output)86- }87-88- // Test that sub-command names are completed with prefix89- output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "s")90- if err != nil {91- t.Errorf("Unexpected error: %v", err)92- }93-94- expected = strings.Join([]string{95- "secondChild",96- ":4",97- "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")98-99- if output != expected {100- t.Errorf("expected: %q, got: %q", expected, output)101- }102-103- // Test that even with no valid sub-command matches, hidden, deprecated and104- // aliases are not completed105- output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "test")106- if err != nil {107- t.Errorf("Unexpected error: %v", err)108- }109-110- expected = strings.Join([]string{111- ":4",112- "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")113-114- if output != expected {115- t.Errorf("expected: %q, got: %q", expected, output)116- }117-118- // Test that sub-command names are completed with description119- output, err = executeCommand(rootCmd, ShellCompRequestCmd, "")120- if err != nil {121- t.Errorf("Unexpected error: %v", err)122- }123-124- expected = strings.Join([]string{125- "aliased\tA command with aliases",126- "firstChild\tFirst command",127- "help\tHelp about any command",128- "secondChild",129- ":4",130- "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")131-132- if output != expected {133- t.Errorf("expected: %q, got: %q", expected, output)134- }135-}136-137-func TestNoCmdNameCompletionInGo(t *testing.T) {138- rootCmd := &Command{139- Use: "root",140- Run: emptyRun,141- }142- rootCmd.Flags().String("localroot", "", "local root flag")143-144- childCmd1 := &Command{145- Use: "childCmd1",146- Short: "First command",147- Args: MinimumNArgs(0),148- Run: emptyRun,149- }150- rootCmd.AddCommand(childCmd1)151- childCmd1.PersistentFlags().StringP("persistent", "p", "", "persistent flag")152- persistentFlag := childCmd1.PersistentFlags().Lookup("persistent")153- childCmd1.Flags().StringP("nonPersistent", "n", "", "non-persistent flag")154- nonPersistentFlag := childCmd1.Flags().Lookup("nonPersistent")155-156- childCmd2 := &Command{157- Use: "childCmd2",158- Run: emptyRun,159- }160- childCmd1.AddCommand(childCmd2)161-162- // Test that sub-command names are not completed if there is an argument already163- output, err := executeCommand(rootCmd, ShellCompNoDescRequestCmd, "childCmd1", "arg1", "")164- if err != nil {165- t.Errorf("Unexpected error: %v", err)166- }167-168- expected := strings.Join([]string{169- ":0",170- "Completion ended with directive: ShellCompDirectiveDefault", ""}, "\n")171-172- if output != expected {173- t.Errorf("expected: %q, got: %q", expected, output)174- }175-176- // Test that sub-command names are not completed if a local non-persistent flag is present177- output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "childCmd1", "--nonPersistent", "value", "")178- if err != nil {179- t.Errorf("Unexpected error: %v", err)180- }181- // Reset the flag for the next command182- nonPersistentFlag.Changed = false183-184- expected = strings.Join([]string{185- ":0",186- "Completion ended with directive: ShellCompDirectiveDefault", ""}, "\n")187-188- if output != expected {189- t.Errorf("expected: %q, got: %q", expected, output)190- }191-192- // Test that sub-command names are completed if a local non-persistent flag is present and TraverseChildren is set to true193- // set TraverseChildren to true on the root cmd194- rootCmd.TraverseChildren = true195-196- output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "--localroot", "value", "")197- if err != nil {198- t.Errorf("Unexpected error: %v", err)199- }200- // Reset TraverseChildren for next command201- rootCmd.TraverseChildren = false202-203- expected = strings.Join([]string{204- "childCmd1",205- "help",206- ":4",207- "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")208-209- if output != expected {210- t.Errorf("expected: %q, got: %q", expected, output)211- }212-213- // Test that sub-command names from a child cmd are completed if a local non-persistent flag is present214- // and TraverseChildren is set to true on the root cmd215- rootCmd.TraverseChildren = true216-217- output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "--localroot", "value", "childCmd1", "--nonPersistent", "value", "")218- if err != nil {219- t.Errorf("Unexpected error: %v", err)220- }221- // Reset TraverseChildren for next command222- rootCmd.TraverseChildren = false223- // Reset the flag for the next command224- nonPersistentFlag.Changed = false225-226- expected = strings.Join([]string{227- "childCmd2",228- ":4",229- "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")230-231- if output != expected {232- t.Errorf("expected: %q, got: %q", expected, output)233- }234-235- // Test that we don't use Traverse when we shouldn't.236- // This command should not return a completion since the command line is invalid without TraverseChildren.237- output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "--localroot", "value", "childCmd1", "")238- if err != nil {239- t.Errorf("Unexpected error: %v", err)240- }241-242- expected = strings.Join([]string{243- ":0",244- "Completion ended with directive: ShellCompDirectiveDefault", ""}, "\n")245-246- if output != expected {247- t.Errorf("expected: %q, got: %q", expected, output)248- }249-250- // Test that sub-command names are not completed if a local non-persistent short flag is present251- output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "childCmd1", "-n", "value", "")252- if err != nil {253- t.Errorf("Unexpected error: %v", err)254- }255- // Reset the flag for the next command256- nonPersistentFlag.Changed = false257-258- expected = strings.Join([]string{259- ":0",260- "Completion ended with directive: ShellCompDirectiveDefault", ""}, "\n")261-262- if output != expected {263- t.Errorf("expected: %q, got: %q", expected, output)264- }265-266- // Test that sub-command names are completed with a persistent flag267- output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "childCmd1", "--persistent", "value", "")268- if err != nil {269- t.Errorf("Unexpected error: %v", err)270- }271- // Reset the flag for the next command272- persistentFlag.Changed = false273-274- expected = strings.Join([]string{275- "childCmd2",276- ":4",277- "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")278-279- if output != expected {280- t.Errorf("expected: %q, got: %q", expected, output)281- }282-283- // Test that sub-command names are completed with a persistent short flag284- output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "childCmd1", "-p", "value", "")285- if err != nil {286- t.Errorf("Unexpected error: %v", err)287- }288- // Reset the flag for the next command289- persistentFlag.Changed = false290-291- expected = strings.Join([]string{292- "childCmd2",293- ":4",294- "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")295-296- if output != expected {297- t.Errorf("expected: %q, got: %q", expected, output)298- }299-}300-301-func TestValidArgsCompletionInGo(t *testing.T) {302- rootCmd := &Command{303- Use: "root",304- ValidArgs: []string{"one", "two", "three"},305- Args: MinimumNArgs(1),306- }307-308- // Test that validArgs are completed309- output, err := executeCommand(rootCmd, ShellCompNoDescRequestCmd, "")310- if err != nil {311- t.Errorf("Unexpected error: %v", err)312- }313-314- expected := strings.Join([]string{315- "one",316- "two",317- "three",318- ":4",319- "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")320-321- if output != expected {322- t.Errorf("expected: %q, got: %q", expected, output)323- }324-325- // Test that validArgs are completed with prefix326- output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "o")327- if err != nil {328- t.Errorf("Unexpected error: %v", err)329- }330-331- expected = strings.Join([]string{332- "one",333- ":4",334- "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")335-336- if output != expected {337- t.Errorf("expected: %q, got: %q", expected, output)338- }339-340- // Test that validArgs don't repeat341- output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "one", "")342- if err != nil {343- t.Errorf("Unexpected error: %v", err)344- }345-346- expected = strings.Join([]string{347- ":0",348- "Completion ended with directive: ShellCompDirectiveDefault", ""}, "\n")349-350- if output != expected {351- t.Errorf("expected: %q, got: %q", expected, output)352- }353-}354-355-func TestValidArgsAndCmdCompletionInGo(t *testing.T) {356- rootCmd := &Command{357- Use: "root",358- ValidArgs: []string{"one", "two"},359- Run: emptyRun,360- }361-362- childCmd := &Command{363- Use: "thechild",364- Run: emptyRun,365- }366-367- rootCmd.AddCommand(childCmd)368-369- // Test that both sub-commands and validArgs are completed370- output, err := executeCommand(rootCmd, ShellCompNoDescRequestCmd, "")371- if err != nil {372- t.Errorf("Unexpected error: %v", err)373- }374-375- expected := strings.Join([]string{376- "help",377- "thechild",378- "one",379- "two",380- ":4",381- "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")382-383- if output != expected {384- t.Errorf("expected: %q, got: %q", expected, output)385- }386-387- // Test that both sub-commands and validArgs are completed with prefix388- output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "t")389- if err != nil {390- t.Errorf("Unexpected error: %v", err)391- }392-393- expected = strings.Join([]string{394- "thechild",395- "two",396- ":4",397- "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")398-399- if output != expected {400- t.Errorf("expected: %q, got: %q", expected, output)401- }402-}403-404-func TestValidArgsFuncAndCmdCompletionInGo(t *testing.T) {405- rootCmd := &Command{406- Use: "root",407- ValidArgsFunction: validArgsFunc,408- Run: emptyRun,409- }410-411- childCmd := &Command{412- Use: "thechild",413- Short: "The child command",414- Run: emptyRun,415- }416-417- rootCmd.AddCommand(childCmd)418-419- // Test that both sub-commands and validArgsFunction are completed420- output, err := executeCommand(rootCmd, ShellCompNoDescRequestCmd, "")421- if err != nil {422- t.Errorf("Unexpected error: %v", err)423- }424-425- expected := strings.Join([]string{426- "help",427- "thechild",428- "one",429- "two",430- ":0",431- "Completion ended with directive: ShellCompDirectiveDefault", ""}, "\n")432-433- if output != expected {434- t.Errorf("expected: %q, got: %q", expected, output)435- }436-437- // Test that both sub-commands and validArgs are completed with prefix438- output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "t")439- if err != nil {440- t.Errorf("Unexpected error: %v", err)441- }442-443- expected = strings.Join([]string{444- "thechild",445- "two",446- ":0",447- "Completion ended with directive: ShellCompDirectiveDefault", ""}, "\n")448-449- if output != expected {450- t.Errorf("expected: %q, got: %q", expected, output)451- }452-453- // Test that both sub-commands and validArgs are completed with description454- output, err = executeCommand(rootCmd, ShellCompRequestCmd, "t")455- if err != nil {456- t.Errorf("Unexpected error: %v", err)457- }458-459- expected = strings.Join([]string{460- "thechild\tThe child command",461- "two\tThe second",462- ":0",463- "Completion ended with directive: ShellCompDirectiveDefault", ""}, "\n")464-465- if output != expected {466- t.Errorf("expected: %q, got: %q", expected, output)467- }468-}469-470-func TestFlagNameCompletionInGo(t *testing.T) {471- rootCmd := &Command{472- Use: "root",473- Run: emptyRun,474- }475- childCmd := &Command{476- Use: "childCmd",477- Run: emptyRun,478- }479- rootCmd.AddCommand(childCmd)480-481- rootCmd.Flags().IntP("first", "f", -1, "first flag")482- rootCmd.PersistentFlags().BoolP("second", "s", false, "second flag")483- childCmd.Flags().String("subFlag", "", "sub flag")484-485- // Test that flag names are not shown if the user has not given the '-' prefix486- output, err := executeCommand(rootCmd, ShellCompNoDescRequestCmd, "")487- if err != nil {488- t.Errorf("Unexpected error: %v", err)489- }490-491- expected := strings.Join([]string{492- "childCmd",493- "help",494- ":4",495- "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")496-497- if output != expected {498- t.Errorf("expected: %q, got: %q", expected, output)499- }500-501- // Test that flag names are completed502- output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "-")503- if err != nil {504- t.Errorf("Unexpected error: %v", err)505- }506-507- expected = strings.Join([]string{508- "--first",509- "-f",510- "--second",511- "-s",512- ":4",513- "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")514-515- if output != expected {516- t.Errorf("expected: %q, got: %q", expected, output)517- }518-519- // Test that flag names are completed when a prefix is given520- output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "--f")521- if err != nil {522- t.Errorf("Unexpected error: %v", err)523- }524-525- expected = strings.Join([]string{526- "--first",527- ":4",528- "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")529-530- if output != expected {531- t.Errorf("expected: %q, got: %q", expected, output)532- }533-534- // Test that flag names are completed in a sub-cmd535- output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "childCmd", "-")536- if err != nil {537- t.Errorf("Unexpected error: %v", err)538- }539-540- expected = strings.Join([]string{541- "--second",542- "-s",543- "--subFlag",544- ":4",545- "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")546-547- if output != expected {548- t.Errorf("expected: %q, got: %q", expected, output)549- }550-}551-552-func TestFlagNameCompletionInGoWithDesc(t *testing.T) {553- rootCmd := &Command{554- Use: "root",555- Run: emptyRun,556- }557- childCmd := &Command{558- Use: "childCmd",559- Short: "first command",560- Run: emptyRun,561- }562- rootCmd.AddCommand(childCmd)563-564- rootCmd.Flags().IntP("first", "f", -1, "first flag\nlonger description for flag")565- rootCmd.PersistentFlags().BoolP("second", "s", false, "second flag")566- childCmd.Flags().String("subFlag", "", "sub flag")567-568- // Test that flag names are not shown if the user has not given the '-' prefix569- output, err := executeCommand(rootCmd, ShellCompRequestCmd, "")570- if err != nil {571- t.Errorf("Unexpected error: %v", err)572- }573-574- expected := strings.Join([]string{575- "childCmd\tfirst command",576- "help\tHelp about any command",577- ":4",578- "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")579-580- if output != expected {581- t.Errorf("expected: %q, got: %q", expected, output)582- }583-584- // Test that flag names are completed585- output, err = executeCommand(rootCmd, ShellCompRequestCmd, "-")586- if err != nil {587- t.Errorf("Unexpected error: %v", err)588- }589-590- expected = strings.Join([]string{591- "--first\tfirst flag",592- "-f\tfirst flag",593- "--second\tsecond flag",594- "-s\tsecond flag",595- ":4",596- "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")597-598- if output != expected {599- t.Errorf("expected: %q, got: %q", expected, output)600- }601-602- // Test that flag names are completed when a prefix is given603- output, err = executeCommand(rootCmd, ShellCompRequestCmd, "--f")604- if err != nil {605- t.Errorf("Unexpected error: %v", err)606- }607-608- expected = strings.Join([]string{609- "--first\tfirst flag",610- ":4",611- "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")612-613- if output != expected {614- t.Errorf("expected: %q, got: %q", expected, output)615- }616-617- // Test that flag names are completed in a sub-cmd618- output, err = executeCommand(rootCmd, ShellCompRequestCmd, "childCmd", "-")619- if err != nil {620- t.Errorf("Unexpected error: %v", err)621- }622-623- expected = strings.Join([]string{624- "--second\tsecond flag",625- "-s\tsecond flag",626- "--subFlag\tsub flag",627- ":4",628- "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")629-630- if output != expected {631- t.Errorf("expected: %q, got: %q", expected, output)632- }633-}634-635-func TestFlagNameCompletionRepeat(t *testing.T) {636- rootCmd := &Command{637- Use: "root",638- Run: emptyRun,639- }640- childCmd := &Command{641- Use: "childCmd",642- Short: "first command",643- Run: emptyRun,644- }645- rootCmd.AddCommand(childCmd)646-647- rootCmd.Flags().IntP("first", "f", -1, "first flag")648- firstFlag := rootCmd.Flags().Lookup("first")649- rootCmd.Flags().BoolP("second", "s", false, "second flag")650- secondFlag := rootCmd.Flags().Lookup("second")651- rootCmd.Flags().StringArrayP("array", "a", nil, "array flag")652- arrayFlag := rootCmd.Flags().Lookup("array")653- rootCmd.Flags().IntSliceP("slice", "l", nil, "slice flag")654- sliceFlag := rootCmd.Flags().Lookup("slice")655- rootCmd.Flags().BoolSliceP("bslice", "b", nil, "bool slice flag")656- bsliceFlag := rootCmd.Flags().Lookup("bslice")657-658- // Test that flag names are not repeated unless they are an array or slice659- output, err := executeCommand(rootCmd, ShellCompNoDescRequestCmd, "--first", "1", "--")660- if err != nil {661- t.Errorf("Unexpected error: %v", err)662- }663- // Reset the flag for the next command664- firstFlag.Changed = false665-666- expected := strings.Join([]string{667- "--array",668- "--bslice",669- "--second",670- "--slice",671- ":4",672- "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")673-674- if output != expected {675- t.Errorf("expected: %q, got: %q", expected, output)676- }677-678- // Test that flag names are not repeated unless they are an array or slice679- output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "--first", "1", "--second=false", "--")680- if err != nil {681- t.Errorf("Unexpected error: %v", err)682- }683- // Reset the flag for the next command684- firstFlag.Changed = false685- secondFlag.Changed = false686-687- expected = strings.Join([]string{688- "--array",689- "--bslice",690- "--slice",691- ":4",692- "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")693-694- if output != expected {695- t.Errorf("expected: %q, got: %q", expected, output)696- }697-698- // Test that flag names are not repeated unless they are an array or slice699- output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "--slice", "1", "--slice=2", "--array", "val", "--bslice", "true", "--")700- if err != nil {701- t.Errorf("Unexpected error: %v", err)702- }703- // Reset the flag for the next command704- sliceFlag.Changed = false705- arrayFlag.Changed = false706- bsliceFlag.Changed = false707-708- expected = strings.Join([]string{709- "--array",710- "--bslice",711- "--first",712- "--second",713- "--slice",714- ":4",715- "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")716-717- if output != expected {718- t.Errorf("expected: %q, got: %q", expected, output)719- }720-721- // Test that flag names are not repeated unless they are an array or slice, using shortname722- output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "-l", "1", "-l=2", "-a", "val", "-")723- if err != nil {724- t.Errorf("Unexpected error: %v", err)725- }726- // Reset the flag for the next command727- sliceFlag.Changed = false728- arrayFlag.Changed = false729-730- expected = strings.Join([]string{731- "--array",732- "-a",733- "--bslice",734- "-b",735- "--first",736- "-f",737- "--second",738- "-s",739- "--slice",740- "-l",741- ":4",742- "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")743-744- if output != expected {745- t.Errorf("expected: %q, got: %q", expected, output)746- }747-748- // Test that flag names are not repeated unless they are an array or slice, using shortname with prefix749- output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "-l", "1", "-l=2", "-a", "val", "-a")750- if err != nil {751- t.Errorf("Unexpected error: %v", err)752- }753- // Reset the flag for the next command754- sliceFlag.Changed = false755- arrayFlag.Changed = false756-757- expected = strings.Join([]string{758- "-a",759- ":4",760- "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")761-762- if output != expected {763- t.Errorf("expected: %q, got: %q", expected, output)764- }765-}766-767-func TestRequiredFlagNameCompletionInGo(t *testing.T) {768- rootCmd := &Command{769- Use: "root",770- ValidArgs: []string{"realArg"},771- Run: emptyRun,772- }773- childCmd := &Command{774- Use: "childCmd",775- ValidArgsFunction: func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective) {776- return []string{"subArg"}, ShellCompDirectiveNoFileComp777- },778- Run: emptyRun,779- }780- rootCmd.AddCommand(childCmd)781-782- rootCmd.Flags().IntP("requiredFlag", "r", -1, "required flag")783- assertNoErr(t, rootCmd.MarkFlagRequired("requiredFlag"))784- requiredFlag := rootCmd.Flags().Lookup("requiredFlag")785-786- rootCmd.PersistentFlags().IntP("requiredPersistent", "p", -1, "required persistent")787- assertNoErr(t, rootCmd.MarkPersistentFlagRequired("requiredPersistent"))788- requiredPersistent := rootCmd.PersistentFlags().Lookup("requiredPersistent")789-790- rootCmd.Flags().StringP("release", "R", "", "Release name")791-792- childCmd.Flags().BoolP("subRequired", "s", false, "sub required flag")793- assertNoErr(t, childCmd.MarkFlagRequired("subRequired"))794- childCmd.Flags().BoolP("subNotRequired", "n", false, "sub not required flag")795-796- // Test that a required flag is suggested even without the - prefix797- output, err := executeCommand(rootCmd, ShellCompNoDescRequestCmd, "")798- if err != nil {799- t.Errorf("Unexpected error: %v", err)800- }801-802- expected := strings.Join([]string{803- "childCmd",804- "help",805- "--requiredFlag",806- "-r",807- "--requiredPersistent",808- "-p",809- "realArg",810- ":4",811- "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")812-813- if output != expected {814- t.Errorf("expected: %q, got: %q", expected, output)815- }816-817- // Test that a required flag is suggested without other flags when using the '-' prefix818- output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "-")819- if err != nil {820- t.Errorf("Unexpected error: %v", err)821- }822-823- expected = strings.Join([]string{824- "--requiredFlag",825- "-r",826- "--requiredPersistent",827- "-p",828- ":4",829- "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")830-831- if output != expected {832- t.Errorf("expected: %q, got: %q", expected, output)833- }834-835- // Test that if no required flag matches, the normal flags are suggested836- output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "--relea")837- if err != nil {838- t.Errorf("Unexpected error: %v", err)839- }840-841- expected = strings.Join([]string{842- "--release",843- ":4",844- "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")845-846- if output != expected {847- t.Errorf("expected: %q, got: %q", expected, output)848- }849-850- // Test required flags for sub-commands851- output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "childCmd", "")852- if err != nil {853- t.Errorf("Unexpected error: %v", err)854- }855-856- expected = strings.Join([]string{857- "--requiredPersistent",858- "-p",859- "--subRequired",860- "-s",861- "subArg",862- ":4",863- "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")864-865- if output != expected {866- t.Errorf("expected: %q, got: %q", expected, output)867- }868-869- output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "childCmd", "-")870- if err != nil {871- t.Errorf("Unexpected error: %v", err)872- }873-874- expected = strings.Join([]string{875- "--requiredPersistent",876- "-p",877- "--subRequired",878- "-s",879- ":4",880- "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")881-882- if output != expected {883- t.Errorf("expected: %q, got: %q", expected, output)884- }885-886- output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "childCmd", "--subNot")887- if err != nil {888- t.Errorf("Unexpected error: %v", err)889- }890-891- expected = strings.Join([]string{892- "--subNotRequired",893- ":4",894- "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")895-896- if output != expected {897- t.Errorf("expected: %q, got: %q", expected, output)898- }899-900- // Test that when a required flag is present, it is not suggested anymore901- output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "--requiredFlag", "1", "")902- if err != nil {903- t.Errorf("Unexpected error: %v", err)904- }905- // Reset the flag for the next command906- requiredFlag.Changed = false907-908- expected = strings.Join([]string{909- "--requiredPersistent",910- "-p",911- "realArg",912- ":4",913- "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")914-915- if output != expected {916- t.Errorf("expected: %q, got: %q", expected, output)917- }918-919- // Test that when a persistent required flag is present, it is not suggested anymore920- output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "--requiredPersistent", "1", "")921- if err != nil {922- t.Errorf("Unexpected error: %v", err)923- }924- // Reset the flag for the next command925- requiredPersistent.Changed = false926-927- expected = strings.Join([]string{928- "childCmd",929- "help",930- "--requiredFlag",931- "-r",932- "realArg",933- ":4",934- "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")935-936- if output != expected {937- t.Errorf("expected: %q, got: %q", expected, output)938- }939-940- // Test that when all required flags are present, normal completion is done941- output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "--requiredFlag", "1", "--requiredPersistent", "1", "")942- if err != nil {943- t.Errorf("Unexpected error: %v", err)944- }945- // Reset the flags for the next command946- requiredFlag.Changed = false947- requiredPersistent.Changed = false948-949- expected = strings.Join([]string{950- "realArg",951- ":4",952- "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")953-954- if output != expected {955- t.Errorf("expected: %q, got: %q", expected, output)956- }957-}958-959-func TestFlagFileExtFilterCompletionInGo(t *testing.T) {960- rootCmd := &Command{961- Use: "root",962- Run: emptyRun,963- }964-965- // No extensions. Should be ignored.966- rootCmd.Flags().StringP("file", "f", "", "file flag")967- assertNoErr(t, rootCmd.MarkFlagFilename("file"))968-969- // Single extension970- rootCmd.Flags().StringP("log", "l", "", "log flag")971- assertNoErr(t, rootCmd.MarkFlagFilename("log", "log"))972-973- // Multiple extensions974- rootCmd.Flags().StringP("yaml", "y", "", "yaml flag")975- assertNoErr(t, rootCmd.MarkFlagFilename("yaml", "yaml", "yml"))976-977- // Directly using annotation978- rootCmd.Flags().StringP("text", "t", "", "text flag")979- assertNoErr(t, rootCmd.Flags().SetAnnotation("text", BashCompFilenameExt, []string{"txt"}))980-981- // Test that the completion logic returns the proper info for the completion982- // script to handle the file filtering983- output, err := executeCommand(rootCmd, ShellCompNoDescRequestCmd, "--file", "")984- if err != nil {985- t.Errorf("Unexpected error: %v", err)986- }987-988- expected := strings.Join([]string{989- ":0",990- "Completion ended with directive: ShellCompDirectiveDefault", ""}, "\n")991-992- if output != expected {993- t.Errorf("expected: %q, got: %q", expected, output)994- }995-996- output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "--log", "")997- if err != nil {998- t.Errorf("Unexpected error: %v", err)999- }1000-1001- expected = strings.Join([]string{1002- "log",1003- ":8",1004- "Completion ended with directive: ShellCompDirectiveFilterFileExt", ""}, "\n")1005-1006- if output != expected {1007- t.Errorf("expected: %q, got: %q", expected, output)1008- }1009-1010- output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "--yaml", "")1011- if err != nil {1012- t.Errorf("Unexpected error: %v", err)1013- }1014-1015- expected = strings.Join([]string{1016- "yaml", "yml",1017- ":8",1018- "Completion ended with directive: ShellCompDirectiveFilterFileExt", ""}, "\n")1019-1020- if output != expected {1021- t.Errorf("expected: %q, got: %q", expected, output)1022- }1023-1024- output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "--yaml=")1025- if err != nil {1026- t.Errorf("Unexpected error: %v", err)1027- }1028-1029- expected = strings.Join([]string{1030- "yaml", "yml",1031- ":8",1032- "Completion ended with directive: ShellCompDirectiveFilterFileExt", ""}, "\n")1033-1034- if output != expected {1035- t.Errorf("expected: %q, got: %q", expected, output)1036- }1037-1038- output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "-y", "")1039- if err != nil {1040- t.Errorf("Unexpected error: %v", err)1041- }1042-1043- expected = strings.Join([]string{1044- "yaml", "yml",1045- ":8",1046- "Completion ended with directive: ShellCompDirectiveFilterFileExt", ""}, "\n")1047-1048- if output != expected {1049- t.Errorf("expected: %q, got: %q", expected, output)1050- }1051-1052- output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "-y=")1053- if err != nil {1054- t.Errorf("Unexpected error: %v", err)1055- }1056-1057- expected = strings.Join([]string{1058- "yaml", "yml",1059- ":8",1060- "Completion ended with directive: ShellCompDirectiveFilterFileExt", ""}, "\n")1061-1062- if output != expected {1063- t.Errorf("expected: %q, got: %q", expected, output)1064- }1065-1066- output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "--text", "")1067- if err != nil {1068- t.Errorf("Unexpected error: %v", err)1069- }1070-1071- expected = strings.Join([]string{1072- "txt",1073- ":8",1074- "Completion ended with directive: ShellCompDirectiveFilterFileExt", ""}, "\n")1075-1076- if output != expected {1077- t.Errorf("expected: %q, got: %q", expected, output)1078- }1079-}1080-1081-func TestFlagDirFilterCompletionInGo(t *testing.T) {1082- rootCmd := &Command{1083- Use: "root",1084- Run: emptyRun,1085- }1086-1087- // Filter directories1088- rootCmd.Flags().StringP("dir", "d", "", "dir flag")1089- assertNoErr(t, rootCmd.MarkFlagDirname("dir"))1090-1091- // Filter directories within a directory1092- rootCmd.Flags().StringP("subdir", "s", "", "subdir")1093- assertNoErr(t, rootCmd.Flags().SetAnnotation("subdir", BashCompSubdirsInDir, []string{"themes"}))1094-1095- // Multiple directory specification get ignored1096- rootCmd.Flags().StringP("manydir", "m", "", "manydir")1097- assertNoErr(t, rootCmd.Flags().SetAnnotation("manydir", BashCompSubdirsInDir, []string{"themes", "colors"}))1098-1099- // Test that the completion logic returns the proper info for the completion1100- // script to handle the directory filtering1101- output, err := executeCommand(rootCmd, ShellCompNoDescRequestCmd, "--dir", "")1102- if err != nil {1103- t.Errorf("Unexpected error: %v", err)1104- }1105-1106- expected := strings.Join([]string{1107- ":16",1108- "Completion ended with directive: ShellCompDirectiveFilterDirs", ""}, "\n")1109-1110- if output != expected {1111- t.Errorf("expected: %q, got: %q", expected, output)1112- }1113-1114- output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "-d", "")1115- if err != nil {1116- t.Errorf("Unexpected error: %v", err)1117- }1118-1119- expected = strings.Join([]string{1120- ":16",1121- "Completion ended with directive: ShellCompDirectiveFilterDirs", ""}, "\n")1122-1123- if output != expected {1124- t.Errorf("expected: %q, got: %q", expected, output)1125- }1126-1127- output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "--subdir", "")1128- if err != nil {1129- t.Errorf("Unexpected error: %v", err)1130- }1131-1132- expected = strings.Join([]string{1133- "themes",1134- ":16",1135- "Completion ended with directive: ShellCompDirectiveFilterDirs", ""}, "\n")1136-1137- if output != expected {1138- t.Errorf("expected: %q, got: %q", expected, output)1139- }1140-1141- output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "--subdir=")1142- if err != nil {1143- t.Errorf("Unexpected error: %v", err)1144- }1145-1146- expected = strings.Join([]string{1147- "themes",1148- ":16",1149- "Completion ended with directive: ShellCompDirectiveFilterDirs", ""}, "\n")1150-1151- if output != expected {1152- t.Errorf("expected: %q, got: %q", expected, output)1153- }1154-1155- output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "-s", "")1156- if err != nil {1157- t.Errorf("Unexpected error: %v", err)1158- }1159-1160- expected = strings.Join([]string{1161- "themes",1162- ":16",1163- "Completion ended with directive: ShellCompDirectiveFilterDirs", ""}, "\n")1164-1165- if output != expected {1166- t.Errorf("expected: %q, got: %q", expected, output)1167- }1168-1169- output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "-s=")1170- if err != nil {1171- t.Errorf("Unexpected error: %v", err)1172- }1173-1174- expected = strings.Join([]string{1175- "themes",1176- ":16",1177- "Completion ended with directive: ShellCompDirectiveFilterDirs", ""}, "\n")1178-1179- if output != expected {1180- t.Errorf("expected: %q, got: %q", expected, output)1181- }1182-1183- output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "--manydir", "")1184- if err != nil {1185- t.Errorf("Unexpected error: %v", err)1186- }1187-1188- expected = strings.Join([]string{1189- ":16",1190- "Completion ended with directive: ShellCompDirectiveFilterDirs", ""}, "\n")1191-1192- if output != expected {1193- t.Errorf("expected: %q, got: %q", expected, output)1194- }1195-}1196-1197-func TestValidArgsFuncSingleCmd(t *testing.T) {1198- rootCmd := &Command{1199- Use: "root",1200- ValidArgsFunction: validArgsFunc,1201- Run: emptyRun,1202- }1203-1204- // Test completing an empty string1205- output, err := executeCommand(rootCmd, ShellCompNoDescRequestCmd, "")1206- if err != nil {1207- t.Errorf("Unexpected error: %v", err)1208- }1209-1210- expected := strings.Join([]string{1211- "one",1212- "two",1213- ":0",1214- "Completion ended with directive: ShellCompDirectiveDefault", ""}, "\n")1215-1216- if output != expected {1217- t.Errorf("expected: %q, got: %q", expected, output)1218- }1219-1220- // Check completing with a prefix1221- output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "t")1222- if err != nil {1223- t.Errorf("Unexpected error: %v", err)1224- }1225-1226- expected = strings.Join([]string{1227- "two",1228- ":0",1229- "Completion ended with directive: ShellCompDirectiveDefault", ""}, "\n")1230-1231- if output != expected {1232- t.Errorf("expected: %q, got: %q", expected, output)1233- }1234-}1235-1236-func TestValidArgsFuncSingleCmdInvalidArg(t *testing.T) {1237- rootCmd := &Command{1238- Use: "root",1239- // If we don't specify a value for Args, this test fails.1240- // This is only true for a root command without any subcommands, and is caused1241- // by the fact that the __complete command becomes a subcommand when there should not be one.1242- // The problem is in the implementation of legacyArgs().1243- Args: MinimumNArgs(1),1244- ValidArgsFunction: validArgsFunc,1245- Run: emptyRun,1246- }1247-1248- // Check completing with wrong number of args1249- output, err := executeCommand(rootCmd, ShellCompNoDescRequestCmd, "unexpectedArg", "t")1250- if err != nil {1251- t.Errorf("Unexpected error: %v", err)1252- }1253-1254- expected := strings.Join([]string{1255- ":4",1256- "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")1257-1258- if output != expected {1259- t.Errorf("expected: %q, got: %q", expected, output)1260- }1261-}1262-1263-func TestValidArgsFuncChildCmds(t *testing.T) {1264- rootCmd := &Command{Use: "root", Args: NoArgs, Run: emptyRun}1265- child1Cmd := &Command{1266- Use: "child1",1267- ValidArgsFunction: validArgsFunc,1268- Run: emptyRun,1269- }1270- child2Cmd := &Command{1271- Use: "child2",1272- ValidArgsFunction: validArgsFunc2,1273- Run: emptyRun,1274- }1275- rootCmd.AddCommand(child1Cmd, child2Cmd)1276-1277- // Test completion of first sub-command with empty argument1278- output, err := executeCommand(rootCmd, ShellCompNoDescRequestCmd, "child1", "")1279- if err != nil {1280- t.Errorf("Unexpected error: %v", err)1281- }1282-1283- expected := strings.Join([]string{1284- "one",1285- "two",1286- ":0",1287- "Completion ended with directive: ShellCompDirectiveDefault", ""}, "\n")1288-1289- if output != expected {1290- t.Errorf("expected: %q, got: %q", expected, output)1291- }1292-1293- // Test completion of first sub-command with a prefix to complete1294- output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "child1", "t")1295- if err != nil {1296- t.Errorf("Unexpected error: %v", err)1297- }1298-1299- expected = strings.Join([]string{1300- "two",1301- ":0",1302- "Completion ended with directive: ShellCompDirectiveDefault", ""}, "\n")1303-1304- if output != expected {1305- t.Errorf("expected: %q, got: %q", expected, output)1306- }1307-1308- // Check completing with wrong number of args1309- output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "child1", "unexpectedArg", "t")1310- if err != nil {1311- t.Errorf("Unexpected error: %v", err)1312- }1313-1314- expected = strings.Join([]string{1315- ":4",1316- "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")1317-1318- if output != expected {1319- t.Errorf("expected: %q, got: %q", expected, output)1320- }1321-1322- // Test completion of second sub-command with empty argument1323- output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "child2", "")1324- if err != nil {1325- t.Errorf("Unexpected error: %v", err)1326- }1327-1328- expected = strings.Join([]string{1329- "three",1330- "four",1331- ":0",1332- "Completion ended with directive: ShellCompDirectiveDefault", ""}, "\n")1333-1334- if output != expected {1335- t.Errorf("expected: %q, got: %q", expected, output)1336- }1337-1338- output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "child2", "t")1339- if err != nil {1340- t.Errorf("Unexpected error: %v", err)1341- }1342-1343- expected = strings.Join([]string{1344- "three",1345- ":0",1346- "Completion ended with directive: ShellCompDirectiveDefault", ""}, "\n")1347-1348- if output != expected {1349- t.Errorf("expected: %q, got: %q", expected, output)1350- }1351-1352- // Check completing with wrong number of args1353- output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "child2", "unexpectedArg", "t")1354- if err != nil {1355- t.Errorf("Unexpected error: %v", err)1356- }1357-1358- expected = strings.Join([]string{1359- ":4",1360- "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")1361-1362- if output != expected {1363- t.Errorf("expected: %q, got: %q", expected, output)1364- }1365-}1366-1367-func TestValidArgsFuncAliases(t *testing.T) {1368- rootCmd := &Command{Use: "root", Args: NoArgs, Run: emptyRun}1369- child := &Command{1370- Use: "child",1371- Aliases: []string{"son", "daughter"},1372- ValidArgsFunction: validArgsFunc,1373- Run: emptyRun,1374- }1375- rootCmd.AddCommand(child)1376-1377- // Test completion of first sub-command with empty argument1378- output, err := executeCommand(rootCmd, ShellCompNoDescRequestCmd, "son", "")1379- if err != nil {1380- t.Errorf("Unexpected error: %v", err)1381- }1382-1383- expected := strings.Join([]string{1384- "one",1385- "two",1386- ":0",1387- "Completion ended with directive: ShellCompDirectiveDefault", ""}, "\n")1388-1389- if output != expected {1390- t.Errorf("expected: %q, got: %q", expected, output)1391- }1392-1393- // Test completion of first sub-command with a prefix to complete1394- output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "daughter", "t")1395- if err != nil {1396- t.Errorf("Unexpected error: %v", err)1397- }1398-1399- expected = strings.Join([]string{1400- "two",1401- ":0",1402- "Completion ended with directive: ShellCompDirectiveDefault", ""}, "\n")1403-1404- if output != expected {1405- t.Errorf("expected: %q, got: %q", expected, output)1406- }1407-1408- // Check completing with wrong number of args1409- output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "son", "unexpectedArg", "t")1410- if err != nil {1411- t.Errorf("Unexpected error: %v", err)1412- }1413-1414- expected = strings.Join([]string{1415- ":4",1416- "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")1417-1418- if output != expected {1419- t.Errorf("expected: %q, got: %q", expected, output)1420- }1421-}1422-1423-func TestValidArgsFuncInBashScript(t *testing.T) {1424- rootCmd := &Command{Use: "root", Args: NoArgs, Run: emptyRun}1425- child := &Command{1426- Use: "child",1427- ValidArgsFunction: validArgsFunc,1428- Run: emptyRun,1429- }1430- rootCmd.AddCommand(child)1431-1432- buf := new(bytes.Buffer)1433- assertNoErr(t, rootCmd.GenBashCompletion(buf))1434- output := buf.String()1435-1436- check(t, output, "has_completion_function=1")1437-}1438-1439-func TestNoValidArgsFuncInBashScript(t *testing.T) {1440- rootCmd := &Command{Use: "root", Args: NoArgs, Run: emptyRun}1441- child := &Command{1442- Use: "child",1443- Run: emptyRun,1444- }1445- rootCmd.AddCommand(child)1446-1447- buf := new(bytes.Buffer)1448- assertNoErr(t, rootCmd.GenBashCompletion(buf))1449- output := buf.String()1450-1451- checkOmit(t, output, "has_completion_function=1")1452-}1453-1454-func TestCompleteCmdInBashScript(t *testing.T) {1455- rootCmd := &Command{Use: "root", Args: NoArgs, Run: emptyRun}1456- child := &Command{1457- Use: "child",1458- ValidArgsFunction: validArgsFunc,1459- Run: emptyRun,1460- }1461- rootCmd.AddCommand(child)1462-1463- buf := new(bytes.Buffer)1464- assertNoErr(t, rootCmd.GenBashCompletion(buf))1465- output := buf.String()1466-1467- check(t, output, ShellCompNoDescRequestCmd)1468-}1469-1470-func TestCompleteNoDesCmdInZshScript(t *testing.T) {1471- rootCmd := &Command{Use: "root", Args: NoArgs, Run: emptyRun}1472- child := &Command{1473- Use: "child",1474- ValidArgsFunction: validArgsFunc,1475- Run: emptyRun,1476- }1477- rootCmd.AddCommand(child)1478-1479- buf := new(bytes.Buffer)1480- assertNoErr(t, rootCmd.GenZshCompletionNoDesc(buf))1481- output := buf.String()1482-1483- check(t, output, ShellCompNoDescRequestCmd)1484-}1485-1486-func TestCompleteCmdInZshScript(t *testing.T) {1487- rootCmd := &Command{Use: "root", Args: NoArgs, Run: emptyRun}1488- child := &Command{1489- Use: "child",1490- ValidArgsFunction: validArgsFunc,1491- Run: emptyRun,1492- }1493- rootCmd.AddCommand(child)1494-1495- buf := new(bytes.Buffer)1496- assertNoErr(t, rootCmd.GenZshCompletion(buf))1497- output := buf.String()1498-1499- check(t, output, ShellCompRequestCmd)1500- checkOmit(t, output, ShellCompNoDescRequestCmd)1501-}1502-1503-func TestFlagCompletionInGo(t *testing.T) {1504- rootCmd := &Command{1505- Use: "root",1506- Run: emptyRun,1507- }1508- rootCmd.Flags().IntP("introot", "i", -1, "help message for flag introot")1509- assertNoErr(t, rootCmd.RegisterFlagCompletionFunc("introot", func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective) {1510- completions := []string{}1511- for _, comp := range []string{"1\tThe first", "2\tThe second", "10\tThe tenth"} {1512- if strings.HasPrefix(comp, toComplete) {1513- completions = append(completions, comp)1514- }1515- }1516- return completions, ShellCompDirectiveDefault1517- }))1518- rootCmd.Flags().String("filename", "", "Enter a filename")1519- assertNoErr(t, rootCmd.RegisterFlagCompletionFunc("filename", func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective) {1520- completions := []string{}1521- for _, comp := range []string{"file.yaml\tYAML format", "myfile.json\tJSON format", "file.xml\tXML format"} {1522- if strings.HasPrefix(comp, toComplete) {1523- completions = append(completions, comp)1524- }1525- }1526- return completions, ShellCompDirectiveNoSpace | ShellCompDirectiveNoFileComp1527- }))1528-1529- // Test completing an empty string1530- output, err := executeCommand(rootCmd, ShellCompNoDescRequestCmd, "--introot", "")1531- if err != nil {1532- t.Errorf("Unexpected error: %v", err)1533- }1534-1535- expected := strings.Join([]string{1536- "1",1537- "2",1538- "10",1539- ":0",1540- "Completion ended with directive: ShellCompDirectiveDefault", ""}, "\n")1541-1542- if output != expected {1543- t.Errorf("expected: %q, got: %q", expected, output)1544- }1545-1546- // Check completing with a prefix1547- output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "--introot", "1")1548- if err != nil {1549- t.Errorf("Unexpected error: %v", err)1550- }1551-1552- expected = strings.Join([]string{1553- "1",1554- "10",1555- ":0",1556- "Completion ended with directive: ShellCompDirectiveDefault", ""}, "\n")1557-1558- if output != expected {1559- t.Errorf("expected: %q, got: %q", expected, output)1560- }1561-1562- // Test completing an empty string1563- output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "--filename", "")1564- if err != nil {1565- t.Errorf("Unexpected error: %v", err)1566- }1567-1568- expected = strings.Join([]string{1569- "file.yaml",1570- "myfile.json",1571- "file.xml",1572- ":6",1573- "Completion ended with directive: ShellCompDirectiveNoSpace, ShellCompDirectiveNoFileComp", ""}, "\n")1574-1575- if output != expected {1576- t.Errorf("expected: %q, got: %q", expected, output)1577- }1578-1579- // Check completing with a prefix1580- output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "--filename", "f")1581- if err != nil {1582- t.Errorf("Unexpected error: %v", err)1583- }1584-1585- expected = strings.Join([]string{1586- "file.yaml",1587- "file.xml",1588- ":6",1589- "Completion ended with directive: ShellCompDirectiveNoSpace, ShellCompDirectiveNoFileComp", ""}, "\n")1590-1591- if output != expected {1592- t.Errorf("expected: %q, got: %q", expected, output)1593- }1594-}1595-1596-func TestValidArgsFuncChildCmdsWithDesc(t *testing.T) {1597- rootCmd := &Command{Use: "root", Args: NoArgs, Run: emptyRun}1598- child1Cmd := &Command{1599- Use: "child1",1600- ValidArgsFunction: validArgsFunc,1601- Run: emptyRun,1602- }1603- child2Cmd := &Command{1604- Use: "child2",1605- ValidArgsFunction: validArgsFunc2,1606- Run: emptyRun,1607- }1608- rootCmd.AddCommand(child1Cmd, child2Cmd)1609-1610- // Test completion of first sub-command with empty argument1611- output, err := executeCommand(rootCmd, ShellCompRequestCmd, "child1", "")1612- if err != nil {1613- t.Errorf("Unexpected error: %v", err)1614- }1615-1616- expected := strings.Join([]string{1617- "one\tThe first",1618- "two\tThe second",1619- ":0",1620- "Completion ended with directive: ShellCompDirectiveDefault", ""}, "\n")1621-1622- if output != expected {1623- t.Errorf("expected: %q, got: %q", expected, output)1624- }1625-1626- // Test completion of first sub-command with a prefix to complete1627- output, err = executeCommand(rootCmd, ShellCompRequestCmd, "child1", "t")1628- if err != nil {1629- t.Errorf("Unexpected error: %v", err)1630- }1631-1632- expected = strings.Join([]string{1633- "two\tThe second",1634- ":0",1635- "Completion ended with directive: ShellCompDirectiveDefault", ""}, "\n")1636-1637- if output != expected {1638- t.Errorf("expected: %q, got: %q", expected, output)1639- }1640-1641- // Check completing with wrong number of args1642- output, err = executeCommand(rootCmd, ShellCompRequestCmd, "child1", "unexpectedArg", "t")1643- if err != nil {1644- t.Errorf("Unexpected error: %v", err)1645- }1646-1647- expected = strings.Join([]string{1648- ":4",1649- "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")1650-1651- if output != expected {1652- t.Errorf("expected: %q, got: %q", expected, output)1653- }1654-1655- // Test completion of second sub-command with empty argument1656- output, err = executeCommand(rootCmd, ShellCompRequestCmd, "child2", "")1657- if err != nil {1658- t.Errorf("Unexpected error: %v", err)1659- }1660-1661- expected = strings.Join([]string{1662- "three\tThe third",1663- "four\tThe fourth",1664- ":0",1665- "Completion ended with directive: ShellCompDirectiveDefault", ""}, "\n")1666-1667- if output != expected {1668- t.Errorf("expected: %q, got: %q", expected, output)1669- }1670-1671- output, err = executeCommand(rootCmd, ShellCompRequestCmd, "child2", "t")1672- if err != nil {1673- t.Errorf("Unexpected error: %v", err)1674- }1675-1676- expected = strings.Join([]string{1677- "three\tThe third",1678- ":0",1679- "Completion ended with directive: ShellCompDirectiveDefault", ""}, "\n")1680-1681- if output != expected {1682- t.Errorf("expected: %q, got: %q", expected, output)1683- }1684-1685- // Check completing with wrong number of args1686- output, err = executeCommand(rootCmd, ShellCompRequestCmd, "child2", "unexpectedArg", "t")1687- if err != nil {1688- t.Errorf("Unexpected error: %v", err)1689- }1690-1691- expected = strings.Join([]string{1692- ":4",1693- "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")1694-1695- if output != expected {1696- t.Errorf("expected: %q, got: %q", expected, output)1697- }1698-}1699-1700-func TestFlagCompletionInGoWithDesc(t *testing.T) {1701- rootCmd := &Command{1702- Use: "root",1703- Run: emptyRun,1704- }1705- rootCmd.Flags().IntP("introot", "i", -1, "help message for flag introot")1706- assertNoErr(t, rootCmd.RegisterFlagCompletionFunc("introot", func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective) {1707- completions := []string{}1708- for _, comp := range []string{"1\tThe first", "2\tThe second", "10\tThe tenth"} {1709- if strings.HasPrefix(comp, toComplete) {1710- completions = append(completions, comp)1711- }1712- }1713- return completions, ShellCompDirectiveDefault1714- }))1715- rootCmd.Flags().String("filename", "", "Enter a filename")1716- assertNoErr(t, rootCmd.RegisterFlagCompletionFunc("filename", func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective) {1717- completions := []string{}1718- for _, comp := range []string{"file.yaml\tYAML format", "myfile.json\tJSON format", "file.xml\tXML format"} {1719- if strings.HasPrefix(comp, toComplete) {1720- completions = append(completions, comp)1721- }1722- }1723- return completions, ShellCompDirectiveNoSpace | ShellCompDirectiveNoFileComp1724- }))1725-1726- // Test completing an empty string1727- output, err := executeCommand(rootCmd, ShellCompRequestCmd, "--introot", "")1728- if err != nil {1729- t.Errorf("Unexpected error: %v", err)1730- }1731-1732- expected := strings.Join([]string{1733- "1\tThe first",1734- "2\tThe second",1735- "10\tThe tenth",1736- ":0",1737- "Completion ended with directive: ShellCompDirectiveDefault", ""}, "\n")1738-1739- if output != expected {1740- t.Errorf("expected: %q, got: %q", expected, output)1741- }1742-1743- // Check completing with a prefix1744- output, err = executeCommand(rootCmd, ShellCompRequestCmd, "--introot", "1")1745- if err != nil {1746- t.Errorf("Unexpected error: %v", err)1747- }1748-1749- expected = strings.Join([]string{1750- "1\tThe first",1751- "10\tThe tenth",1752- ":0",1753- "Completion ended with directive: ShellCompDirectiveDefault", ""}, "\n")1754-1755- if output != expected {1756- t.Errorf("expected: %q, got: %q", expected, output)1757- }1758-1759- // Test completing an empty string1760- output, err = executeCommand(rootCmd, ShellCompRequestCmd, "--filename", "")1761- if err != nil {1762- t.Errorf("Unexpected error: %v", err)1763- }1764-1765- expected = strings.Join([]string{1766- "file.yaml\tYAML format",1767- "myfile.json\tJSON format",1768- "file.xml\tXML format",1769- ":6",1770- "Completion ended with directive: ShellCompDirectiveNoSpace, ShellCompDirectiveNoFileComp", ""}, "\n")1771-1772- if output != expected {1773- t.Errorf("expected: %q, got: %q", expected, output)1774- }1775-1776- // Check completing with a prefix1777- output, err = executeCommand(rootCmd, ShellCompRequestCmd, "--filename", "f")1778- if err != nil {1779- t.Errorf("Unexpected error: %v", err)1780- }1781-1782- expected = strings.Join([]string{1783- "file.yaml\tYAML format",1784- "file.xml\tXML format",1785- ":6",1786- "Completion ended with directive: ShellCompDirectiveNoSpace, ShellCompDirectiveNoFileComp", ""}, "\n")1787-1788- if output != expected {1789- t.Errorf("expected: %q, got: %q", expected, output)1790- }1791-}1792-1793-func TestValidArgsNotValidArgsFunc(t *testing.T) {1794- rootCmd := &Command{1795- Use: "root",1796- ValidArgs: []string{"one", "two"},1797- ValidArgsFunction: func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective) {1798- return []string{"three", "four"}, ShellCompDirectiveNoFileComp1799- },1800- Run: emptyRun,1801- }1802-1803- // Test that if both ValidArgs and ValidArgsFunction are present1804- // only ValidArgs is considered1805- output, err := executeCommand(rootCmd, ShellCompNoDescRequestCmd, "")1806- if err != nil {1807- t.Errorf("Unexpected error: %v", err)1808- }1809-1810- expected := strings.Join([]string{1811- "one",1812- "two",1813- ":4",1814- "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")1815-1816- if output != expected {1817- t.Errorf("expected: %q, got: %q", expected, output)1818- }1819-1820- // Check completing with a prefix1821- output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "t")1822- if err != nil {1823- t.Errorf("Unexpected error: %v", err)1824- }1825-1826- expected = strings.Join([]string{1827- "two",1828- ":4",1829- "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")1830-1831- if output != expected {1832- t.Errorf("expected: %q, got: %q", expected, output)1833- }1834-}1835-1836-func TestArgAliasesCompletionInGo(t *testing.T) {1837- rootCmd := &Command{1838- Use: "root",1839- Args: OnlyValidArgs,1840- ValidArgs: []string{"one", "two", "three"},1841- ArgAliases: []string{"un", "deux", "trois"},1842- Run: emptyRun,1843- }1844-1845- // Test that argaliases are not completed when there are validargs that match1846- output, err := executeCommand(rootCmd, ShellCompNoDescRequestCmd, "")1847- if err != nil {1848- t.Errorf("Unexpected error: %v", err)1849- }1850-1851- expected := strings.Join([]string{1852- "one",1853- "two",1854- "three",1855- ":4",1856- "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")1857-1858- if output != expected {1859- t.Errorf("expected: %q, got: %q", expected, output)1860- }1861-1862- // Test that argaliases are not completed when there are validargs that match using a prefix1863- output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "t")1864- if err != nil {1865- t.Errorf("Unexpected error: %v", err)1866- }1867-1868- expected = strings.Join([]string{1869- "two",1870- "three",1871- ":4",1872- "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")1873-1874- if output != expected {1875- t.Errorf("expected: %q, got: %q", expected, output)1876- }1877-1878- // Test that argaliases are completed when there are no validargs that match1879- output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "tr")1880- if err != nil {1881- t.Errorf("Unexpected error: %v", err)1882- }1883-1884- expected = strings.Join([]string{1885- "trois",1886- ":4",1887- "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")1888-1889- if output != expected {1890- t.Errorf("expected: %q, got: %q", expected, output)1891- }1892-}1893-1894-func TestCompleteHelp(t *testing.T) {1895- rootCmd := &Command{Use: "root", Args: NoArgs, Run: emptyRun}1896- child1Cmd := &Command{1897- Use: "child1",1898- Run: emptyRun,1899- }1900- child2Cmd := &Command{1901- Use: "child2",1902- Run: emptyRun,1903- }1904- rootCmd.AddCommand(child1Cmd, child2Cmd)1905-1906- child3Cmd := &Command{1907- Use: "child3",1908- Run: emptyRun,1909- }1910- child1Cmd.AddCommand(child3Cmd)1911-1912- // Test that completion includes the help command1913- output, err := executeCommand(rootCmd, ShellCompNoDescRequestCmd, "")1914- if err != nil {1915- t.Errorf("Unexpected error: %v", err)1916- }1917-1918- expected := strings.Join([]string{1919- "child1",1920- "child2",1921- "help",1922- ":4",1923- "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")1924-1925- if output != expected {1926- t.Errorf("expected: %q, got: %q", expected, output)1927- }1928-1929- // Test sub-commands are completed on first level of help command1930- output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "help", "")1931- if err != nil {1932- t.Errorf("Unexpected error: %v", err)1933- }1934-1935- expected = strings.Join([]string{1936- "child1",1937- "child2",1938- "help", // "<program> help help" is a valid command, so should be completed1939- ":4",1940- "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")1941-1942- if output != expected {1943- t.Errorf("expected: %q, got: %q", expected, output)1944- }1945-1946- // Test sub-commands are completed on first level of help command1947- output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "help", "child1", "")1948- if err != nil {1949- t.Errorf("Unexpected error: %v", err)1950- }1951-1952- expected = strings.Join([]string{1953- "child3",1954- ":4",1955- "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")1956-1957- if output != expected {1958- t.Errorf("expected: %q, got: %q", expected, output)1959- }1960-}deleted:custom_completions.go-557 removed
1-package cobra2-3-import (4- "fmt"5- "os"6- "strings"7-8- "github.com/spf13/pflag"9-)10-11-const (12- // 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 scripts.14- ShellCompRequestCmd = "__complete"15- // ShellCompNoDescRequestCmd is the name of the hidden command that is used to request16- // completion results without their description. It is used by the shell completion scripts.17- ShellCompNoDescRequestCmd = "__completeNoDesc"18-)19-20-// Global map of flag completion functions.21-var flagCompletionFunctions = map[*pflag.Flag]func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective){}22-23-// ShellCompDirective is a bit map representing the different behaviors the shell24-// can be instructed to have once completions have been provided.25-type ShellCompDirective int26-27-const (28- // ShellCompDirectiveError indicates an error occurred and completions should be ignored.29- ShellCompDirectiveError ShellCompDirective = 1 << iota30-31- // ShellCompDirectiveNoSpace indicates that the shell should not add a space32- // after the completion even if there is a single completion provided.33- ShellCompDirectiveNoSpace34-35- // ShellCompDirectiveNoFileComp indicates that the shell should not provide36- // file completion even when no completion is provided.37- // This currently does not work for zsh or bash < 438- ShellCompDirectiveNoFileComp39-40- // ShellCompDirectiveFilterFileExt indicates that the provided completions41- // should be used as file extension filters.42- // For flags, using Command.MarkFlagFilename() and Command.MarkPersistentFlagFilename()43- // is a shortcut to using this directive explicitly. The BashCompFilenameExt44- // annotation can also be used to obtain the same behavior for flags.45- ShellCompDirectiveFilterFileExt46-47- // ShellCompDirectiveFilterDirs indicates that only directory names should48- // be provided in file completion. To request directory names within another49- // directory, the returned completions should specify the directory within50- // which to search. The BashCompSubdirsInDir annotation can be used to51- // obtain the same behavior but only for flags.52- ShellCompDirectiveFilterDirs53-54- // ===========================================================================55-56- // All directives using iota should be above this one.57- // For internal use.58- shellCompDirectiveMaxValue59-60- // ShellCompDirectiveDefault indicates to let the shell perform its default61- // behavior after completions have been provided.62- // This one must be last to avoid messing up the iota count.63- ShellCompDirectiveDefault ShellCompDirective = 064-)65-66-// RegisterFlagCompletionFunc should be called to register a function to provide completion for a flag.67-func (c *Command) RegisterFlagCompletionFunc(flagName string, f func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective)) error {68- flag := c.Flag(flagName)69- if flag == nil {70- return fmt.Errorf("RegisterFlagCompletionFunc: flag '%s' does not exist", flagName)71- }72- if _, exists := flagCompletionFunctions[flag]; exists {73- return fmt.Errorf("RegisterFlagCompletionFunc: flag '%s' already registered", flagName)74- }75- flagCompletionFunctions[flag] = f76- return nil77-}78-79-// Returns a string listing the different directive enabled in the specified parameter80-func (d ShellCompDirective) string() string {81- var directives []string82- if d&ShellCompDirectiveError != 0 {83- directives = append(directives, "ShellCompDirectiveError")84- }85- if d&ShellCompDirectiveNoSpace != 0 {86- directives = append(directives, "ShellCompDirectiveNoSpace")87- }88- if d&ShellCompDirectiveNoFileComp != 0 {89- directives = append(directives, "ShellCompDirectiveNoFileComp")90- }91- if d&ShellCompDirectiveFilterFileExt != 0 {92- directives = append(directives, "ShellCompDirectiveFilterFileExt")93- }94- if d&ShellCompDirectiveFilterDirs != 0 {95- directives = append(directives, "ShellCompDirectiveFilterDirs")96- }97- if len(directives) == 0 {98- directives = append(directives, "ShellCompDirectiveDefault")99- }100-101- if d >= shellCompDirectiveMaxValue {102- return fmt.Sprintf("ERROR: unexpected ShellCompDirective value: %d", d)103- }104- return strings.Join(directives, ", ")105-}106-107-// Adds a special hidden command that can be used to request custom completions.108-func (c *Command) initCompleteCmd(args []string) {109- completeCmd := &Command{110- Use: fmt.Sprintf("%s [command-line]", ShellCompRequestCmd),111- Aliases: []string{ShellCompNoDescRequestCmd},112- DisableFlagsInUseLine: true,113- Hidden: true,114- DisableFlagParsing: true,115- Args: MinimumNArgs(1),116- Short: "Request shell completion choices for the specified command-line",117- Long: fmt.Sprintf("%[2]s is a special command that is used by the shell completion logic\n%[1]s",118- "to request completion choices for the specified command-line.", ShellCompRequestCmd),119- Run: func(cmd *Command, args []string) {120- finalCmd, completions, directive, err := cmd.getCompletions(args)121- if err != nil {122- CompErrorln(err.Error())123- // Keep going for multiple reasons:124- // 1- There could be some valid completions even though there was an error125- // 2- Even without completions, we need to print the directive126- }127-128- noDescriptions := (cmd.CalledAs() == ShellCompNoDescRequestCmd)129- for _, comp := range completions {130- if noDescriptions {131- // Remove any description that may be included following a tab character.132- comp = strings.Split(comp, "\t")[0]133- }134-135- // Make sure we only write the first line to the output.136- // This is needed if a description contains a linebreak.137- // Otherwise the shell scripts will interpret the other lines as new flags138- // and could therefore provide a wrong completion.139- comp = strings.Split(comp, "\n")[0]140-141- // Finally trim the completion. This is especially important to get rid142- // of a trailing tab when there are no description following it.143- // For example, a sub-command without a description should not be completed144- // with a tab at the end (or else zsh will show a -- following it145- // although there is no description).146- comp = strings.TrimSpace(comp)147-148- // Print each possible completion to stdout for the completion script to consume.149- fmt.Fprintln(finalCmd.OutOrStdout(), comp)150- }151-152- if directive >= shellCompDirectiveMaxValue {153- directive = ShellCompDirectiveDefault154- }155-156- // As the last printout, print the completion directive for the completion script to parse.157- // The directive integer must be that last character following a single colon (:).158- // The completion script expects :<directive>159- fmt.Fprintf(finalCmd.OutOrStdout(), ":%d\n", directive)160-161- // Print some helpful info to stderr for the user to understand.162- // Output from stderr must be ignored by the completion script.163- fmt.Fprintf(finalCmd.ErrOrStderr(), "Completion ended with directive: %s\n", directive.string())164- },165- }166- c.AddCommand(completeCmd)167- subCmd, _, err := c.Find(args)168- if err != nil || subCmd.Name() != ShellCompRequestCmd {169- // Only create this special command if it is actually being called.170- // This reduces possible side-effects of creating such a command;171- // for example, having this command would cause problems to a172- // cobra program that only consists of the root command, since this173- // command would cause the root command to suddenly have a subcommand.174- c.RemoveCommand(completeCmd)175- }176-}177-178-func (c *Command) getCompletions(args []string) (*Command, []string, ShellCompDirective, error) {179- // The last argument, which is not completely typed by the user,180- // should not be part of the list of arguments181- toComplete := args[len(args)-1]182- trimmedArgs := args[:len(args)-1]183-184- var finalCmd *Command185- var finalArgs []string186- var err error187- // Find the real command for which completion must be performed188- // check if we need to traverse here to parse local flags on parent commands189- if c.Root().TraverseChildren {190- finalCmd, finalArgs, err = c.Root().Traverse(trimmedArgs)191- } else {192- finalCmd, finalArgs, err = c.Root().Find(trimmedArgs)193- }194- if err != nil {195- // Unable to find the real command. E.g., <program> someInvalidCmd <TAB>196- return c, []string{}, ShellCompDirectiveDefault, fmt.Errorf("Unable to find a command for arguments: %v", trimmedArgs)197- }198-199- // Check if we are doing flag value completion before parsing the flags.200- // This is important because if we are completing a flag value, we need to also201- // remove the flag name argument from the list of finalArgs or else the parsing202- // could fail due to an invalid value (incomplete) for the flag.203- flag, finalArgs, toComplete, err := checkIfFlagCompletion(finalCmd, finalArgs, toComplete)204- if err != nil {205- // Error while attempting to parse flags206- return finalCmd, []string{}, ShellCompDirectiveDefault, err207- }208-209- // Parse the flags early so we can check if required flags are set210- if err = finalCmd.ParseFlags(finalArgs); err != nil {211- return finalCmd, []string{}, ShellCompDirectiveDefault, fmt.Errorf("Error while parsing flags from args %v: %s", finalArgs, err.Error())212- }213-214- if flag != nil {215- // Check if we are completing a flag value subject to annotations216- if validExts, present := flag.Annotations[BashCompFilenameExt]; present {217- if len(validExts) != 0 {218- // File completion filtered by extensions219- return finalCmd, validExts, ShellCompDirectiveFilterFileExt, nil220- }221-222- // The annotation requests simple file completion. There is no reason to do223- // that since it is the default behavior anyway. Let's ignore this annotation224- // in case the program also registered a completion function for this flag.225- // Even though it is a mistake on the program's side, let's be nice when we can.226- }227-228- if subDir, present := flag.Annotations[BashCompSubdirsInDir]; present {229- if len(subDir) == 1 {230- // Directory completion from within a directory231- return finalCmd, subDir, ShellCompDirectiveFilterDirs, nil232- }233- // Directory completion234- return finalCmd, []string{}, ShellCompDirectiveFilterDirs, nil235- }236- }237-238- // When doing completion of a flag name, as soon as an argument starts with239- // a '-' we know it is a flag. We cannot use isFlagArg() here as it requires240- // the flag name to be complete241- if flag == nil && len(toComplete) > 0 && toComplete[0] == '-' && !strings.Contains(toComplete, "=") {242- var completions []string243-244- // First check for required flags245- completions = completeRequireFlags(finalCmd, toComplete)246-247- // If we have not found any required flags, only then can we show regular flags248- if len(completions) == 0 {249- doCompleteFlags := func(flag *pflag.Flag) {250- if !flag.Changed ||251- strings.Contains(flag.Value.Type(), "Slice") ||252- strings.Contains(flag.Value.Type(), "Array") {253- // If the flag is not already present, or if it can be specified multiple times (Array or Slice)254- // we suggest it as a completion255- completions = append(completions, getFlagNameCompletions(flag, toComplete)...)256- }257- }258-259- // We cannot use finalCmd.Flags() because we may not have called ParsedFlags() for commands260- // that have set DisableFlagParsing; it is ParseFlags() that merges the inherited and261- // non-inherited flags.262- finalCmd.InheritedFlags().VisitAll(func(flag *pflag.Flag) {263- doCompleteFlags(flag)264- })265- finalCmd.NonInheritedFlags().VisitAll(func(flag *pflag.Flag) {266- doCompleteFlags(flag)267- })268- }269-270- directive := ShellCompDirectiveNoFileComp271- if len(completions) == 1 && strings.HasSuffix(completions[0], "=") {272- // If there is a single completion, the shell usually adds a space273- // after the completion. We don't want that if the flag ends with an =274- directive = ShellCompDirectiveNoSpace275- }276- return finalCmd, completions, directive, nil277- }278-279- // We only remove the flags from the arguments if DisableFlagParsing is not set.280- // This is important for commands which have requested to do their own flag completion.281- if !finalCmd.DisableFlagParsing {282- finalArgs = finalCmd.Flags().Args()283- }284-285- var completions []string286- directive := ShellCompDirectiveDefault287- if flag == nil {288- foundLocalNonPersistentFlag := false289- // If TraverseChildren is true on the root command we don't check for290- // local flags because we can use a local flag on a parent command291- if !finalCmd.Root().TraverseChildren {292- // Check if there are any local, non-persistent flags on the command-line293- localNonPersistentFlags := finalCmd.LocalNonPersistentFlags()294- finalCmd.NonInheritedFlags().VisitAll(func(flag *pflag.Flag) {295- if localNonPersistentFlags.Lookup(flag.Name) != nil && flag.Changed {296- foundLocalNonPersistentFlag = true297- }298- })299- }300-301- // Complete subcommand names, including the help command302- if len(finalArgs) == 0 && !foundLocalNonPersistentFlag {303- // We only complete sub-commands if:304- // - there are no arguments on the command-line and305- // - there are no local, non-peristent flag on the command-line or TraverseChildren is true306- for _, subCmd := range finalCmd.Commands() {307- if subCmd.IsAvailableCommand() || subCmd == finalCmd.helpCommand {308- if strings.HasPrefix(subCmd.Name(), toComplete) {309- completions = append(completions, fmt.Sprintf("%s\t%s", subCmd.Name(), subCmd.Short))310- }311- directive = ShellCompDirectiveNoFileComp312- }313- }314- }315-316- // Complete required flags even without the '-' prefix317- completions = append(completions, completeRequireFlags(finalCmd, toComplete)...)318-319- // Always complete ValidArgs, even if we are completing a subcommand name.320- // This is for commands that have both subcommands and ValidArgs.321- if len(finalCmd.ValidArgs) > 0 {322- if len(finalArgs) == 0 {323- // ValidArgs are only for the first argument324- for _, validArg := range finalCmd.ValidArgs {325- if strings.HasPrefix(validArg, toComplete) {326- completions = append(completions, validArg)327- }328- }329- directive = ShellCompDirectiveNoFileComp330-331- // If no completions were found within commands or ValidArgs,332- // see if there are any ArgAliases that should be completed.333- if len(completions) == 0 {334- for _, argAlias := range finalCmd.ArgAliases {335- if strings.HasPrefix(argAlias, toComplete) {336- completions = append(completions, argAlias)337- }338- }339- }340- }341-342- // If there are ValidArgs specified (even if they don't match), we stop completion.343- // Only one of ValidArgs or ValidArgsFunction can be used for a single command.344- return finalCmd, completions, directive, nil345- }346-347- // Let the logic continue so as to add any ValidArgsFunction completions,348- // even if we already found sub-commands.349- // This is for commands that have subcommands but also specify a ValidArgsFunction.350- }351-352- // Find the completion function for the flag or command353- var completionFn func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective)354- if flag != nil {355- completionFn = flagCompletionFunctions[flag]356- } else {357- completionFn = finalCmd.ValidArgsFunction358- }359- if completionFn != nil {360- // Go custom completion defined for this flag or command.361- // Call the registered completion function to get the completions.362- var comps []string363- comps, directive = completionFn(finalCmd, finalArgs, toComplete)364- completions = append(completions, comps...)365- }366-367- return finalCmd, completions, directive, nil368-}369-370-func getFlagNameCompletions(flag *pflag.Flag, toComplete string) []string {371- if nonCompletableFlag(flag) {372- return []string{}373- }374-375- var completions []string376- flagName := "--" + flag.Name377- if strings.HasPrefix(flagName, toComplete) {378- // Flag without the =379- completions = append(completions, fmt.Sprintf("%s\t%s", flagName, flag.Usage))380-381- // Why suggest both long forms: --flag and --flag= ?382- // This forces the user to *always* have to type either an = or a space after the flag name.383- // Let's be nice and avoid making users have to do that.384- // Since boolean flags and shortname flags don't show the = form, let's go that route and never show it.385- // The = form will still work, we just won't suggest it.386- // This also makes the list of suggested flags shorter as we avoid all the = forms.387- //388- // if len(flag.NoOptDefVal) == 0 {389- // // Flag requires a value, so it can be suffixed with =390- // flagName += "="391- // completions = append(completions, fmt.Sprintf("%s\t%s", flagName, flag.Usage))392- // }393- }394-395- flagName = "-" + flag.Shorthand396- if len(flag.Shorthand) > 0 && strings.HasPrefix(flagName, toComplete) {397- completions = append(completions, fmt.Sprintf("%s\t%s", flagName, flag.Usage))398- }399-400- return completions401-}402-403-func completeRequireFlags(finalCmd *Command, toComplete string) []string {404- var completions []string405-406- doCompleteRequiredFlags := func(flag *pflag.Flag) {407- if _, present := flag.Annotations[BashCompOneRequiredFlag]; present {408- if !flag.Changed {409- // If the flag is not already present, we suggest it as a completion410- completions = append(completions, getFlagNameCompletions(flag, toComplete)...)411- }412- }413- }414-415- // We cannot use finalCmd.Flags() because we may not have called ParsedFlags() for commands416- // that have set DisableFlagParsing; it is ParseFlags() that merges the inherited and417- // non-inherited flags.418- finalCmd.InheritedFlags().VisitAll(func(flag *pflag.Flag) {419- doCompleteRequiredFlags(flag)420- })421- finalCmd.NonInheritedFlags().VisitAll(func(flag *pflag.Flag) {422- doCompleteRequiredFlags(flag)423- })424-425- return completions426-}427-428-func checkIfFlagCompletion(finalCmd *Command, args []string, lastArg string) (*pflag.Flag, []string, string, error) {429- if finalCmd.DisableFlagParsing {430- // We only do flag completion if we are allowed to parse flags431- // This is important for commands which have requested to do their own flag completion.432- return nil, args, lastArg, nil433- }434-435- var flagName string436- trimmedArgs := args437- flagWithEqual := false438-439- // When doing completion of a flag name, as soon as an argument starts with440- // a '-' we know it is a flag. We cannot use isFlagArg() here as that function441- // requires the flag name to be complete442- if len(lastArg) > 0 && lastArg[0] == '-' {443- if index := strings.Index(lastArg, "="); index >= 0 {444- // Flag with an =445- flagName = strings.TrimLeft(lastArg[:index], "-")446- lastArg = lastArg[index+1:]447- flagWithEqual = true448- } else {449- // Normal flag completion450- return nil, args, lastArg, nil451- }452- }453-454- if len(flagName) == 0 {455- if len(args) > 0 {456- prevArg := args[len(args)-1]457- if isFlagArg(prevArg) {458- // Only consider the case where the flag does not contain an =.459- // If the flag contains an = it means it has already been fully processed,460- // so we don't need to deal with it here.461- if index := strings.Index(prevArg, "="); index < 0 {462- flagName = strings.TrimLeft(prevArg, "-")463-464- // Remove the uncompleted flag or else there could be an error created465- // for an invalid value for that flag466- trimmedArgs = args[:len(args)-1]467- }468- }469- }470- }471-472- if len(flagName) == 0 {473- // Not doing flag completion474- return nil, trimmedArgs, lastArg, nil475- }476-477- flag := findFlag(finalCmd, flagName)478- if flag == nil {479- // Flag not supported by this command, nothing to complete480- err := fmt.Errorf("Subcommand '%s' does not support flag '%s'", finalCmd.Name(), flagName)481- return nil, nil, "", err482- }483-484- if !flagWithEqual {485- if len(flag.NoOptDefVal) != 0 {486- // We had assumed dealing with a two-word flag but the flag is a boolean flag.487- // In that case, there is no value following it, so we are not really doing flag completion.488- // Reset everything to do noun completion.489- trimmedArgs = args490- flag = nil491- }492- }493-494- return flag, trimmedArgs, lastArg, nil495-}496-497-func findFlag(cmd *Command, name string) *pflag.Flag {498- flagSet := cmd.Flags()499- if len(name) == 1 {500- // First convert the short flag into a long flag501- // as the cmd.Flag() search only accepts long flags502- if short := flagSet.ShorthandLookup(name); short != nil {503- name = short.Name504- } else {505- set := cmd.InheritedFlags()506- if short = set.ShorthandLookup(name); short != nil {507- name = short.Name508- } else {509- return nil510- }511- }512- }513- return cmd.Flag(name)514-}515-516-// CompDebug prints the specified string to the same file as where the517-// completion script prints its logs.518-// Note that completion printouts should never be on stdout as they would519-// be wrongly interpreted as actual completion choices by the completion script.520-func CompDebug(msg string, printToStdErr bool) {521- msg = fmt.Sprintf("[Debug] %s", msg)522-523- // Such logs are only printed when the user has set the environment524- // variable BASH_COMP_DEBUG_FILE to the path of some file to be used.525- if path := os.Getenv("BASH_COMP_DEBUG_FILE"); path != "" {526- f, err := os.OpenFile(path,527- os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)528- if err == nil {529- defer f.Close()530- WriteStringAndCheck(f, msg)531- }532- }533-534- if printToStdErr {535- // Must print to stderr for this not to be read by the completion script.536- fmt.Fprint(os.Stderr, msg)537- }538-}539-540-// CompDebugln prints the specified string with a newline at the end541-// to the same file as where the completion script prints its logs.542-// Such logs are only printed when the user has set the environment543-// variable BASH_COMP_DEBUG_FILE to the path of some file to be used.544-func CompDebugln(msg string, printToStdErr bool) {545- CompDebug(fmt.Sprintf("%s\n", msg), printToStdErr)546-}547-548-// CompError prints the specified completion message to stderr.549-func CompError(msg string) {550- msg = fmt.Sprintf("[Error] %s", msg)551- CompDebug(msg, true)552-}553-554-// CompErrorln prints the specified completion message to stderr with a newline at the end.555-func CompErrorln(msg string) {556- CompError(fmt.Sprintf("%s\n", msg))557-}modified:shell_completions.md+30 added-1 removed
5 unmodified lines6 - Zsh7 - fish8 - PowerShell9 10+Cobra will automatically provide your program with a fully functional `completion` command,11+similarly to how it provides the `help` command.12+13+## Creating your own completion command14+15+If you do not wish to use the default `completion` command, you can choose to16+provide your own, which will take precedence over the default one. (This also provides17+backwards-compatibility with programs that already have their own `completion` command.)18+19 If you are using the generator, you can create a completion command by running20 21 ```bash22 cobra add completion55 unmodified lines78 cmd.Root().GenZshCompletion(os.Stdout)79 case "fish":80 cmd.Root().GenFishCompletion(os.Stdout, true)81 case "powershell":73- cmd.Root().GenPowerShellCompletion(os.Stdout)82+ cmd.Root().GenPowerShellCompletionWithDesc(os.Stdout)83 }84 },85 }86 ```87 88 **Note:** The cobra generator may include messages printed to stdout, for example, if the config file is loaded; this will break the auto-completion script so must be removed.89 90+## Adapting the default completion command91+92+Cobra provides a few options for the default `completion` command. To configure such options you must set93+the `CompletionOptions` field on the *root* command.94+95+To tell Cobra *not* to provide the default `completion` command:96+```97+rootCmd.CompletionOptions.DisableDefaultCmd = true98+```99+100+To tell Cobra *not* to provide the user with the `--no-descriptions` flag to the completion sub-commands:101+```102+rootCmd.CompletionOptions.DisableNoDescFlag = true103+```104+105+To tell Cobra to completely disable descriptions for completions:106+```107+rootCmd.CompletionOptions.DisableDescriptions = true108+```109+110 # Customizing completions111 112 The generated completion scripts will automatically handle completing commands and flags. However, you can make your completions much more powerful by providing information to complete your program's nouns and flag values.113 399 unmodified lines