Skip to main content

Cobra

Cobra is a CLI framework for Go. It contains a library for creating powerful modern CLI applications and a tool to rapidly generate Cobra based applications and command files.

install cobra cli
go get -u github.com/spf13/cobra/cobra

how to use?

inject cobra into existing project
cobra init
add new command
cobra add <commandName>
# command will be created in cmd directory with <commandName>

Structure & Concepts

Command - it is a handler which implement you logic which should be executed.

Flag - it is options like --name, etc... Flag can be defined in command scope or globally.

main.go
package main

import "pro.ganyushkin.archlab.core-cli/cmd"

func main() {
cmd.Execute()
}
root commant in cmd/root.go
package cmd

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

var rootCmd = &cobra.Command{
Use: "arch-lab",
Short: "Arch Lab Cli tool",
Long: `Manage arch staff with arch-lab`,
}

func Execute() {
err := rootCmd.Execute()
if err != nil {
os.Exit(1)
}
}
command cmd/mycommand.go
package cmd

import (
"github.com/spf13/cobra"
"log/slog"
)

var MyCommandCmd = &cobra.Command{
Use: "mycommand",
Short: "Say hello",
Long: `Test command`,
Run: handler,
}

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

func handler(cmd *cobra.Command, args []string) {
...
}

Flags

Options like --name, etc...

add flog for command
helloworldCmd.Flags().String("flag name", "default value", "description")
read flag
homeDir, err := cmd.Flags().GetString("flag name")

Global flags

Flag can be defined for whole application, in root scope and can be provided and read in all commands.

add global flog, for all commands scope
helloworldCmd.PersistentFlags().String("flag name", "default value", "description")
read global/persistent flag
# same as for command flag
homeDir, err := cmd.Flags().GetString("flag name")

Version

add version cmd.SetVersionTemplate(s string)

and use # your-app --version

cobra.dev
Создание CLI утилит на Go с библиотекой Cobra