From 86f532b7caea2ba33659447af7768960c93e52d4 Mon Sep 17 00:00:00 2001 From: Paul Holzinger Date: Sun, 12 Jul 2020 17:07:15 +0200 Subject: [PATCH] Handle linebreaks in custom completions. If a command/flag description contains a linebreak then the shell completion script will interpret this as new command/flag. To fix this we only use the first line from the description in the output. Signed-off-by: Paul Holzinger --- custom_completions.go | 6 ++++++ custom_completions_test.go | 2 +- 2 files changed, 7 insertions(+), 1 deletion(-) diff --git a/custom_completions.go b/custom_completions.go index c25c03e40..df4500388 100644 --- a/custom_completions.go +++ b/custom_completions.go @@ -132,6 +132,12 @@ func (c *Command) initCompleteCmd(args []string) { comp = strings.Split(comp, "\t")[0] } + // Make sure we only write the first line to the output. + // This is needed if a description contains a linebreak. + // Otherwise the shell scripts will interpret the other lines as new flags + // and could therefore provide a wrong completion. + comp = strings.Split(comp, "\n")[0] + // Finally trim the completion. This is especially important to get rid // of a trailing tab when there are no description following it. // For example, a sub-command without a description should not be completed diff --git a/custom_completions_test.go b/custom_completions_test.go index 276b8a77b..885c81d3c 100644 --- a/custom_completions_test.go +++ b/custom_completions_test.go @@ -501,7 +501,7 @@ func TestFlagNameCompletionInGoWithDesc(t *testing.T) { } rootCmd.AddCommand(childCmd) - rootCmd.Flags().IntP("first", "f", -1, "first flag") + rootCmd.Flags().IntP("first", "f", -1, "first flag\nlonger description for flag") rootCmd.PersistentFlags().BoolP("second", "s", false, "second flag") childCmd.Flags().String("subFlag", "", "sub flag")