This page looks best with JavaScript enabled

cobra

 ·  ☕ 3 min read

cobra package

cobra is command line tool that can be used to build command line tools!

installation

Get cobra installed
go get -u github.com/spf13/cobra/cobra

usage

cobra init

creating a new CLI application is as easy as running cobra init

cobra init --pkg-name github.com/gophersumit/mycli

This should create new cli application:

main.go

1
2
3
4
5
6
7
package main

import "github.com/gophersumit/mycli/cmd"

func main() {
cmd.Execute()
}

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
package cmd

import (
"fmt"
"os"
"github.com/spf13/cobra"

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

)


var cfgFile string


// rootCmd represents the base command when called without any subcommands
var rootCmd = &cobra.Command{
Use:   "mycli",
Short: "A brief description of your application",
Long: `A longer description that spans multiple lines and likely contains
examples and usage of using your application. For example:

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.`,
}

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

func init() {
cobra.OnInitialize(initConfig)
rootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.mycli.yaml)")
rootCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle")
}

func initConfig() {
if cfgFile != "" {
  viper.SetConfigFile(cfgFile)
} else {
  home, err := homedir.Dir()
  if err != nil {
    fmt.Println(err)
    os.Exit(1)
  }

  viper.AddConfigPath(home)
  viper.SetConfigName(".mycli")
}

viper.AutomaticEnv() // read in environment variables that match

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

build and run the application

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
$ go mod init github.com/gophersumit/mycli
  go: creating new go.mod: module github.com/gophersumit/mycli

$ go build .

$ ./mycli 
  A longer description that spans multiple lines and likely contains
  examples and usage of using your application. For example:

  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.

We have created full fledged cli app using just few commands.

cobra add

cobra supports addition of sub commands using add.
To add a new sub-command, use cobra add <sub command name>

1
$ cobra add generate

Following sub command will be created.

 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
package cmd

import (
	"fmt"

	"github.com/spf13/cobra"
)

// generateCmd represents the generate command
var generateCmd = &cobra.Command{
	Use:   "generate",
	Short: "A brief description of your command",
	Long: `A longer description that spans multiple lines and likely contains examples
and usage of using your command. For example:

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.`,
	Run: func(cmd *cobra.Command, args []string) {
		fmt.Println("generate called")
	},
}

func init() {
	rootCmd.AddCommand(generateCmd)

}

package source and documentation

https://pkg.go.dev/github.com/spf13/cobra?tab=doc


Sumit
WRITTEN BY
Sumit
Gopher


What's on this Page