Automatic cobra command registration with fx

Cobra is a popular Go package for creating CLIs. It provides a lot of functionality for creating commands, subcommands, and flags. However, it can be tedious to manually register all of your commands.

fx is a Go package that provides a dependency injection framework. It can be used to automatically register your application components, including but not limited to Cobra commands.

In this blog post, I will show you how you can use fx to automatically register your Cobra commands.

This code was written 5 minutes ago, but works, and I imagine it could help folks bootstrap more complex CLIs rapidly.

The problem

When you create a Cobra command, you need to manually register it with the root command. This can be tedious, especially if you have a lot of commands.

For example, the following code registers a command called hello:

func NewHelloCmd() *cobra.Command {
  cmd := &cobra.Command{
    Use:   "hello",
    Short: "Say hello",
    Run: func(cmd *cobra.Command, args []string) {
      cmd.Println("Hello, world!")
    },
  }
  return cmd
}

func main() {
  rootCmd := &cobra.Command{
    Use:   "myapp",
    Short: "My application",
  }
  rootCmd.AddCommand(NewHelloCmd())
  rootCmd.Execute()
}Code language: Go (go)

Read more

cobra: unable to redefine ‘h’ shorthand

Cobra is both a library for creating powerful modern CLI applications as well as a program to generate applications and command files”

I’m currently using Cobra in the MediaWiki CLI project and recently came across an error while trying to auto-generate docs.

panic: unable to redefine 'h' shorthand in "login" flagset: it's already used for "hostname" flag

goroutine 1 [running]:
github.com/spf13/pflag.(*FlagSet).AddFlag(0xc0000b5d00, 0xc00053d680)
        /go/pkg/mod/github.com/spf13/pflag@v1.0.5/flag.go:874 +0x6f0Code language: PHP (php)

I’m not actually trying to redefine this flag, but it looks like by default cobra always uses the -h flag for a help command, if you don’t define a help flag that doesn’t have the shorthand.

Read more