A Commander for modern Go CLI interactions

cobra logo

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

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.

Build Status GoDoc Go Report Card Slack

Table of Contents

Overview

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

Cobra is also an application that will generate your application scaffolding to rapidly develop a Cobra-based application.

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
  • Easy generation of applications & commands with cobra init appname & cobra add cmdname
  • Intelligent suggestions (app srver... did you mean app server?)
  • Automatic help generation for commands and flags
  • 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 tight 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. This command will install the cobra generator executable along with the library and its dependencies:

go get -u github.com/spf13/cobra

Next, include Cobra in your application:

import "github.com/spf13/cobra"

Getting Started

While you are welcome to provide your own organization, typically a Cobra-based application will follow the following organizational structure:

  ▾ appName/
    ▾ cmd/
        add.go
        your.go
        commands.go
        here.go
      main.go

In a Cobra app, typically the main.go file is very bare. It serves one purpose: initializing Cobra.

package main

import (
  "{pathToYourApp}/cmd"
)

func main() {
  cmd.Execute()
}

Using the Cobra Generator

Cobra provides its own program that will create your application and add any commands you want. It's the easiest way to incorporate Cobra into your application.

Here you can find more information about it.

Using the Cobra Library

To manually implement Cobra you need to create a bare main.go file and a rootCmd file. You will optionally provide additional commands as you see fit.

Create rootCmd

Cobra doesn't require any special constructors. Simply create your commands.

Ideally you place this in app/cmd/root.go:

var rootCmd = &cobra.Command{
  Use:   "hugo",
  Short: "Hugo is a very fast static site generator",
  Long: `A Fast and Flexible Static Site Generator built with
                love by spf13 and friends in Go.
                Complete documentation is available at http://hugo.spf13.com`,
  Run: func(cmd *cobra.Command, args []string) {
    // Do Stuff Here
  },
}

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

You will additionally define flags and handle configuration in your init() function.

For example cmd/root.go:

package cmd

import (
	"fmt"
	"os"

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

var (
	// Used for flags.
	cfgFile     string
	userLicense string

	rootCmd = &cobra.Command{
		Use:   "cobra",
		Short: "A generator for Cobra based Applications",
		Long: `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.`,
	}
)

// Execute executes the root command.
func Execute() error {
	return rootCmd.Execute()
}

func init() {
	cobra.OnInitialize(initConfig)

	rootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.cobra.yaml)")
	rootCmd.PersistentFlags().StringP("author", "a", "YOUR NAME", "author name for copyright attribution")
	rootCmd.PersistentFlags().StringVarP(&userLicense, "license", "l", "", "name of license for the project")
	rootCmd.PersistentFlags().Bool("viper", true, "use Viper for configuration")
	viper.BindPFlag("author", rootCmd.PersistentFlags().Lookup("author"))
	viper.BindPFlag("useViper", rootCmd.PersistentFlags().Lookup("viper"))
	viper.SetDefault("author", "NAME HERE <EMAIL ADDRESS>")
	viper.SetDefault("license", "apache")

	rootCmd.AddCommand(addCmd)
	rootCmd.AddCommand(initCmd)
}

func er(msg interface{}) {
	fmt.Println("Error:", msg)
	os.Exit(1)
}

