cobra

package module
v1.10.2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 3, 2025 License: Apache-2.0 Imports: 17 Imported by: 195,884

README

Cobra is a library for creating powerful modern CLI applications.

Visit Cobra.dev for extensive documentation

Cobra is used in many Go projects such as Kubernetes, Hugo, and GitHub CLI to name a few. This list contains a more extensive list of projects using Cobra.

Go Reference Go Report Card Slack



Overview

Cobra is a library providing a simple interface to create powerful modern CLI interfaces similar to git & go tools.

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
  • Intelligent suggestions (app srver... did you mean app server?)
  • Automatic help generation for commands and flags
  • Grouping help for subcommands
  • 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 seamless 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:

hugo server --port=1313

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

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

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. 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, a fork of the flag standard library which maintains the same interface while adding POSIX compliance.

Installing

Using Cobra is easy. First, use go get to install the latest version of the library.

go get -u github.com/spf13/cobra@latest

Next, include Cobra in your application:

import "github.com/spf13/cobra"

Usage

cobra-cli is a command line program to generate cobra applications and command files. It will bootstrap your application scaffolding to rapidly develop a Cobra-based application. It is the easiest way to incorporate Cobra into your application.

It can be installed by running:

go install github.com/spf13/cobra-cli@latest

For complete details on using the Cobra-CLI generator, please read The Cobra Generator README

For complete details on using the Cobra library, please read The Cobra User Guide.

License

Cobra is released under the Apache 2.0 license. See LICENSE.txt

Documentation

Overview

Package cobra is a commander providing a simple interface to create powerful modern CLI interfaces. In addition to providing an interface, Cobra simultaneously provides a controller to organize your application code.

Index

Constants

View Source
const (
	BashCompFilenameExt     = "cobra_annotation_bash_completion_filename_extensions"
	BashCompCustom          = "cobra_annotation_bash_completion_custom"
	BashCompOneRequiredFlag = "cobra_annotation_bash_completion_one_required_flag"
	BashCompSubdirsInDir    = "cobra_annotation_bash_completion_subdirs_in_dir"
)

Annotations for Bash completion.

View Source
const (
	FlagSetByCobraAnnotation     = "cobra_annotation_flag_set_by_cobra"
	CommandDisplayNameAnnotation = "cobra_annotation_command_display_name"
)
View Source
const (
	// ShellCompRequestCmd is the name of the hidden command that is used to request
	// completion results from the program.  It is used by the shell completion scripts.
	ShellCompRequestCmd = "__complete"
	// ShellCompNoDescRequestCmd is the name of the hidden command that is used to request
	// completion results without their description.  It is used by the shell completion scripts.
	ShellCompNoDescRequestCmd = "__completeNoDesc"
)

Variables

View Source
var EnableCaseInsensitive = defaultCaseInsensitive

EnableCaseInsensitive allows case-insensitive commands names. (case sensitive by default)

View Source
var EnableCommandSorting = defaultCommandSorting

EnableCommandSorting controls sorting of the slice of commands, which is turned on by default. To disable sorting, set it to false.

View Source
var EnablePrefixMatching = defaultPrefixMatching

EnablePrefixMatching allows setting automatic prefix matching. Automatic prefix matching can be a dangerous thing to automatically enable in CLI tools. Set this to true to enable it.

View Source
var EnableTraverseRunHooks = defaultTraverseRunHooks

EnableTraverseRunHooks executes persistent pre-run and post-run hooks from all parents. By default this is disabled, which means only the first run hook to be found is executed.

View Source
var MousetrapDisplayDuration = 5 * time.Second

MousetrapDisplayDuration controls how long the MousetrapHelpText message is displayed on Windows if the CLI is started from explorer.exe. Set to 0 to wait for the return key to be pressed. To disable the mousetrap, just set MousetrapHelpText to blank string (""). Works only on Microsoft Windows.

View Source
var MousetrapHelpText = `This is a command line tool.

You need to open cmd.exe and run it from there.
`

MousetrapHelpText enables an information splash screen on Windows if the CLI is started from explorer.exe. To disable the mousetrap, just set this variable to blank string (""). Works only on Microsoft Windows.

Functions

func AddTemplateFunc

func AddTemplateFunc(name string, tmplFunc interface{})

AddTemplateFunc adds a template function that's available to Usage and Help template generation.

func AddTemplateFuncs

func AddTemplateFuncs(tmplFuncs template.FuncMap)

AddTemplateFuncs adds multiple template functions that are available to Usage and Help template generation.

func ArbitraryArgs

func ArbitraryArgs(cmd *Command, args []string) error

ArbitraryArgs never returns an error.

func CheckErr added in v1.1.2

func CheckErr(msg interface{})

CheckErr prints the msg with the prefix 'Error:' and exits with error code 1. If the msg is nil, it does nothing.

func CompDebug added in v1.0.0

func CompDebug(msg string, printToStdErr bool)

CompDebug prints the specified string to the same file as where the completion script prints its logs. Note that completion printouts should never be on stdout as they would be wrongly interpreted as actual completion choices by the completion script.

func CompDebugln added in v1.0.0

func CompDebugln(msg string, printToStdErr bool)

CompDebugln prints the specified string with a newline at the end to the same file as where the completion script prints its logs. Such logs are only printed when the user has set the environment variable BASH_COMP_DEBUG_FILE to the path of some file to be used.

func CompError added in v1.0.0

func CompError(msg string)

CompError prints the specified completion message to stderr.

func CompErrorln added in v1.0.0

func CompErrorln(msg string)

CompErrorln prints the specified completion message to stderr with a newline at the end.

func Eq

func Eq(a interface{}, b interface{}) bool

Eq takes two types and checks whether they are equal. Supported types are int and string. Unsupported types will panic.

func GetActiveHelpConfig added in v1.5.0

func GetActiveHelpConfig(cmd *Command) string

GetActiveHelpConfig returns the value of the ActiveHelp environment variable <PROGRAM>_ACTIVE_HELP where <PROGRAM> is the name of the root command in upper case, with all non-ASCII-alphanumeric characters replaced by `_`. It will always return "0" if the global environment variable COBRA_ACTIVE_HELP is set to "0".

func Gt

func Gt(a interface{}, b interface{}) bool

Gt takes two types and checks whether the first type is greater than the second. In case of types Arrays, Chans, Maps and Slices, Gt will compare their lengths. Ints are compared directly while strings are first parsed as ints and then compared.

func MarkFlagCustom

func MarkFlagCustom(flags *pflag.FlagSet, name string, f string) error

MarkFlagCustom adds the BashCompCustom annotation to the named flag, if it exists. The bash completion script will call the bash function f for the flag.

This will only work for bash completion. It is recommended to instead use c.RegisterFlagCompletionFunc(...) which allows to register a Go function which will work across all shells.

func MarkFlagDirname added in v0.0.5

func MarkFlagDirname(flags *pflag.FlagSet, name string) error

MarkFlagDirname instructs the various shell completion implementations to limit completions for the named flag to directory names.

func MarkFlagFilename

func MarkFlagFilename(flags *pflag.FlagSet, name string, extensions ...string) error

MarkFlagFilename instructs the various shell completion implementations to limit completions for the named flag to the specified file extensions.

func MarkFlagRequired

func MarkFlagRequired(flags *pflag.FlagSet, name string) error

MarkFlagRequired instructs the various shell completion implementations to prioritize the named flag when performing completion, and causes your command to report an error if invoked without the flag.

func NoArgs