Using the Cobra Library

To manually implement Cobra you need to create a bare main.go file and a rootCmd file.
You will optionally provide additional commands as you see fit.

Create rootCmd

Cobra doesn’t require any special constructors. Simply create your commands.

Ideally you place this in app/cmd/root.go:

  1. var rootCmd = &cobra.Command{
  2. Use: "hugo",
  3. Short: "Hugo is a very fast static site generator",
  4. Long: `A Fast and Flexible Static Site Generator built with
  5. love by spf13 and friends in Go.
  6. Complete documentation is available at http://hugo.spf13.com`,
  7. Run: func(cmd *cobra.Command, args []string) {
  8. // Do Stuff Here
  9. },
  10. }
  11. func Execute() {
  12. if err := rootCmd.Execute(); err != nil {
  13. fmt.Println(err)
  14. os.Exit(1)
  15. }
  16. }

You will additionally define flags and handle configuration in your init() function.

For example cmd/root.go:

  1. import (
  2. "fmt"
  3. "os"
  4. homedir "github.com/mitchellh/go-homedir"
  5. "github.com/spf13/cobra"
  6. "github.com/spf13/viper"
  7. )
  8. func init() {
  9. cobra.OnInitialize(initConfig)
  10. rootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.cobra.yaml)")
  11. rootCmd.PersistentFlags().StringVarP(&projectBase, "projectbase", "b", "", "base project directory eg. github.com/spf13/")
  12. rootCmd.PersistentFlags().StringP("author", "a", "YOUR NAME", "Author name for copyright attribution")
  13. rootCmd.PersistentFlags().StringVarP(&userLicense, "license", "l", "", "Name of license for the project (can provide `licensetext` in config)")
  14. rootCmd.PersistentFlags().Bool("viper", true, "Use Viper for configuration")
  15. viper.BindPFlag("author", rootCmd.PersistentFlags().Lookup("author"))
  16. viper.BindPFlag("projectbase", rootCmd.PersistentFlags().Lookup("projectbase"))
  17. viper.BindPFlag("useViper", rootCmd.PersistentFlags().Lookup("viper"))
  18. viper.SetDefault("author", "NAME HERE <EMAIL ADDRESS>")
  19. viper.SetDefault("license", "apache")
  20. }
  21. func initConfig() {
  22. // Don't forget to read config either from cfgFile or from home directory!
  23. if cfgFile != "" {
  24. // Use config file from the flag.
  25. viper.SetConfigFile(cfgFile)
  26. } else {
  27. // Find home directory.
  28. home, err := homedir.Dir()
  29. if err != nil {
  30. fmt.Println(err)
  31. os.Exit(1)
  32. }
  33. // Search config in home directory with name ".cobra" (without extension).
  34. viper.AddConfigPath(home)
  35. viper.SetConfigName(".cobra")
  36. }
  37. if err := viper.ReadInConfig(); err != nil {
  38. fmt.Println("Can't read config:", err)
  39. os.Exit(1)
  40. }
  41. }

Create your main.go

With the root command you need to have your main function execute it.
Execute should be run on the root for clarity, though it can be called on any command.

In a Cobra app, typically the main.go file is very bare. It serves, one purpose, to initialize Cobra.

  1. package main
  2. import (
  3. "{pathToYourApp}/cmd"
  4. )
  5. func main() {
  6. cmd.Execute()
  7. }

Create additional commands

Additional commands can be defined and typically are each given their own file
inside of the cmd/ directory.

If you wanted to create a version command you would create cmd/version.go and
populate it with the following:

  1. package cmd
  2. import (
  3. "fmt"
  4. "github.com/spf13/cobra"
  5. )
  6. func init() {
  7. rootCmd.AddCommand(versionCmd)
  8. }
  9. var versionCmd = &cobra.Command{
  10. Use: "version",
  11. Short: "Print the version number of Hugo",
  12. Long: `All software has versions. This is Hugo's`,
  13. Run: func(cmd *cobra.Command, args []string) {
  14. fmt.Println("Hugo Static Site Generator v0.9 -- HEAD")
  15. },
  16. }