Allow command name to have an escaped space

This commit is contained in:
Brian Pursley 2020-03-11 14:55:11 -04:00
parent 95f2f73ed9
commit 94822da119
2 changed files with 47 additions and 4 deletions

View file

@ -1203,9 +1203,9 @@ func (c *Command) CommandPath() string {
func (c *Command) UseLine() string {
var useline string
if c.HasParent() {
useline = c.parent.CommandPath() + " " + c.Use
useline = c.parent.CommandPath() + " " + replaceEscapedSpaces(c.Use)
} else {
useline = c.Use
useline = replaceEscapedSpaces(c.Use)
}
if c.DisableFlagsInUseLine {
return useline
@ -1260,11 +1260,29 @@ func (c *Command) DebugFlags() {
// Name returns the command's name: the first word in the use line.
func (c *Command) Name() string {
name := c.Use
i := strings.Index(name, " ")
i := getIndexOfFirstNonEscapedSpace(name)
if i >= 0 {
name = name[:i]
}
return name
return replaceEscapedSpaces(name)
}
func getIndexOfFirstNonEscapedSpace(s string) int {
i := 0
for i < len(s) {
switch s[i] {
case '\\':
i++ // The next character is escaped, so advance another position to skip over it
case ' ':
return i
}
i++
}
return -1
}
func replaceEscapedSpaces(s string) string {
return strings.Replace(s, "\\ ", " ", -1)
}
// HasAlias determines if a given string is an alias of the command.

View file

@ -1955,3 +1955,28 @@ func TestFParseErrWhitelistSiblingCommand(t *testing.T) {
}
checkStringContains(t, output, "unknown flag: --unknown")
}
func TestHelpDisplaysRootCommandNameWithEscapedSpace(t *testing.T) {
rootCmd := &Command{Use: "kubectl\\ myplugin", Run: emptyRun}
rootCmd.AddCommand(&Command{Use: "child", Run: emptyRun})
output, err := executeCommand(rootCmd, "help")
if err != nil {
t.Errorf("Unexpected error: %v", err)
}
checkStringContains(t, output, "kubectl myplugin [command]")
}
func TestSubcommandHelpDisplaysRootCommandNameWithEscapedSpace(t *testing.T) {
rootCmd := &Command{Use: "kubectl\\ myplugin", Run: emptyRun}
childCmd := &Command{Use: "child", Long: "Long description", Run: emptyRun}
rootCmd.AddCommand(childCmd)
output, err := executeCommand(rootCmd, "help", "child")
if err != nil {
t.Errorf("Unexpected error: %v", err)
}
checkStringContains(t, output, "kubectl myplugin child [flags]")
}