Fix help text for runnable plugin command

When creating a plugin without sub commands, the help text included the
command name (kubectl-plugin) instead of the display name (kubectl plugin):

    Usage:
      kubectl-plugin [flags]

The issue is that the usage line for this case does not use the
command path but the raw `Use` string, and this case was not tested.

Add a test for this case and fix UsageLine() to replace the command name
with the display name.

Tested using https://github.com/nirs/kubernetes/tree/sample-cli-plugin-help
This commit is contained in:
Nir Soffer 2023-11-12 20:07:59 +02:00 committed by Marc Khouzam
parent df547f5fc6
commit a73b9c391a
2 changed files with 23 additions and 2 deletions

View File

@ -1441,10 +1441,11 @@ func (c *Command) displayName() string {
// UseLine puts out the full usage for a given command (including parents).
func (c *Command) UseLine() string {
var useline string
use := strings.Replace(c.Use, c.Name(), c.displayName(), 1)
if c.HasParent() {
useline = c.parent.CommandPath() + " " + c.Use
useline = c.parent.CommandPath() + " " + use
} else {
useline = c.Use
useline = use
}
if c.DisableFlagsInUseLine {
return useline

View File

@ -370,6 +370,26 @@ func TestAliasPrefixMatching(t *testing.T) {
// executable is `kubectl-plugin`, but we run it as `kubectl plugin`. The help
// text should reflect the way we run the command.
func TestPlugin(t *testing.T) {
cmd := &Command{
Use: "kubectl-plugin",
Args: NoArgs,
Annotations: map[string]string{
CommandDisplayNameAnnotation: "kubectl plugin",
},
Run: emptyRun,
}
cmdHelp, err := executeCommand(cmd, "-h")
if err != nil {
t.Errorf("Unexpected error: %v", err)
}
checkStringContains(t, cmdHelp, "kubectl plugin [flags]")
checkStringContains(t, cmdHelp, "help for kubectl plugin")
}
// TestPlugin checks usage as plugin with sub commands.
func TestPluginWithSubCommands(t *testing.T) {
rootCmd := &Command{
Use: "kubectl-plugin",
Args: NoArgs,