func initConfig() {
	if cfgFile != "" {
		// Use config file from the flag.
		viper.SetConfigFile(cfgFile)
	} else {
		// Find home directory.
		home, err := homedir.Dir()
		if err != nil {
			er(err)
		}

		// Search config in home directory with name ".cobra" (without extension).
		viper.AddConfigPath(home)
		viper.SetConfigName(".cobra")
	}

	viper.AutomaticEnv()

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

Create your main.go

With the root command you need to have your main function execute it. Execute should be run on the root for clarity, though it can be called on any command.

In a Cobra app, typically the main.go file is very bare. It serves one purpose: to initialize Cobra.

package main

import (
  "{pathToYourApp}/cmd"
)

func main() {
  cmd.Execute()
}

Create additional commands

Additional commands can be defined and typically are each given their own file inside of the cmd/ directory.

If you wanted to create a version command you would create cmd/version.go and populate it with the following:

package cmd

import (
  "fmt"

  "github.com/spf13/cobra"
)

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

var versionCmd = &cobra.Command{
  Use:   "version",
  Short: "Print the version number of Hugo",
  Long:  `All software has versions. This is Hugo's`,
  Run: func(cmd *cobra.Command, args []string) {
    fmt.Println("Hugo Static Site Generator v0.9 -- HEAD")
  },
}

Returning and handling errors

If you wish to return an error to the caller of a command, RunE can be used.

package cmd

import (
  "fmt"

  "github.com/spf13/cobra"
)

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

var tryCmd = &cobra.Command{
  Use:   "try",
  Short: "Try and possibly fail at something",
  RunE: func(cmd *cobra.Command, args []string) error {
    if err := someFunc(); err != nil {
	return err
    }
    return nil
  },
}

The error can then be caught at the execute function call.

Working with Flags

Flags provide modifiers to control how the action command operates.

Assign flags to a command

Since the flags are defined and used in different locations, we need to define a variable outside with the correct scope to assign the flag to work with.

var Verbose bool
var Source string

There are two different approaches to assign a flag.

Persistent Flags

A flag can be 'persistent', meaning that this flag will be available to the command it's assigned to as well as every command under that command. For global flags, assign a flag as a persistent flag on the root.

rootCmd.PersistentFlags().BoolVarP(&Verbose, "verbose", "v", false, "verbose output")

Local Flags

A flag can also be assigned locally, which will only apply to that specific command.

localCmd.Flags().StringVarP(&Source, "source", "s", "", "Source directory to read from")

Local Flag on Parent Commands

By default, Cobra only parses local flags on the target command, and any local flags on parent commands are ignored. By enabling Command.TraverseChildren, Cobra will parse local flags on each command before executing the target command.

command := cobra.Command{
  Use: "print [OPTIONS] [COMMANDS]",
  TraverseChildren: true,
}

Bind Flags with Config

You can also bind your flags with viper:

var author string

func init() {
  rootCmd.PersistentFlags().StringVar(&author, "author", "YOUR NAME", "Author name for copyright attribution")
  viper.BindPFlag("author", rootCmd.PersistentFlags().Lookup("author"))
}

In this example, the persistent flag author is bound with viper. Note: the variable author will not be set to the value from config, when the --author flag is not provided by user.

More in viper documentation.

Required flags

Flags are optional by default. If instead you wish your command to report an error when a flag has not been set, mark it as required:

rootCmd.Flags().StringVarP(&Region, "region", "r", "", "AWS region (required)")
rootCmd.MarkFlagRequired("region")

Or, for persistent flags:

rootCmd.PersistentFlags().StringVarP(&Region, "region", "r", "", "AWS region (required)")
rootCmd.MarkPersistentFlagRequired("region")

Positional and Custom Arguments

Validation of positional arguments can be specified using the Args field of Command.

The following validators are built in:

  • NoArgs - the command will report an error if there are any positional args.
  • ArbitraryArgs - the command will accept any args.
  • OnlyValidArgs - the command will report an error if there are any positional args that are not in the ValidArgs field of Command.
  • MinimumNArgs(int) - the command will report an error if there are not at least N positional args.
  • MaximumNArgs(int) - the command will report an error if there are more than N positional args.
  • ExactArgs(int) - the command will report an error if there are not exactly N positional args.
  • ExactValidArgs(int) - the command will report an error if there are not exactly N positional args OR if there are any positional args that are not in the ValidArgs field of Command
  • RangeArgs(min, max) - the command will report an error if the number of args is not between the minimum and maximum number of expected args.

An example of setting the custom validator:

var cmd = &cobra.Command{
  Short: "hello",
  Args: func(cmd *cobra.Command, args []string) error {
    if len(args) < 1 {
      return errors.New("requires a color argument")
    }
    if myapp.IsValidColor(args[0]) {
      return nil
    }
    return fmt.Errorf("invalid color specified: %s", args[0])
  },
  Run: func(cmd *cobra.Command, args []string) {
    fmt.Println("Hello, World!")
  },
}

Example

In the example below, we have defined three commands. Two are at the top level and one (cmdTimes) is a child of one of the top commands. In this case the root is not executable, meaning that a subcommand is required. This is accomplished by not providing a 'Run' for the 'rootCmd'.

We have only defined one flag for a single command.

More documentation about flags is available at https://github.com/spf13/pflag

package main

import (
  "fmt"
  "strings"

  "github.com/spf13/cobra"
)

func main() {
  var echoTimes int

  var cmdPrint = &cobra.Command{
    Use:   "print [string to print]",
    Short: "Print anything to the screen",
    Long: `print is for printing anything back to the screen.
For many years people have printed back to the screen.`,
    Args: cobra.MinimumNArgs(1),
    Run: func(cmd *cobra.Command, args []string) {
      fmt.Println("Print: " + strings.Join(args, " "))
    },
  }

  var cmdEcho = &cobra.Command{
    Use:   "echo [string to echo]",
    Short: "Echo anything to the screen",
    Long: `echo is for echoing anything back.
Echo works a lot like print, except it has a child command.`,
    Args: cobra.MinimumNArgs(1),
    Run: func(cmd *cobra.Command, args []string) {
      fmt.Println("Echo: " + strings.Join(args, " "))
    },
  }

  var cmdTimes = &cobra.Command{
    Use:   "times [string to echo]",
    Short: "Echo anything to the screen more times",
    Long: `echo things multiple times back to the user by providing
a count and a string.`,
    Args: cobra.MinimumNArgs(1),
    Run: func(cmd *cobra.Command, args []string) {
      for i := 0; i < echoTimes; i++ {
        fmt.Println("Echo: " + strings.Join(args, " "))
      }
    },
  }

  cmdTimes.Flags().IntVarP(&echoTimes, "times", "t", 1, "times to echo the input")

  var rootCmd = &cobra.Command{Use: "app"}
  rootCmd.AddCommand(cmdPrint, cmdEcho)
  cmdEcho.AddCommand(cmdTimes)
  rootCmd.Execute()
}

For a more complete example of a larger application, please checkout Hugo.

Help Command

Cobra automatically adds a help command to your application when you have subcommands. This will be called when a user runs 'app help'. Additionally, help will also support all other commands as input. Say, for instance, you have a command called 'create' without any additional configuration; Cobra will work when 'app help create' is called. Every command will automatically have the '--help' flag added.

Example

The following output is automatically generated by Cobra. Nothing beyond the command and flag definitions are needed.

$ cobra help

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:
  cobra [command]

Available Commands:
  add         Add a command to a Cobra Application
  help        Help about any command
  init        Initialize a Cobra Application

Flags:
  -a, --author string    author name for copyright attribution (default "YOUR NAME")
      --config string    config file (default is $HOME/.cobra.yaml)
  -h, --help             help for cobra
  -l, --license string   name of license for the project
      --viper            use Viper for configuration (default true)

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

Help is just a command like any other. There is no special logic or behavior around it. In fact, you can provide your own if you want.

Defining your own help

You can provide your own Help command or your own template for the default command to use with following functions:

cmd.SetHelpCommand(cmd *Command)
cmd.SetHelpFunc(f func(*Command, []string))
cmd.SetHelpTemplate(s string)

The latter two will also apply to any children commands.

Usage Message

When the user provides an invalid flag or invalid command, Cobra responds by showing the user the 'usage'.

Example

You may recognize this from the help above. That's because the default help embeds the usage as part of its output.

$ cobra --invalid
Error: unknown flag: --invalid
Usage:
  cobra [command]

Available Commands:
  add         Add a command to a Cobra Application
  help        Help about any command
  init        Initialize a Cobra Application

Flags:
  -a, --author string    author name for copyright attribution (default "YOUR NAME")
      --config string    config file (default is $HOME/.cobra.yaml)
  -h, --help             help for cobra
  -l, --license string   name of license for the project
      --viper            use Viper for configuration (default true)

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

Defining your own usage

You can provide your own usage function or template for Cobra to use. Like help, the function and template are overridable through public methods:

cmd.SetUsageFunc(f func(*Command) error)
cmd.SetUsageTemplate(s string)

Version Flag

Cobra adds a top-level '--version' flag if the Version field is set on the root command. Running an application with the '--version' flag will print the version to stdout using the version template. The template can be customized using the cmd.SetVersionTemplate(s string) function.

PreRun and PostRun Hooks

It is possible to run functions before or after the main Run function of your command. The PersistentPreRun and PreRun functions will be executed before Run. PersistentPostRun and PostRun will be executed after Run. The Persistent*Run functions will be inherited by children if they do not declare their own. These functions are run in the following order:

  • PersistentPreRun
  • PreRun
  • Run
  • PostRun
  • PersistentPostRun

An example of two commands which use all of these features is below. When the subcommand is executed, it will run the root command's PersistentPreRun but not the root command's PersistentPostRun:

package main

import (
  "fmt"

  "github.com/spf13/cobra"
)

func main() {

  var rootCmd = &cobra.Command{
    Use:   "root [sub]",
    Short: "My root command",
    PersistentPreRun: func(cmd *cobra.Command, args []string) {
      fmt.Printf("Inside rootCmd PersistentPreRun with args: %v\n", args)
    },
    PreRun: func(cmd *cobra.Command, args []string) {
      fmt.Printf("Inside rootCmd PreRun with args: %v\n", args)
    },
    Run: func(cmd *cobra.Command, args []string) {
      fmt.Printf("Inside rootCmd Run with args: %v\n", args)
    },
    PostRun: func(cmd *cobra.Command, args []string) {
      fmt.Printf("Inside rootCmd PostRun with args: %v\n", args)
    },
    PersistentPostRun: func(cmd *cobra.Command, args []string) {
      fmt.Printf("Inside rootCmd PersistentPostRun with args: %v\n", args)
    },
  }

  var subCmd = &cobra.Command{
    Use:   "sub [no options!]",
    Short: "My subcommand",
    PreRun: func(cmd *cobra.Command, args []string) {
      fmt.Printf("Inside subCmd PreRun with args: %v\n", args)
    },
    Run: func(cmd *cobra.Command, args []string) {
      fmt.Printf("Inside subCmd Run with args: %v\n", args)
    },
    PostRun: func(cmd *cobra.Command, args []string) {
      fmt.Printf("Inside subCmd PostRun with args: %v\n", args)
    },
    PersistentPostRun: func(cmd *cobra.Command, args []string) {
      fmt.Printf("Inside subCmd PersistentPostRun with args: %v\n", args)
    },
  }

  rootCmd.AddCommand(subCmd)

  rootCmd.SetArgs([]string{""})
  rootCmd.Execute()
  fmt.Println()
  rootCmd.SetArgs([]string{"sub", "arg1", "arg2"})
  rootCmd.Execute()
}

Output:

Inside rootCmd PersistentPreRun with args: []
Inside rootCmd PreRun with args: []
Inside rootCmd Run with args: []
Inside rootCmd PostRun with args: []
Inside rootCmd PersistentPostRun with args: []

Inside rootCmd PersistentPreRun with args: [arg1 arg2]
Inside subCmd PreRun with args: [arg1 arg2]
Inside subCmd Run with args: [arg1 arg2]
Inside subCmd PostRun with args: [arg1 arg2]
Inside subCmd PersistentPostRun with args: [arg1 arg2]

Suggestions when "unknown command" happens

Cobra will print automatic suggestions when "unknown command" errors happen. This allows Cobra to behave similarly to the git command when a typo happens. For example:

$ hugo srever
Error: unknown command "srever" for "hugo"

Did you mean this?
        server

Run 'hugo --help' for usage.

Suggestions are automatic based on every subcommand registered and use an implementation of Levenshtein distance. Every registered command that matches a minimum distance of 2 (ignoring case) will be displayed as a suggestion.

If you need to disable suggestions or tweak the string distance in your command, use:

command.DisableSuggestions = true

or

command.SuggestionsMinimumDistance = 1

You can also explicitly set names for which a given command will be suggested using the SuggestFor attribute. This allows suggestions for strings that are not close in terms of string distance, but makes sense in your set of commands and for some which you don't want aliases. Example:

$ kubectl remove
Error: unknown command "remove" for "kubectl"

Did you mean this?
        delete

Run 'kubectl help' for usage.

Generating documentation for your command

Cobra can generate documentation based on subcommands, flags, etc. Read more about it in the docs generation documentation.

Generating shell completions

Cobra can generate a shell-completion file for the following shells: Bash, Zsh, Fish, Powershell. If you add more information to your commands, these completions can be amazingly powerful and flexible. Read more about it in Shell Completions.

License

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

Owner
Steve Francia
@golang product lead at @google • Author, Speaker, Developer • Creator of @gohugoio, Cobra, Viper & spf13-vim • former @docker & @mongodb
Steve Francia
Comments
  • Zsh completion V2

    Zsh completion V2

    This is a new implementation of Zsh completion but based on the Custom Go Completions of PRs #1035 and #1048.

    The current Zsh completion has a major limitation in the fact that it does not support custom completions. Furthermore, if it ever did, it would require the program using Cobra to implement a second, zsh-flavoured version of its bash completion code.

    This v2 version allows to automatically re-use custom completions once they have been migrated to the Custom Go Completion solution of PR #1035.

    Advantages:

    • support custom completions (in Go only) (as mentioned above)
    • proper support for using = for flags
    • fixed size completion script of around 100 lines, so very fast on shell startup
    • allows disabling of descriptions (to feel like bash)
    • when there are no other completions, provides file completion automatically. This can be turned off on a per command basis
  • Zsh Completion

    Zsh Completion

    I improved the existing zsh completion with support for flags and some of the custom completion commands from bash completion. A description of what's supported could be found i the zsh completion readme. Thanks to everyone in the #107 thread for their help, especially to @eparis for explaining things to me over and over again ...

    One important note is that I only tested it on a small project on my laptop. It needs to be tested on a larger project and more important on other people's shell configurations to make sure it works correctly.

  • Allow consuming cobra as a library without picking up viper dependencies

    Allow consuming cobra as a library without picking up viper dependencies

    Status

    1. https://github.com/spf13/cobra-cli has been created with an extracted copy of github.com/spf13/cobra/cobra/...
    2. https://github.com/spf13/cobra-cli/pull/1 renamed the command to cobra-cli
    3. https://github.com/spf13/cobra-cli/releases/tag/v1.3.0, matching github.com/spf13/cobra v1.3.0 (except for the binary name)
    4. PRs to update public references to cobra/cobra in go imports and scripted references
      • go imports
        • https://github.com/kubeapps/kubeapps/pull/4373
        • https://github.com/certusone/wormhole/pull/936
        • https://github.com/allaboutapps/go-starter/pull/169
        • https://github.com/shihanng/gig/pull/56
      • scripted installs
        • https://github.com/codeedu/imersao-fullstack-fullcycle/issues/7
        • https://github.com/blacktop/ipsw/pull/86
        • https://github.com/codeedu/imersao-fullcycle-3/issues/3
        • https://github.com/GoogleCloudPlatform/kafka-pubsub-emulator/pull/40
        • https://github.com/ezbuy/tgen/pull/74
        • https://github.com/blacktop/graboid/pull/12
        • https://github.com/ahmetb/dotfiles/pull/2
        • https://github.com/cisco-sso/kdk/pull/218
        • https://github.com/codeedu/fc2-arquitetura-hexagonal/pull/4
        • https://github.com/awslabs/tecli/pull/14
      • doc references
        • https://github.com/SimonWaldherr/golang-examples/pull/63
        • https://github.com/Kevin-fqh/learning-k8s-source-code/issues/4
        • https://github.com/G-Research/armada/pull/888
    5. Remove CLI from this repo and update this repo's readme:
      • https://github.com/spf13/cobra/pull/1604

    (original description follows)

    First, many thanks for such a useful command library. The widespread adoption demonstrates how useful it is. A consequence of being very popular is that any dependencies of this module are picked up as transitive dependencies by a lot of consumers. The github.com/spf13/viper dependency of the cobra command line tool is particularly problematic, as it pulls in large numbers of large dependencies.

    It would greatly help downstream consumers if this library could be consumed without picking up the viper dependencies.


    History

    Relevant existing issues:

    • https://github.com/spf13/cobra/issues/1138
    • https://github.com/spf13/cobra/issues/1435#issuecomment-873073440
    • https://github.com/spf13/cobra/issues/1240

    There was a prior attempt at isolating the CLI command and viper dependency via a submodule:

    • https://github.com/spf13/cobra/pull/1139

    That resulted in the following issues:

    • https://github.com/spf13/cobra/issues/1191
    • https://github.com/spf13/cobra/issues/1215
    • https://github.com/spf13/cobra/issues/1219

    There were a few problems with the previous attempt:

    • No new tag was created for github.com/spf13/cobra once the submodule was created, so the @latest version of both github.com/spf13/cobra and github.com/spf13/cobra/cobra provided the github.com/spf13/cobra/cobra import path. This caused the "ambiguous import" error
    • The submodule used a local filesystem replace ... => ../ directive, which would break go get github.com/spf13/cobra/cobra and go install github.com/spf13/cobra/cobra@latest

    Proposal

    2022-03-10 note: rather than the approach proposed here, the Cobra CLI was split to a separate repo at https://github.com/spf13/cobra-cli. See discussion starting at https://github.com/spf13/cobra/issues/1597#issuecomment-1033234802

    Possible solutions for reorganizing this library to isolate the viper dependency are discussed in https://github.com/spf13/cobra/issues/1240. I agree with @spf13 that we should avoid solutions that disrupt current consumers of the github.com/spf13/cobra import path.

    I think the previous attempt to create a dedicated module for the cobra command packages (github.com/spf13/cobra/cobra/...) was the right direction, and could resolve the problems with the previous attempt with two changes:

    1. Tag a github.com/spf13/cobra release after adding the sub go.mod so github.com/spf13/cobra@latest resolves to a version that does not provide the github.com/spf13/cobra/cobra package.
    2. Update github.com/spf13/cobra/cobra to refer to the tagged github.com/spf13/cobra release created in step 1 so that it works with go get and go install

    Testing

    To test this approach, I:

    1. cloned this repo to github.com/liggitt/cobra, and created tags at various points in cobra's history with the import paths renamed (v1.0.0, v1.1.3, and v1.3.0)
    2. created a go.mod file at github.com/liggitt/cobra/cobra, committed and tagged as github.com/liggitt/cobra v1.5.0 - https://github.com/liggitt/cobra/commit/0c686b5b3365985ca75ac55a39e05c14c8618113
    3. updated the go.mod file at github.com/liggitt/cobra/cobra to refer to github.com/liggitt/[email protected], committed and tagged github.com/liggitt/cobra/cobra cobra/v1.5.0 - https://github.com/liggitt/cobra/commit/458f3c50b2238b018cb63874a25aba8409d8736f

    Now, all of the following still work with no complaints about ambiguous import paths:

    go get:

    go get github.com/liggitt/cobra
    go get github.com/liggitt/[email protected]
    go get github.com/liggitt/[email protected]
    go get github.com/liggitt/cobra@latest
    go get -u github.com/liggitt/cobra
    go get -u github.com/liggitt/[email protected]
    go get -u github.com/liggitt/cobra@latest
    

    go install:

    go install github.com/liggitt/cobra/[email protected]
    go install github.com/liggitt/cobra/[email protected]
    go install github.com/liggitt/cobra/cobra@latest
    

    Impact on library consumers

    To see what the impact would be on downstream consumers of this library, I took Kubernetes' use as an example (test commits visible in https://github.com/liggitt/kubernetes/commits/cobra130):

    1. made copies of Kubernetes dependencies that refer to spf13/cobra@{v1.0.0,v1.1.3,v1.3.0}, and adjusted Kubernetes and the dependencies to use liggitt/cobra at the same versions
    2. updated Kubernetes to use liggitt/[email protected]
    3. saw a significant number of transitive dependencies drop out of our dependency graph:
      • cloud.google.com/go/firestore
      • github.com/DataDog/datadog-go
      • github.com/armon/go-metrics
      • github.com/armon/go-radix
      • github.com/bgentry/speakeasy
      • github.com/circonus-labs/circonus-gometrics
      • github.com/circonus-labs/circonusllhist
      • github.com/fatih/color
      • github.com/hashicorp/consul/api
      • github.com/hashicorp/consul/sdk
      • github.com/hashicorp/errwrap
      • github.com/hashicorp/go-cleanhttp
      • github.com/hashicorp/go-hclog
      • github.com/hashicorp/go-immutable-radix
      • github.com/hashicorp/go-msgpack
      • github.com/hashicorp/go-multierror
      • github.com/hashicorp/go-retryablehttp
      • github.com/hashicorp/go-rootcerts
      • github.com/hashicorp/go-sockaddr
      • github.com/hashicorp/go-syslog
      • github.com/hashicorp/go-uuid
      • github.com/hashicorp/golang-lru
      • github.com/hashicorp/hcl
      • github.com/hashicorp/logutils
      • github.com/hashicorp/mdns
      • github.com/hashicorp/memberlist
      • github.com/hashicorp/serf
      • github.com/magiconair/properties
      • github.com/mattn/go-colorable
      • github.com/mattn/go-isatty
      • github.com/miekg/dns
      • github.com/mitchellh/cli
      • github.com/mitchellh/go-homedir
      • github.com/mitchellh/go-testing-interface
      • github.com/pascaldekloe/goe
      • github.com/pelletier/go-toml
      • github.com/posener/complete
      • github.com/ryanuber/columnize
      • github.com/sagikazarmark/crypt
      • github.com/sean-/seed
      • github.com/spf13/cast
      • github.com/spf13/jwalterweatherman
      • github.com/spf13/viper
      • github.com/subosito/gotenv
      • github.com/tv42/httpunix
      • gopkg.in/ini.v1

    Impact on library consumers of github.com/spf13/cobra/cobra/...

    There don't appear to be very many consumers of these packages (which is not surprising, since their purpose is to support the cobra command line):

    • https://grep.app/search?q=%22github.com/spf13/cobra/cobra%22&filter[lang][0]=Go (4 public references in .go files)
    • https://grep.app/search?q=%22github.com/spf13/cobra/cobra/cmd%22 (0 public references outside of vendored copies of github.com/spf13/cobra)
    • https://grep.app/search?q=%22github.com/spf13/cobra/cobra/tpl%22 (0 public references outside of vendored copies of github.com/spf13/cobra)

    Any consumers using these packages beyond v1.3.0 would need to depend on the github.com/spf13/cobra/cobra module instead.


    Impact on development

    Changes that span the two modules would become more difficult to make, and could not be committed/pushed in a single PR. This is because the two modules are effectively behaving like two distinct modules that happen to live in the same repo, and a release of the library module would be required before the command module could start relying on the changes in it via a publicly referenced version.


    Impact on release mechanics

    Currently, to release github.com/spf13/cobra:

    1. create and push a v1.x.y git tag

    With multiple modules, effectively, two releases would be required (one for the library and one for the command), which would require two tags and a go.mod change:

    1. create and push a v1.x.y git tag
    2. update the github.com/spf13/cobra/cobra/go.mod file to reference that version of the github.com/spf13/cobra library, go mod tidy, commit and push
    3. create and push a cobra/v1.x.y git tag
  • Make sure we quote brackets when generating zsh completion

    Make sure we quote brackets when generating zsh completion

    zsh completion would fail when we have brackets in description, for example :

    % source   <(./tkn completion zsh)
    % tkn task list[TAB]
    _arguments:comparguments:319: invalid option definition: --template[Template string or path to template file to use when -o=go-template, -o=go-template-file. The template format is golang templates [http://golang.org/pkg/text/template/#pkg-overview].]:filename:_files
    
  • Support validation of positional arguments

    Support validation of positional arguments

    Fixes #42 Branched from #120

    Adds a new field Args that allows a user to define the expected positional arguments that a command should receive. If a command doesn't receive the expected args it returns an error.

    By accepting a validation function users can create their own custom validation for positional args. This PR includes validators for the most common cases.

  • Bash completion V2 with completion descriptions

    Bash completion V2 with completion descriptions

    With Cobra supporting shell completion for Bash, Zsh, Fish and Powershell, having a uniform experience across all shells is a desirable feature. With Fish (#1048) , Zsh (#1070) and PowerShell (#1208) sharing the same Go completion logic, their behaviour is strongly aligned.

    This PR uses the same Go completion code to power Bash completion.

    However, it is important to keep support for legacy bash completion for backwards-compatibility of existing bash custom completions (cmd.BashCompletionFunction and BashCompCustom) which are being used by many programs out there. ~Therefore this PR also adds support for legacy bash custom completion through Go completions (see more below).~ Therefore this PR introduces a V2 version of bash completion while retaining the current V1 support.

    Completion descriptions: The simplicity of the proposed bash completion script allowed to also add descriptions to bash completions.

    bash-5.0$ helm show [tab][tab]
    all     (show all information of the chart)  readme  (show the chart's README)
    chart   (show the chart's definition)        values  (show the chart's values)
    

    Descriptions are not actually supported natively in Bash, but I fell upon a Stack Overflow answer that suggested how it could be implemented by the script. With Fish, Zsh and PowerShell all supporting completion descriptions, I felt it would be a nice addition for Bash (can be disabled).

    ~Maintenance: Having a v2 version for bash completion while keeping v1 would impose that Cobra maintainers maintain both v1 and v2 versions. To reduce this maintenance burden, the PR completely replaces bash completion v1 with this new approach.~

    The current bash completion logic has been extremely useful to many projects over the last 5 years and has been an amazing initiative by @eparis and all maintainers and contributors that have worked on it. It has been the inspiration behind this proposed evolution.

    Backwards compatibility The PR retains backwards compatibility not only in compilation but in also honouring legacy bash custom completion.

    ~To do so, it introduces two new (internal) ShellCompDirective:shellCompDirectiveLegacyCustomComp and shellCompDirectiveLegacyCustomArgsComp which are used to tell the new bash completion script to perform legacy bash completion as was done before, when appropriate.~

    ~One complexity is that bash code inserted by the program using Cobra could technically reference any variable or function that was part of the previous bash completion script (e.g., two_word_flags, must_have_one_flag, etc). However, Iooking at kubectl, it seems that the $last_command and $nouns variables should be sufficient. Therefore, the new solution sets those two variables to allow the injected legacy custom bash code to use them.~

    ~I have tested this solution with kubectl and have confirmed that its legacy completion continues to work. However, there is still a risk of breaking some completions for some programs out there, if they use other variables or functions of the current bash script.~

    Here is what I feel are our options for backwards compatibility:

    1. Ignore this PR and keep bash completion as is
    2. Keep the current bash completion and introduce a V2 using custom Go completions
    3. Keep but deprecate the current bash completion and introduce a V2 using custom Go completions which also support legacy custom completions. This would give an easy migration path to programs to move to the V2 solution, while not even having to get rid of their legacy custom completion code. The current bash completion could then be removed in a 2.0 version of Cobra. (commits 1 and 2 of this PR)
    4. Replace the current bash completion with the new custom Go completions which also support legacy custom completions almost completely (commits 1, 2 and 3 of this PR)

    This PR implements option 2.

    Advantages of this new approach:

    1. Aligned behaviour across bash, zsh and fish
    2. ~Reduced maintenance~
    3. Fixes and improvements to completion support would automatically propagate to all four shells
    4. New support for completion descriptions for bash
    5. Fixed-size completion script of less than 300 lines (in comparaison the v1 script for kubectl is over 12,000 lines)
  • zsh autocompletion generator

    zsh autocompletion generator

    There are desires among users (see https://github.com/spf13/hugo/pull/1088) for an auto-completion generator for zsh, similar to what @eparis has made available for bash in his excellent work in #69.

    So, here is a reminder so perhaps someone could use @eparis's excellent work for bash as the basis for the same for zsh. :-)

  • Fall release 🍁 - 2021

    Fall release 🍁 - 2021

    ~Last release was planned for May 2021 and released in July. Next week, it will be 3 months since that. In this period, 3 PRs were merged.~

    ~Is there any plan for merging PRs and releasing a new version in the following weeks?~

    Release candidate (please try out and test!)

    • #1525

    To Do

    Approved by a maintainer but merge seems to have been forgotten:

    • #841

    Left pending in the previous release (#1388):

    • #1387

    Small completion fixes from the community:

    • #1467

    Worth considering:

    • #1530

    Some random cool ones:

    • #1231
    • #1003

    Done

    • #880
    • #896
    • #949
    • #979
    • #1009
    • #1159
    • #1161
    • #1321
    • #1372
    • #1426
    • #1427
    • #1429
    • #1444
    • #1454. Closes:
      • #987
      • #1371
      • #1377
      • #1380
      • #1407
      • #1446
      • #1451
      • #1497
      • #1506
      • #1522
      • #1528
    • #1455
    • #1459
    • #1463
    • #1473
    • #1477
    • #1509
    • #1510
    • #1514
    • #1520
    • #1541
    • #1552
    • #1557

    Delayed to a later release

    • #1500
  • Add ability to mark flags as required or exclusive as a group

    Add ability to mark flags as required or exclusive as a group

    This change adds two features for dealing with flags:

    • requiring flags be provided as a group (or not at all)
    • requiring flags be mutually exclusive of each other

    By utilizing the flag annotations we can mark which flag groups a flag is a part of and during the parsing process we track which ones we have seen or not.

    A flag may be a part of multiple groups. The list of flags and the type of group (required together or exclusive) make it a unique group.

    Fixes #1654 Fixes #1595 Fixes #1238

    Signed-off-by: John Schnake [email protected]

  • Use semantic versioning

    Use semantic versioning

    Please consider assigning version numbers and tagging releases. Tags/releases are useful for downstream package maintainers (in Debian and other distributions) to export source tarballs, automatically track new releases and to declare dependencies between packages. Read more in the Debian Upstream Guide.

    Versioning provides additional benefits to encourage vendoring of a particular (e.g. latest stable) release contrary to random unreleased snapshots.

    Thank you.

    See also

    • http://semver.org/
    • https://en.wikipedia.org/wiki/Software_versioning
  • Factor out external dependencies

    Factor out external dependencies

    I was trying to use cobra in one of my projects and I've noticed that cobra depends on a couple of libraries don't really belong to the core. The reason I'm bringing this up is because I'm managing my deps manually via vendoring into a sub dir and separate commits per lib. It feels a bit odd to copy dependencies which I don't need but cobra won't compile without them.

    The libraries in question are:

    github.com/inconshreveable/mousetrap github.com/cpuguy83/go-md2man/md2man

    The first one is only needed on Windows and the second one only for the man page generation. The man and markdown generation also seems needlessly tied to the cobra.Command object.

    Both of them can be factored out either with conditional compilation (for mousetrap) or move the code into a sub directory (man and md generation).

    I have PRs ready for both refactorings but would like to know whether this is in line with the project.

  • [question] How to pass two values for an option?

    [question] How to pass two values for an option?

    I am writing a drop-in replacement for an existing tool. This tool accepts command line options with two arguments:

    --arg name value
    

    Is it possible to configure cobra in such way, that it would expect two values for one argument?

    (of course, it is possible to use = as a separator: --arg name=value etc, but as I said, it is not an option in my case, because I am working on a fully compatible drop-in replacement)

    /cc stackoverflow: https://stackoverflow.com/questions/75018376/how-to-pass-two-values-for-an-option-in-cobra

  • Expose version flag also as version command

    Expose version flag also as version command

    When the Version field is set, it will automatically add the --version and -v flag. The feature request is to also add a version command when the Version field is set. And also make it configurable, so that the developer can choose to expose the Version as a flag, a command or both.

    Examples:

    • The git cli supports both -v and version
    • The kubectl cli only support version

    Also sometimes CLI's use the -v for verbose logging levels. Allowing them to specify to use version command only and not expose it as a flag would still allow them doing so.

    Looking for feedback, and if interest, happy to see if I can make this work as part of a PR.

  • Add a Default Help Function to Cobra

    Add a Default Help Function to Cobra

    Hi folks, the current help function is: https://github.com/spf13/cobra/blob/bf11ab6321f2831be5390fdd71ab0bb2edbd9ed5/command.go#L439-L455

    My proposal is to split it into 2 functions, such as:

    func (c *Command) HelpFunc() func(*Command, []string) {
    	if c.helpFunc != nil {
    		return c.helpFunc
    	}
    	return c.DefaultHelpFunc()
    }
    
    func (c *Command) DefaultHelpFunc() func(*Command, []string) {
    	if c.HasParent() {
    		return c.Parent().HelpFunc()
    	}
    	return func(c *Command, a []string) {
    		c.mergePersistentFlags()
    		// The help should be sent to stdout
    		// See https://github.com/spf13/cobra/issues/1002
    		err := tmpl(c.OutOrStdout(), c.HelpTemplate(), c)
    		if err != nil {
    			c.PrintErrln(err)
    		}
    	}
    }
    

    Basically, Lines 443-454 become a separate function, which is the default behaviour of HelpFunc().

    Use case: Recently I was in a situation which required me to change the behaviour of the help function to do some tasks before help output got printed to the terminal. I did not want to change the help output in any way, just do some specific things before it was printed, and I realised that getting the default help behaviour after using SetHelpFunc() is really difficult. It would be nice if there were a DefaultHelpFunc that I could call after my tasks in my custom help function.

    I'll be more than happy to raise a PR with the changes if this seems like a reasonable refactor/change.

    Thanks for this awesome library!

  • build(deps): bump actions/stale from 6 to 7

    build(deps): bump actions/stale from 6 to 7

    Bumps actions/stale from 6 to 7.

    Release notes

    Sourced from actions/stale's releases.

    v7.0.0

    ⚠️ This version contains breaking changes ⚠️

    What's Changed

    Breaking Changes

    • In this release we prevent this action from managing the stale label on items included in exempt-issue-labels and exempt-pr-labels
    • We decided that this is outside of the scope of this action, and to be left up to the maintainer

    New Contributors

    Full Changelog: https://github.com/actions/stale/compare/v6...v7.0.0

    v6.0.1

    Update @​actions/core to 1.10.0 #839

    Full Changelog: https://github.com/actions/stale/compare/v6.0.0...v6.0.1

    Changelog

    Sourced from actions/stale's changelog.

    Changelog

    [7.0.0]

    :warning: Breaking change :warning:

    [6.0.1]

    Update @​actions/core to v1.10.0 (#839)

    [6.0.0]

    :warning: Breaking change :warning:

    Issues/PRs default close-issue-reason is now not_planned(#789)

    [5.1.0]

    Don't process stale issues right after they're marked stale [Add close-issue-reason option]#764#772 Various dependabot/dependency updates

    4.1.0 (2021-07-14)

    Features

    4.0.0 (2021-07-14)

    Features

    Bug Fixes

    • dry-run: forbid mutations in dry-run (#500) (f1017f3), closes #499
    • logs: coloured logs (#465) (5fbbfba)
    • operations: fail fast the current batch to respect the operations limit (#474) (5f6f311), closes #466
    • label comparison: make label comparison case insensitive #517, closes #516
    • filtering comments by actor could have strange behavior: "stale" comments are now detected based on if the message is the stale message not who made the comment(#519), fixes #441, #509, #518

    Breaking Changes

    ... (truncated)

    Commits
    • 6f05e42 draft release for v7.0.0 (#888)
    • eed91cb Update how stale handles exempt items (#874)
    • 10dc265 Merge pull request #880 from akv-platform/update-stale-repo
    • 9c1eb3f Update .md files and allign build-test.yml with the current test.yml
    • bc357bd Update .github/workflows/release-new-action-version.yml
    • 690ede5 Update .github/ISSUE_TEMPLATE/bug_report.md
    • afbcabf Merge branch 'main' into update-stale-repo
    • e364411 Update name of codeql.yml file
    • 627cef3 fix print outputs step (#859)
    • 975308f Merge pull request #876 from jongwooo/chore/use-cache-in-check-dist
    • Additional commits viewable in compare view

    Dependabot compatibility score

    Dependabot will resolve any conflicts with this PR as long as you don't alter it yourself. You can also trigger a rebase manually by commenting @dependabot rebase.


    Dependabot commands and options

    You can trigger Dependabot actions by commenting on this PR:

    • @dependabot rebase will rebase this PR
    • @dependabot recreate will recreate this PR, overwriting any edits that have been made to it
    • @dependabot merge will merge this PR after your CI passes on it
    • @dependabot squash and merge will squash and merge this PR after your CI passes on it
    • @dependabot cancel merge will cancel a previously requested merge and block automerging
    • @dependabot reopen will reopen this PR if it is closed
    • @dependabot close will close this PR and stop Dependabot recreating it. You can achieve the same result by closing it manually
    • @dependabot ignore this major version will close this PR and stop Dependabot creating any more for this major version (unless you reopen the PR or upgrade to it yourself)
    • @dependabot ignore this minor version will close this PR and stop Dependabot creating any more for this minor version (unless you reopen the PR or upgrade to it yourself)
    • @dependabot ignore this dependency will close this PR and stop Dependabot creating any more for this dependency (unless you reopen the PR or upgrade to it yourself)
  • Update main image to better handle dark background

    Update main image to better handle dark background

    This commit uses the images provided by @Deleplace in #1880

    ~I'm not too sure if it is safe to point to that image URL directly as provided in the issue? Seems to work...~ The image is part of a new assets directory

    In the commit message I used what I found as name and email, please confirm this is ok with you @Deleplace.

    Edit: email address removed. Sorry for having posted it.

  • Configurable: Check if any Flags would get shadowed and then return with error

    Configurable: Check if any Flags would get shadowed and then return with error

    Problem description

    It is possible that a flag of a command shadows flags of its parent commands and therefore hides it. But sometimes this behavior is not wanted and it may introduces unwanted shadowing which is not seen immediately.

    Proposed solution

    When Execute is called, a helper method getClashingFlagnames is used to determine all flags with duplicate Flag.Name. The error message list all duplicate flags with its name and usage string (Flag.Name & Flag.Usage). The idea is to help the developer to find the corresponding duplicate flagnames in the code.

    In order to keep old code running the same way, this check is off by default and can be turned on by setting Command.ErrorOnShadowedFlags to true.

    What do you think about such a flag and check?

Bit is a modern Git CLI
Bit is a modern Git CLI

bit is an experimental modernized git CLI built on top of git that provides happy defaults and other niceties: command and flag suggestions to help yo

Dec 28, 2022
A powerful modern CLI and SHELL
A powerful modern CLI and SHELL

Grumble - A powerful modern CLI and SHELL There are a handful of powerful go CLI libraries available (spf13/cobra, urfave/cli). However sometimes an i

Dec 30, 2021
A modern and intuitive terminal-based text editor
A modern and intuitive terminal-based text editor

micro is a terminal-based text editor that aims to be easy to use and intuitive, while also taking advantage of the capabilities of modern terminals

Jan 7, 2023
A modern UNIX ed (line editor) clone written in Go

ed (the awesome UNIX line editor) ed is a clone of the UNIX command-line tool by the same name ed a line editor that was nortorious for being and most

May 29, 2021
Modern ls command with vscode like File Icon and Git Integrations. Written in Golang
Modern ls command with vscode like File Icon and Git Integrations. Written in Golang

logo-ls modern ls command with beautiful Icons and Git Integrations . Written in Golang Command and Arguments supported are listed in HELP.md Table of

Dec 29, 2022
👀 A modern watch command. Time machine and pager etc.
👀 A modern watch command. Time machine and pager etc.

Viddy Modern watch command. Viddy well, gopher. Viddy well. Demo Features Basic features of original watch command. Execute command periodically, and

Jan 2, 2023
🚀 goprobe is a promising command line tool for inspecting URLs with modern and user-friendly way.

goprobe Build go build -o ./bin/goprobe Example > goprobe https://github.com/gaitr/goprobe > cat links.txt | goprobe > echo "https://github.com/gaitr/

Oct 24, 2021
Package command provide simple API to create modern command-line interface

Package command Package command provide simple API to create modern command-line interface, mainly for lightweight usage, inspired by cobra Usage pack

Jan 16, 2022
Sipexer - Modern and flexible SIP (RFC3261) command line tool

sipexer Modern and flexible SIP (RFC3261) command line tool. Overview sipexer is

Jan 1, 2023
Modern YouTube converter, that combines simplicity and effectiveness
Modern YouTube converter, that combines simplicity and effectiveness

Modern YouTube converter, that combines simplicity and effectiveness. How to use it? Go to TubeConv.com Paste a link to a video, or use the search bar

Jul 25, 2022
Elegant CLI wrapper for kubeseal CLI

Overview This is a wrapper CLI ofkubeseal CLI, specifically the raw mode. If you just need to encrypt your secret on RAW mode, this CLI will be the ea

Jan 8, 2022
CLI to run a docker image with R. CLI built using cobra library in go.
CLI  to run a docker image with R. CLI built using cobra library in go.

BlueBeak Installation Guide Task 1: Building the CLI The directory structure looks like Fastest process: 1)cd into bbtools 2)cd into bbtools/bin 3)I h

Dec 20, 2021
A wrapper of aliyun-cli subcommand alidns, run aliyun-cli in Declarative mode.

aliyun-dns A wrapper of aliyun-cli subcommand alidns, run aliyun-cli in Declarative mode. Installation Install aliyun-cli. Usage $ aliyun-dns -h A wra

Dec 21, 2021
Symfony-cli - The Symfony CLI tool For Golang

Symfony CLI Install To install Symfony CLI, please download the appropriate vers

Dec 28, 2022
Go-file-downloader-ftctl - A file downloader cli built using golang. Makes use of cobra for building the cli and go concurrent feature to download files.

ftctl This is a file downloader cli written in Golang which uses the concurrent feature of go to download files. The cli is built using cobra. How to

Jan 2, 2022
Cli-algorithm - A cli program with A&DS in go!

cli-algorithm Objectives The objective of this cli is to implement 4 basic algorithms to sort arrays been Merge Sort Insertion Sort Bubble Sort Quick

Jan 2, 2022
Nebulant-cli - Nebulant's CLI
Nebulant-cli - Nebulant's CLI

Nebulant CLI Website: https://nebulant.io Documentation: https://nebulant.io/docs.html The Nebulant CLI tool is a single binary that can be used as a

Jan 11, 2022
News-parser-cli - Simple CLI which allows you to receive news depending on the parameters passed to it
News-parser-cli - Simple CLI which allows you to receive news depending on the parameters passed to it

news-parser-cli Simple CLI which allows you to receive news depending on the par

Jan 4, 2022