Skip to content

Commit

Permalink
Handle linebreaks in custom completions. (#1162)
Browse files Browse the repository at this point in the history
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 <paul.holzinger@web.de>
  • Loading branch information
Luap99 authored Sep 9, 2020
1 parent 50258f1 commit 8a63648
Show file tree
Hide file tree
Showing 2 changed files with 7 additions and 1 deletion.
6 changes: 6 additions & 0 deletions custom_completions.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
2 changes: 1 addition & 1 deletion custom_completions_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -561,7 +561,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")

Expand Down

0 comments on commit 8a63648

Please sign in to comment.