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
Provenance
- Commit
5d46ac9- Tree
425b1e6- Author
Paul Holzinger <45212748+Luap99@users.noreply.github.com>- Committer
GitHub <noreply@github.com>- Parent
3c8a19e
2 files changed+259 added−11 removed
modified:completions_test.go+222 added
1747 unmodified lines1748 t.Errorf("expected: %q, got: %q", expected, output)1749 }1750 }1751 1752+func 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+ })1772+1773+ // Test flag completion with no argument1774+ output, err := executeCommand(rootCmd, ShellCompRequestCmd, "child", "--")1775+ if err != nil {1776+ t.Errorf("Unexpected error: %v", err)1777+ }1778+1779+ expected := strings.Join([]string{1780+ "--bool\ttest bool flag",1781+ "--string\ttest string flag",1782+ ":4",1783+ "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")1784+1785+ if output != expected {1786+ t.Errorf("expected: %q, got: %q", expected, output)1787+ }1788+1789+ // 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+ }1794+1795+ expected = strings.Join([]string{1796+ "--validarg",1797+ "test",1798+ ":0",1799+ "Completion ended with directive: ShellCompDirectiveDefault", ""}, "\n")1800+1801+ if output != expected {1802+ t.Errorf("expected: %q, got: %q", expected, output)1803+ }1804+1805+ // 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+ }1810+1811+ expected = strings.Join([]string{1812+ "--validarg",1813+ "test",1814+ ":0",1815+ "Completion ended with directive: ShellCompDirectiveDefault", ""}, "\n")1816+1817+ if output != expected {1818+ t.Errorf("expected: %q, got: %q", expected, output)1819+ }1820+1821+ // set Interspersed to false which means that no flags should be completed after the first arg1822+ childCmd.Flags().SetInterspersed(false)1823+1824+ // 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+ }1829+1830+ expected = strings.Join([]string{1831+ "--validarg",1832+ "test",1833+ ":0",1834+ "Completion ended with directive: ShellCompDirectiveDefault", ""}, "\n")1835+1836+ if output != expected {1837+ t.Errorf("expected: %q, got: %q", expected, output)1838+ }1839+1840+ // 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+ }1845+1846+ expected = strings.Join([]string{1847+ "--validarg",1848+ "test",1849+ ":0",1850+ "Completion ended with directive: ShellCompDirectiveDefault", ""}, "\n")1851+1852+ if output != expected {1853+ t.Errorf("expected: %q, got: %q", expected, output)1854+ }1855+1856+ // 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+ }1861+1862+ expected = strings.Join([]string{1863+ "--validarg",1864+ "test",1865+ ":0",1866+ "Completion ended with directive: ShellCompDirectiveDefault", ""}, "\n")1867+1868+ if output != expected {1869+ t.Errorf("expected: %q, got: %q", expected, output)1870+ }1871+1872+ // 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+ }1877+1878+ expected = strings.Join([]string{1879+ "--validarg",1880+ "test",1881+ ":0",1882+ "Completion ended with directive: ShellCompDirectiveDefault", ""}, "\n")1883+1884+ if output != expected {1885+ t.Errorf("expected: %q, got: %q", expected, output)1886+ }1887+1888+ // 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+ }1893+1894+ expected = strings.Join([]string{1895+ "arg1",1896+ "arg2",1897+ ":4",1898+ "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")1899+1900+ if output != expected {1901+ t.Errorf("expected: %q, got: %q", expected, output)1902+ }1903+1904+ // 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+ }1909+1910+ expected = strings.Join([]string{1911+ "--validarg",1912+ "test",1913+ ":0",1914+ "Completion ended with directive: ShellCompDirectiveDefault", ""}, "\n")1915+1916+ if output != expected {1917+ t.Errorf("expected: %q, got: %q", expected, output)1918+ }1919+1920+ // 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+ }1925+1926+ expected = strings.Join([]string{1927+ "--validarg",1928+ "test",1929+ ":0",1930+ "Completion ended with directive: ShellCompDirectiveDefault", ""}, "\n")1931+1932+ if output != expected {1933+ t.Errorf("expected: %q, got: %q", expected, output)1934+ }1935+1936+ // 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+ }1944+1945+ expected = strings.Join([]string{1946+ "--validarg",1947+ ":0",1948+ "Completion ended with directive: ShellCompDirectiveDefault", ""}, "\n")1949+1950+ if output != expected {1951+ t.Errorf("expected: %q, got: %q", expected, output)1952+ }1953+1954+ // 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+ }1962+1963+ expected = strings.Join([]string{1964+ "--validarg",1965+ "--toComp=ab",1966+ ":0",1967+ "Completion ended with directive: ShellCompDirectiveDefault", ""}, "\n")1968+1969+ if output != expected {1970+ t.Errorf("expected: %q, got: %q", expected, output)1971+ }1972+}1973+1974 func TestFlagCompletionInGoWithDesc(t *testing.T) {1975 rootCmd := &Command{1976 Use: "root",1977 Run: emptyRun,533 unmodified linesmodified:completions.go+37 added-11 removed
19 unmodified lines20 // ShellCompDirective is a bit map representing the different behaviors the shell21 // can be instructed to have once completions have been provided.22 type ShellCompDirective int23 24+type flagCompError struct {25+ subCommand string26+ flagName string27+}28+29+func (e *flagCompError) Error() string {30+ return "Subcommand '" + e.subCommand + "' does not support flag '" + e.flagName + "'"31+}32+33 const (34 // ShellCompDirectiveError indicates an error occurred and completions should be ignored.35 ShellCompDirectiveError ShellCompDirective = 1 << iota36 195 unmodified lines232 // 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)237 238+ // 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()245+246 // 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 }250 251+ 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+ }263+264+ 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 extensions18 unmodified lines287 288 // 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 []string293 294 // First check for required flags295 completions = completeRequireFlags(finalCmd, toComplete)104 unmodified lines400 }401 402 // 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 lines484 485 var flagName string486 trimmedArgs := args487 flagWithEqual := false488+ orgLastArg := lastArg489 490 // 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 complete50 unmodified lines543 }544 545 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 }550 551 if !flagWithEqual {552 if len(flag.NoOptDefVal) != 0 {219 unmodified lines