Skip to content

Commit

Permalink
Fix help text for runnable plugin command
Browse files Browse the repository at this point in the history
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
  • Loading branch information
nirs authored and marckhouzam committed Dec 18, 2023
1 parent df547f5 commit a73b9c3
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 2 deletions.
5 changes: 3 additions & 2 deletions command.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
20 changes: 20 additions & 0 deletions command_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down

0 comments on commit a73b9c3

Please sign in to comment.