Skip to content
Myr

custom comp: do not complete flags after args when interspersed is false (#1308)

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

If the interspersed option is set false and one arg is already set all following arguments are counted as arg and not parsed as flags. Because of that we should not offer flag completion. The same applies to arguments followed after `--`.

authored by Paul Holzinger · committed by GitHub · parent 3c8a19e · Browse files · 2 files+259 added−11 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: Paul Holzinger <paul.holzinger@web.de>

Diff stats

2 files+259 added−11 removed

  • other:+259 added−11 removed

2 files+259 added−11 removed

modified:completions_test.go+222 added
1747 unmodified lines
1748 t.Errorf("expected: %q, got: %q", expected, output)1749 }1750}17511752func TestFlagCompletionWithNotInterspersedArgs(t *testing.T) {1753 rootCmd := &Command{Use: "root", Run: emptyRun}1754 childCmd := &Command{1755 Use: "child",1756 Run: emptyRun,1757 ValidArgsFunction: func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective) {1758 return []string{"--validarg", "test"}, ShellCompDirectiveDefault1759 },1760 }1761 childCmd2 := &Command{1762 Use: "child2",1763 Run: emptyRun,1764 ValidArgs: []string{"arg1", "arg2"},1765 }1766 rootCmd.AddCommand(childCmd, childCmd2)1767 childCmd.Flags().Bool("bool", false, "test bool flag")1768 childCmd.Flags().String("string", "", "test string flag")1769 _ = childCmd.RegisterFlagCompletionFunc("string", func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective) {1770 return []string{"myval"}, ShellCompDirectiveDefault1771 })17721773 // Test flag completion with no argument1774 output, err := executeCommand(rootCmd, ShellCompRequestCmd, "child", "--")1775 if err != nil {1776 t.Errorf("Unexpected error: %v", err)1777 }17781779 expected := strings.Join([]string{1780 "--bool\ttest bool flag",1781 "--string\ttest string flag",1782 ":4",1783 "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")17841785 if output != expected {1786 t.Errorf("expected: %q, got: %q", expected, output)1787 }17881789 // Test that no flags are completed after the -- arg1790 output, err = executeCommand(rootCmd, ShellCompRequestCmd, "child", "--", "-")1791 if err != nil {1792 t.Errorf("Unexpected error: %v", err)1793 }17941795 expected = strings.Join([]string{1796 "--validarg",1797 "test",1798 ":0",1799 "Completion ended with directive: ShellCompDirectiveDefault", ""}, "\n")18001801 if output != expected {1802 t.Errorf("expected: %q, got: %q", expected, output)1803 }18041805 // Test that no flags are completed after the -- arg with a flag set1806 output, err = executeCommand(rootCmd, ShellCompRequestCmd, "child", "--bool", "--", "-")1807 if err != nil {1808 t.Errorf("Unexpected error: %v", err)1809 }18101811 expected = strings.Join([]string{1812 "--validarg",1813 "test",1814 ":0",1815 "Completion ended with directive: ShellCompDirectiveDefault", ""}, "\n")18161817 if output != expected {1818 t.Errorf("expected: %q, got: %q", expected, output)1819 }18201821 // set Interspersed to false which means that no flags should be completed after the first arg1822 childCmd.Flags().SetInterspersed(false)18231824 // Test that no flags are completed after the first arg1825 output, err = executeCommand(rootCmd, ShellCompRequestCmd, "child", "arg", "--")1826 if err != nil {1827 t.Errorf("Unexpected error: %v", err)1828 }18291830 expected = strings.Join([]string{1831 "--validarg",1832 "test",1833 ":0",1834 "Completion ended with directive: ShellCompDirectiveDefault", ""}, "\n")18351836 if output != expected {1837 t.Errorf("expected: %q, got: %q", expected, output)1838 }18391840 // Test that no flags are completed after the fist arg with a flag set1841 output, err = executeCommand(rootCmd, ShellCompRequestCmd, "child", "--string", "t", "arg", "--")1842 if err != nil {1843 t.Errorf("Unexpected error: %v", err)1844 }18451846 expected = strings.Join([]string{1847 "--validarg",1848 "test",1849 ":0",1850 "Completion ended with directive: ShellCompDirectiveDefault", ""}, "\n")18511852 if output != expected {1853 t.Errorf("expected: %q, got: %q", expected, output)1854 }18551856 // Check that args are still completed after --1857 output, err = executeCommand(rootCmd, ShellCompRequestCmd, "child", "--", "")1858 if err != nil {1859 t.Errorf("Unexpected error: %v", err)1860 }18611862 expected = strings.Join([]string{1863 "--validarg",1864 "test",1865 ":0",1866 "Completion ended with directive: ShellCompDirectiveDefault", ""}, "\n")18671868 if output != expected {1869 t.Errorf("expected: %q, got: %q", expected, output)1870 }18711872 // Check that args are still completed even if flagname with ValidArgsFunction exists1873 output, err = executeCommand(rootCmd, ShellCompRequestCmd, "child", "--", "--string", "")1874 if err != nil {1875 t.Errorf("Unexpected error: %v", err)1876 }18771878 expected = strings.Join([]string{1879 "--validarg",1880 "test",1881 ":0",1882 "Completion ended with directive: ShellCompDirectiveDefault", ""}, "\n")18831884 if output != expected {1885 t.Errorf("expected: %q, got: %q", expected, output)1886 }18871888 // Check that args are still completed even if flagname with ValidArgsFunction exists1889 output, err = executeCommand(rootCmd, ShellCompRequestCmd, "child2", "--", "a")1890 if err != nil {1891 t.Errorf("Unexpected error: %v", err)1892 }18931894 expected = strings.Join([]string{1895 "arg1",1896 "arg2",1897 ":4",1898 "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")18991900 if output != expected {1901 t.Errorf("expected: %q, got: %q", expected, output)1902 }19031904 // Check that --validarg is not parsed as flag after --1905 output, err = executeCommand(rootCmd, ShellCompRequestCmd, "child", "--", "--validarg", "")1906 if err != nil {1907 t.Errorf("Unexpected error: %v", err)1908 }19091910 expected = strings.Join([]string{1911 "--validarg",1912 "test",1913 ":0",1914 "Completion ended with directive: ShellCompDirectiveDefault", ""}, "\n")19151916 if output != expected {1917 t.Errorf("expected: %q, got: %q", expected, output)1918 }19191920 // Check that --validarg is not parsed as flag after an arg1921 output, err = executeCommand(rootCmd, ShellCompRequestCmd, "child", "arg", "--validarg", "")1922 if err != nil {1923 t.Errorf("Unexpected error: %v", err)1924 }19251926 expected = strings.Join([]string{1927 "--validarg",1928 "test",1929 ":0",1930 "Completion ended with directive: ShellCompDirectiveDefault", ""}, "\n")19311932 if output != expected {1933 t.Errorf("expected: %q, got: %q", expected, output)1934 }19351936 // Check that --validarg is added to args for the ValidArgsFunction1937 childCmd.ValidArgsFunction = func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective) {1938 return args, ShellCompDirectiveDefault1939 }1940 output, err = executeCommand(rootCmd, ShellCompRequestCmd, "child", "--", "--validarg", "")1941 if err != nil {1942 t.Errorf("Unexpected error: %v", err)1943 }19441945 expected = strings.Join([]string{1946 "--validarg",1947 ":0",1948 "Completion ended with directive: ShellCompDirectiveDefault", ""}, "\n")19491950 if output != expected {1951 t.Errorf("expected: %q, got: %q", expected, output)1952 }19531954 // Check that --validarg is added to args for the ValidArgsFunction and toComplete is also set correctly1955 childCmd.ValidArgsFunction = func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective) {1956 return append(args, toComplete), ShellCompDirectiveDefault1957 }1958 output, err = executeCommand(rootCmd, ShellCompRequestCmd, "child", "--", "--validarg", "--toComp=ab")1959 if err != nil {1960 t.Errorf("Unexpected error: %v", err)1961 }19621963 expected = strings.Join([]string{1964 "--validarg",1965 "--toComp=ab",1966 ":0",1967 "Completion ended with directive: ShellCompDirectiveDefault", ""}, "\n")19681969 if output != expected {1970 t.Errorf("expected: %q, got: %q", expected, output)1971 }1972}19731974func TestFlagCompletionInGoWithDesc(t *testing.T) {1975 rootCmd := &Command{1976 Use: "root",1977 Run: emptyRun,
533 unmodified lines
modified:completions.go+37 added-11 removed
19 unmodified lines
20// ShellCompDirective is a bit map representing the different behaviors the shell21// can be instructed to have once completions have been provided.22type ShellCompDirective int2324type flagCompError struct {25 subCommand string26 flagName string27}2829func (e *flagCompError) Error() string {30 return "Subcommand '" + e.subCommand + "' does not support flag '" + e.flagName + "'"31}3233const (34 // ShellCompDirectiveError indicates an error occurred and completions should be ignored.35 ShellCompDirectiveError ShellCompDirective = 1 << iota36
195 unmodified lines
232 // Check if we are doing flag value completion before parsing the flags.233 // This is important because if we are completing a flag value, we need to also234 // remove the flag name argument from the list of finalArgs or else the parsing235 // could fail due to an invalid value (incomplete) for the flag.227 flag, finalArgs, toComplete, err := checkIfFlagCompletion(finalCmd, finalArgs, toComplete)228 if err != nil {229 // Error while attempting to parse flags230 return finalCmd, []string{}, ShellCompDirectiveDefault, err231 }236 flag, finalArgs, toComplete, flagErr := checkIfFlagCompletion(finalCmd, finalArgs, toComplete)237238 // Check if interspersed is false or -- was set on a previous arg.239 // This works by counting the arguments. Normally -- is not counted as arg but240 // if -- was already set or interspersed is false and there is already one arg then241 // the extra added -- is counted as arg.242 flagCompletion := true243 _ = finalCmd.ParseFlags(append(finalArgs, "--"))244 newArgCount := finalCmd.Flags().NArg()245246 // Parse the flags early so we can check if required flags are set247 if err = finalCmd.ParseFlags(finalArgs); err != nil {248 return finalCmd, []string{}, ShellCompDirectiveDefault, fmt.Errorf("Error while parsing flags from args %v: %s", finalArgs, err.Error())249 }250251 realArgCount := finalCmd.Flags().NArg()252 if newArgCount > realArgCount {253 // don't do flag completion (see above)254 flagCompletion = false255 }256 // Error while attempting to parse flags238 if flag != nil {257 if flagErr != nil {258 // If error type is flagCompError and we don't want flagCompletion we should ignore the error259 if _, ok := flagErr.(*flagCompError); !(ok && !flagCompletion) {260 return finalCmd, []string{}, ShellCompDirectiveDefault, flagErr261 }262 }263264 if flag != nil && flagCompletion {265 // Check if we are completing a flag value subject to annotations266 if validExts, present := flag.Annotations[BashCompFilenameExt]; present {267 if len(validExts) != 0 {268 // File completion filtered by extensions
18 unmodified lines
287288 // When doing completion of a flag name, as soon as an argument starts with289 // a '-' we know it is a flag. We cannot use isFlagArg() here as it requires290 // the flag name to be complete265 if flag == nil && len(toComplete) > 0 && toComplete[0] == '-' && !strings.Contains(toComplete, "=") {291 if flag == nil && len(toComplete) > 0 && toComplete[0] == '-' && !strings.Contains(toComplete, "=") && flagCompletion {292 var completions []string293294 // First check for required flags295 completions = completeRequireFlags(finalCmd, toComplete)
104 unmodified lines
400 }401402 // Find the completion function for the flag or command403 var completionFn func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective)378 if flag != nil {404 if flag != nil && flagCompletion {405 completionFn = c.Root().flagCompletionFunctions[flag]406 } else {407 completionFn = finalCmd.ValidArgsFunction408 }
75 unmodified lines
484485 var flagName string486 trimmedArgs := args487 flagWithEqual := false488 orgLastArg := lastArg489490 // When doing completion of a flag name, as soon as an argument starts with491 // a '-' we know it is a flag. We cannot use isFlagArg() here as that function492 // requires the flag name to be complete
50 unmodified lines
543 }544545 flag := findFlag(finalCmd, flagName)546 if flag == nil {520 // Flag not supported by this command, nothing to complete521 err := fmt.Errorf("Subcommand '%s' does not support flag '%s'", finalCmd.Name(), flagName)522 return nil, nil, "", err547 // Flag not supported by this command, the interspersed option might be set so return the original args548 return nil, args, orgLastArg, &flagCompError{subCommand: finalCmd.Name(), flagName: flagName}549 }550551 if !flagWithEqual {552 if len(flag.NoOptDefVal) != 0 {
219 unmodified lines