Skip to content

Commit a73b9c3

Browse files
nirsmarckhouzam
authored andcommitted
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
1 parent df547f5 commit a73b9c3

File tree

2 files changed

+23
-2
lines changed

2 files changed

+23
-2
lines changed

command.go

+3-2
Original file line numberDiff line numberDiff line change
@@ -1441,10 +1441,11 @@ func (c *Command) displayName() string {
14411441
// UseLine puts out the full usage for a given command (including parents).
14421442
func (c *Command) UseLine() string {
14431443
var useline string
1444+
use := strings.Replace(c.Use, c.Name(), c.displayName(), 1)
14441445
if c.HasParent() {
1445-
useline = c.parent.CommandPath() + " " + c.Use
1446+
useline = c.parent.CommandPath() + " " + use
14461447
} else {
1447-
useline = c.Use
1448+
useline = use
14481449
}
14491450
if c.DisableFlagsInUseLine {
14501451
return useline

command_test.go

+20
Original file line numberDiff line numberDiff line change
@@ -370,6 +370,26 @@ func TestAliasPrefixMatching(t *testing.T) {
370370
// executable is `kubectl-plugin`, but we run it as `kubectl plugin`. The help
371371
// text should reflect the way we run the command.
372372
func TestPlugin(t *testing.T) {
373+
cmd := &Command{
374+
Use: "kubectl-plugin",
375+
Args: NoArgs,
376+
Annotations: map[string]string{
377+
CommandDisplayNameAnnotation: "kubectl plugin",
378+
},
379+
Run: emptyRun,
380+
}
381+
382+
cmdHelp, err := executeCommand(cmd, "-h")
383+
if err != nil {
384+
t.Errorf("Unexpected error: %v", err)
385+
}
386+
387+
checkStringContains(t, cmdHelp, "kubectl plugin [flags]")
388+
checkStringContains(t, cmdHelp, "help for kubectl plugin")
389+
}
390+
391+
// TestPlugin checks usage as plugin with sub commands.
392+
func TestPluginWithSubCommands(t *testing.T) {
373393
rootCmd := &Command{
374394
Use: "kubectl-plugin",
375395
Args: NoArgs,

0 commit comments

Comments
 (0)