Skip to content

Support usage line when running as kubectl plugin #2017

@nirs

Description

@nirs

When running as a kubectl plugin[1] we want the help text to look like a builtin
kubectl command. For example if we create a program kubectl-cobra:

$ cat main.go 
package main

import (
	"fmt"

	"github.com/spf13/cobra"
)

func main() {
	root := &cobra.Command{
		Use: "kubectl cobra",
	}

	sub := &cobra.Command{
		Use: "subcmd",
		Run: func(cmd *cobra.Command, args []string) {
			fmt.Println("kubectl cobra subcmd")
		},
	}

	root.AddCommand(sub)
	root.Execute()
}

When we run it we get unwanted output:

$ kubectl cobra
Usage:
  kubectl [command]

Available Commands:
  completion  Generate the autocompletion script for the specified shell
  help        Help about any command
  subcmd      

Flags:
  -h, --help   help for kubectl

Use "kubectl [command] --help" for more information about a command.

$ kubectl cobra subcmd -h
Usage:
  kubectl subcmd [flags]

Flags:
  -h, --help   help for subcmd

The wanted output:

$ kubectl cobra
Usage:
  kubectl cobra [command]

Available Commands:
  completion  Generate the autocompletion script for the specified shell
  help        Help about any command
  subcmd      

Flags:
  -h, --help   help for kubectl cobra

Use "kubectl cobra [command] --help" for more information about a command.

$ kubectl cobra subcmd -h
Usage:
  kubectl cobra subcmd [flags]

Flags:
  -h, --help   help for subcmd

The problem is we don't have a way to set the command name, it is guessed
best on the first word of the Use field. SetUsageFunc() and SetUsageTemplate()
are not helpful in fixing this issue since it require re-implementing too much
logic and template which a user really don't want to re-implement.

Maybe we need SetNameFunc(), or Name field?

Workaround

If can get the wanted output using:

	root := &cobra.Command{
		Use: "kubectl\u00A0cobra",
	}

It works for help output, but I did not check if this affects shell completion.

[1] https://kubernetes.io/docs/tasks/extend-kubectl/kubectl-plugins/

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions