[Awesome Go] Use corbar package to create powerful modern CLI interfaces similar to git & go tools

Cobra

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

Cobra is used in many Go projects such as [Kubernetes - https://kubernetes.io/], Hugo - https://gohugo.io/, and Github CLI - https://github.com/cli/cli to name a few. This list - https://github.com/spf13/cobra/blob/master/projects_using_cobra.md contains a more extensive list of projects using Cobra.

Cobra provides:

  • Easy subcommand-based CLIs: app server, app fetch, etc.

  • Fully POSIX-compliant flags (including short & long versions)

  • Nested subcommands

  • Global, local and cascading flags

  • Easy generation of applications & commands with cobra init appname & cobra add cmdname

  • Intelligent suggestions (app srver… did you mean app server?)

  • Automatic help generation for commands and flags

  • Automatic help flag recognition of -h, --help, etc.

  • Automatically generated shell autocomplete for your application (bash, zsh, fish, powershell)

  • Automatically generated man pages for your application

  • Command aliases so you can change things without breaking them

  • The flexibility to define your own help, usage, etc.

  • Optional tight integration with viper for 12-factor apps

Concepts

Cobra is built on a structure of commands, arguments & flags.

Commands represent actions, Args are things and Flags are modifiers for those actions.

The best applications read like sentences when used, and as a result, users intuitively know how to interact with them.

The pattern to follow is APPNAME VERB NOUN --ADJECTIVE. or APPNAME COMMAND ARG --FLAG

A few good real world examples may better illustrate this point.

In the following example, ‘server’ is a command, and ‘port’ is a flag:

1
$ hugo server --port=1313

In this command we are telling Git to clone the url bare.

1
$ git clone URL --bare

Commands

Command is the central point of the application. Each interaction that the application supports will be contained in a Command. A command can have children commands and optionally run an action.

In the example above, ‘server’ is the command.

More about cobra.Command - https://godoc.org/github.com/spf13/cobra#Command

Flags

A flag is a way to modify the behavior of a command. Cobra supports fully POSIX-compliant flags as well as the Go flag package - https://golang.org/pkg/flag/. A Cobra command can define flags that persist through to children commands and flags that are only available to that command.

In the example above, ‘port’ is the flag.

Flag functionality is provided by the pflag library - https://github.com/spf13/pflag, a fork of the flag standard library which maintains the same interface while adding POSIX compliance.

Installation

Standard go get:

1
go get -u github.com/spf13/cobra

This command will install the cobra generator executable along with the library and its dependencies:

Next, include it in your application:

1
import "github.com/spf13/cobra"

Usage

Getting Started

While you are welcome to provide your own organization, typically a Cobra-based application will follow the following organizational structure:

1
2
3
4
5
6
7
▾ appName/
▾ cmd/
add.go
your.go
commands.go
here.go
main.go

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

1
2
3
4
5
6
7
8
9
package main

import (
"{pathToYourApp}/cmd"
)

func main() {
cmd.Execute()
}

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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
var rootCmd = &cobra.Command{
Use: "hugo",
Short: "Hugo is a very fast static site generator",
Long: `A Fast and Flexible Static Site Generator built with
love by spf13 and friends in Go.
Complete documentation is available at http://hugo.spf13.com`,
Run: func(cmd *cobra.Command, args []string) {
// Do Stuff Here
},
}

func Execute() {
if err := rootCmd.Execute(); err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
}

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

For example cmd/root.go:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
package cmd

import (
"fmt"
"os"

homedir "github.com/mitchellh/go-homedir"
"github.com/spf13/cobra"
"github.com/spf13/viper"
)

var (
// Used for flags.
cfgFile string
userLicense string

rootCmd = &cobra.Command{
Use: "cobra",
Short: "A generator for Cobra based Applications",
Long: `Cobra is a CLI library for Go that empowers applications.
This application is a tool to generate the needed files
to quickly create a Cobra application.`,
}
)

// Execute executes the root command.
func Execute() error {
return rootCmd.Execute()
}

func init() {
cobra.OnInitialize(initConfig)

rootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.cobra.yaml)")
rootCmd.PersistentFlags().StringP("author", "a", "YOUR NAME", "author name for copyright attribution")
rootCmd.PersistentFlags().StringVarP(&userLicense, "license", "l", "", "name of license for the project")
rootCmd.PersistentFlags().Bool("viper", true, "use Viper for configuration")
viper.BindPFlag("author", rootCmd.PersistentFlags().Lookup("author"))
viper.BindPFlag("useViper", rootCmd.PersistentFlags().Lookup("viper"))
viper.SetDefault("author", "NAME HERE <EMAIL ADDRESS>")
viper.SetDefault("license", "apache")

rootCmd.AddCommand(addCmd)
rootCmd.AddCommand(initCmd)
}

func initConfig() {
if cfgFile != "" {
// Use config file from the flag.
viper.SetConfigFile(cfgFile)
} else {
// Find home directory.
home, err := homedir.Dir()
cobra.CheckErr(err)

// Search config in home directory with name ".cobra" (without extension).
viper.AddConfigPath(home)
viper.SetConfigName(".cobra")
}

viper.AutomaticEnv()

if err := viper.ReadInConfig(); err == nil {
fmt.Println("Using config file:", viper.ConfigFileUsed())
}
}

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
2
3
4
5
6
7
8
9
package main

import (
"{pathToYourApp}/cmd"
)

func main() {
cmd.Execute()
}

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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
package cmd

import (
"fmt"

"github.com/spf13/cobra"
)

func init() {
rootCmd.AddCommand(versionCmd)
}

var versionCmd = &cobra.Command{
Use: "version",
Short: "Print the version number of Hugo",
Long: `All software has versions. This is Hugo's`,
Run: func(cmd *cobra.Command, args []string) {
fmt.Println("Hugo Static Site Generator v0.9 -- HEAD")
},
}

Returning and handling errors

If you wish to return an error to the caller of a command, RunE can be used.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
package cmd

import (
"fmt"

"github.com/spf13/cobra"
)

func init() {
rootCmd.AddCommand(tryCmd)
}

var tryCmd = &cobra.Command{
Use: "try",
Short: "Try and possibly fail at something",
RunE: func(cmd *cobra.Command, args []string) error {
if err := someFunc(); err != nil {
return err
}
return nil
},
}

The error can then be caught at the execute function call.

References

[1] GitHub - spf13/cobra: A Commander for modern Go CLI interactions - https://github.com/spf13/cobra