Skip to content

Commit 71ef96a

Browse files
committed
Support usage as plugin for tools like kubectl
In this case the executable is `kubectl-plugin`, but we run it as: kubectl plugin And the help text should reflect the actual usage of the command. To create a plugin create the root command like: rootCmd := &cobra.Command{ CommandName: "kubectl plugin", } When `CommandName` is set, Name() use it as is instead of guessing the command name from the `Use` line. Issues: - Need to update the docs. Fixes: #2017 Signed-off-by: Nir Soffer <[email protected]>
1 parent fd865a4 commit 71ef96a

File tree

2 files changed

+31
-1
lines changed

2 files changed

+31
-1
lines changed

command.go

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -57,6 +57,10 @@ type Command struct {
5757
// Example: add [-F file | -D dir]... [-f format] profile
5858
Use string
5959

60+
// CommandName is the command name if set. Otherwise the command
61+
// name is the first word of the `Use` line.
62+
CommandName string
63+
6064
// Aliases is an array of aliases that can be used instead of the first word in Use.
6165
Aliases []string
6266

@@ -1441,8 +1445,11 @@ func (c *Command) DebugFlags() {
14411445
debugflags(c)
14421446
}
14431447

1444-
// Name returns the command's name: the first word in the use line.
1448+
// Name returns CommandName or the first word in the use line.
14451449
func (c *Command) Name() string {
1450+
if c.CommandName != "" {
1451+
return c.CommandName
1452+
}
14461453
name := c.Use
14471454
i := strings.Index(name, " ")
14481455
if i >= 0 {

command_test.go

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -366,6 +366,29 @@ func TestAliasPrefixMatching(t *testing.T) {
366366
EnablePrefixMatching = defaultPrefixMatching
367367
}
368368

369+
// TestPlugin checks usage as plugin for aother commmand such as kubectl. The
370+
// executable is `kubectl-plugin`, but we run it as `kubectl plugin`. The help
371+
// text should reflect the way we run the commmand.
372+
func TestPlugin(t *testing.T) {
373+
rootCmd := &Command{CommandName: "kubectl plugin", Args: NoArgs}
374+
subCmd := &Command{Use: "sub [flags]", Args: NoArgs, Run: emptyRun}
375+
rootCmd.AddCommand(subCmd)
376+
377+
rootHelp, err := executeCommand(rootCmd, "-h")
378+
if err != nil {
379+
t.Errorf("Unexpected error: %v", err)
380+
}
381+
382+
checkStringContains(t, rootHelp, "kubectl plugin [command]")
383+
384+
childHelp, err := executeCommand(rootCmd, "sub", "-h")
385+
if err != nil {
386+
t.Errorf("Unexpected error: %v", err)
387+
}
388+
389+
checkStringContains(t, childHelp, "kubectl plugin sub [flags]")
390+
}
391+
369392
// TestChildSameName checks the correct behaviour of cobra in cases,
370393
// when an application with name "foo" and with subcommand "foo"
371394
// is executed with args "foo foo".

0 commit comments

Comments
 (0)