Categorygithub.com/spf13/cobra
modulepackage
1.9.1
Repository: https://github.com/spf13/cobra.git
Documentation: pkg.go.dev

# README

cobra logo

Cobra is a library for creating powerful modern CLI applications.

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

# Packages

# Functions

AddTemplateFunc adds a template function that's available to Usage and Help template generation.
AddTemplateFuncs adds multiple template functions that are available to Usage and Help template generation.
AppendActiveHelp adds the specified string to the specified array to be used as ActiveHelp.
ArbitraryArgs never returns an error.
CheckErr prints the msg with the prefix 'Error:' and exits with error code 1.
CompDebug prints the specified string to the same file as where the completion script prints its logs.
CompDebugln prints the specified string with a newline at the end to the same file as where the completion script prints its logs.
CompError prints the specified completion message to stderr.
CompErrorln prints the specified completion message to stderr with a newline at the end.
CompletionWithDesc returns a [Completion] with a description by using the TAB delimited format.
Eq takes two types and checks whether they are equal.
ExactArgs returns an error if there are not exactly n args.
ExactValidArgs returns an error if there are not exactly N positional args OR there are any positional args that are not in the `ValidArgs` field of `Command` Deprecated: use MatchAll(ExactArgs(n), OnlyValidArgs) instead.
FixedCompletions can be used to create a completion function which always returns the same results.
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 `_`.
Gt takes two types and checks whether the first type is greater than the second.
MarkFlagCustom adds the BashCompCustom annotation to the named flag, if it exists.
MarkFlagDirname instructs the various shell completion implementations to limit completions for the named flag to directory names.
MarkFlagFilename instructs the various shell completion implementations to limit completions for the named flag to the specified file extensions.
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.
MatchAll allows combining several PositionalArgs to work in concert.
MaximumNArgs returns an error if there are more than N args.
MinimumNArgs returns an error if there is not at least N args.
NoArgs returns an error if any args are included.
NoFileCompletions can be used to disable file completion for commands that should not trigger file completions.
OnFinalize sets the passed functions to be run when each command's Execute method is terminated.
OnInitialize sets the passed functions to be run when each command's Execute method is called.
OnlyValidArgs returns an error if there are any positional args that are not in the `ValidArgs` field of `Command`.
RangeArgs returns an error if the number of args is not within the expected range.
WriteStringAndCheck writes a string into a buffer, and checks if the error is not nil.

# Constants

Annotations for Bash completion.
Annotations for Bash completion.
Annotations for Bash completion.
Annotations for Bash completion.
ShellCompDirectiveDefault indicates to let the shell perform its default behavior after completions have been provided.
ShellCompDirectiveError indicates an error occurred and completions should be ignored.
ShellCompDirectiveFilterDirs indicates that only directory names should be provided in file completion.
ShellCompDirectiveFilterFileExt indicates that the provided completions should be used as file extension filters.
ShellCompDirectiveKeepOrder indicates that the shell should preserve the order in which the completions are provided.
ShellCompDirectiveNoFileComp indicates that the shell should not provide file completion even when no completion is provided.
ShellCompDirectiveNoSpace indicates that the shell should not add a space after the completion even if there is a single completion provided.
ShellCompNoDescRequestCmd is the name of the hidden command that is used to request completion results without their description.
ShellCompRequestCmd is the name of the hidden command that is used to request completion results from the program.

# Variables

EnableCaseInsensitive allows case-insensitive commands names.
EnableCommandSorting controls sorting of the slice of commands, which is turned on by default.
EnablePrefixMatching allows setting automatic prefix matching.
EnableTraverseRunHooks executes persistent pre-run and post-run hooks from all parents.
MousetrapDisplayDuration controls how long the MousetrapHelpText message is displayed on Windows if the CLI is started from explorer.exe.
MousetrapHelpText enables an information splash screen on Windows if the CLI is started from explorer.exe.

# Structs

Command is just that, a command for your application.
CompletionOptions are the options to control shell completion.
Group Structure to manage groups for commands.

# Interfaces

SliceValue is a reduced version of [pflag.SliceValue].

# Type aliases

Completion is a string that can be used for completions two formats are supported: - the completion choice - the completion choice with a textual description (separated by a TAB).
CompletionFunc is a function that provides completion results.
FParseErrWhitelist configures Flag parse errors to be ignored.
ShellCompDirective is a bit map representing the different behaviors the shell can be instructed to have once completions have been provided.