From cf002b9a50d777b10beaf228f316c5da34f8178a Mon Sep 17 00:00:00 2001 From: Eyal Posener Date: Thu, 21 Nov 2019 00:16:33 +0200 Subject: [PATCH] Fix completion of help when completing flags --- complete.go | 36 ++++++++++++++++++++++-------------- complete_test.go | 1 + 2 files changed, 23 insertions(+), 14 deletions(-) diff --git a/complete.go b/complete.go index b649ee4..9ddfee2 100644 --- a/complete.go +++ b/complete.go @@ -143,7 +143,8 @@ reset: func (c completer) suggestSubCommands(prefix string) []string { if len(prefix) > 0 && prefix[0] == '-' { - return []string{helpFlag(prefix)} + help, _ := helpFlag(prefix) + return []string{help} } subs := c.SubCmdList() return suggest("", prefix, func(prefix string) []string { @@ -256,19 +257,23 @@ func (c completer) iterateStack(f func(Completer)) { func suggest(dashes, prefix string, collect func(prefix string) []string) []string { options := collect(prefix) - // If nothing was suggested, suggest all flags. - if len(options) == 0 { - prefix = "" - options = collect(prefix) + help, helpMatched := helpFlag(dashes + prefix) + // In case that something matched: + if len(options) > 0 { + if strings.HasPrefix(help, dashes+prefix) { + options = append(options, help) + } + return options } - // Add help flag if needed. - help := helpFlag(dashes + prefix) - if len(options) == 0 || strings.HasPrefix(help, dashes+prefix) { - options = append(options, help) + if helpMatched { + return []string{help} } - return options + // Nothing matched. + options = collect("") + help, _ = helpFlag(dashes) + return append(options, help) } func filterByPrefix(prefix string, options ...string) []string { @@ -321,12 +326,15 @@ func hasPrefix(s, prefix string) (string, bool) { } // helpFlag returns either "-h", "-help" or "--help". -func helpFlag(prefix string) string { +func helpFlag(prefix string) (string, bool) { if prefix == "" || prefix == "-" || prefix == "-h" { - return "-h" + return "-h", true + } + if strings.HasPrefix("--help", prefix) { + return "--help", true } if strings.HasPrefix(prefix, "--") { - return "--help" + return "--help", false } - return "-help" + return "-help", false } diff --git a/complete_test.go b/complete_test.go index 36e6c5b..a7c6834 100644 --- a/complete_test.go +++ b/complete_test.go @@ -125,6 +125,7 @@ func TestCompleter(t *testing.T) { {args: "--", want: []string{"--help"}}, {args: "-he", want: []string{"-help"}}, {args: "-x", want: []string{"-help"}}, + {args: "flags -h", want: []string{"-h"}}, } for _, tt := range tests {