Cobra Walkthrough Guide

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

Install

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

Walkthrough Guide

Configuring the cobra generator by ~/.cobra.yaml

It's a good idea to configure Cobra first before generating any commands as this configuration would be refered by the corba tool.

cat > ~/.cobra.yaml <<EOF
author: Bright Zheng <myemail@company.com>
license: AGPL
EOF

In this case, the licensing info will be attached in each file generated by cobra:

/*
Copyright © 2021 Bright Zheng <myemail@company.com>

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU Affero General Public License for more details.

You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/

corbra init - Initialize Cobra project

$ mkdir corbra-app && cd corbra-app

$ go mod init github.com/brightzheng100/corbra-app
$ go mod tidy

$ cobra init --pkg-name github.com/brightzheng100/corbra-app
Using config file: /Users/brightzheng/.cobra.yaml
Your Cobra applicaton is ready at
/Users/brightzheng/development/go/exercises/corbra-app

$ tree .
.
├── LICENSE
├── cmd
│   └── root.go
└── main.go

1 directory, 3 files

corbra add - Add Sub Commands

Assuming we're going to have below commands in our app:

  • app serve

  • app config

  • app config create

$ cobra add serve
$ cobra add config
$ cobra add create -p 'configCmd' # `create` is a sub command of `config` named `configCmd` 

$ tree .
.
├── LICENSE
├── cmd
│   ├── config.go
│   ├── create.go
│   ├── root.go
│   └── serve.go
└── main.go

Try it out

$ go run main.go
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.

Usage:
  corbra-app [command]

Available Commands:
  config      A brief description of your command
  help        Help about any command
  serve       A brief description of your command

Flags:
      --config string   config file (default is $HOME/.corbra-app.yaml)
  -h, --help            help for corbra-app
  -t, --toggle          Help message for toggle

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

$ go run main.go serve
serve called
$ go run main.go config
config called
$ go run main.go config create
create called

References:

Last updated