A Commander for modern Go CLI interactions

Overview

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

Issues
  • 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
    kind/feature area/shell-completion 
    opened by marckhouzam 60
  • 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.

    opened by babysnakes 58
  • 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/[email protected]

    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/[email protected] 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/[email protected]
    go get -u github.com/liggitt/cobra
    go get -u github.com/liggitt/[email protected]
    go get -u github.com/liggitt/[email protected]
    

    go install:

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

    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/[email protected]{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
    opened by liggitt 47
  • 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
    
    opened by chmouel 41
  • 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.

    opened by dnephin 39
  • 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)
    kind/feature 
    opened by marckhouzam 38
  • 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. :-)

    kind/feature area/shell-completion 
    opened by anthonyfok 38
  • 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
    opened by umarcor 36
  • 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]

    kind/feature area/flags-args size/XL lgtm 
    opened by johnSchnake 34
  • 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
    opened by onlyjob 34
  • 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.

    opened by magiconair 33
  • Supporting upgrades for CLIs developed with Cobra?

    Supporting upgrades for CLIs developed with Cobra?

    Hello maintainers and community!

    I am developing a CLI using cobra for my team's internal use. I expect somewhere between 5 to 50 people to use it actively. The purpose of the CLI is simply to automate some of the common tasks many people in our team frequently execute. As such I expect to roll out new versions of this CLI for my team fairly frequently.

    How are upgrades for CLIs developed with Cobra typically carried out? I was hoping for an upgrade command similar to the az upgrade command available in the Azure CLI (docs), but I don't see anything related to that in the docs.

    Are there any ways other than relying on the package manager like brew to offer upgrades? Would love to hear more suggestions from the maintainers and the community.

    Thank you!

    opened by ekamwctx 1
  • feat: add markflagsdependenton (#1739)

    feat: add markflagsdependenton (#1739)

    This PR adds to the group validation capability that came in the Spring release with the advent of MarkFlagsRequiredTogether and MarkFlagsMutuallyExclusive by adding 2 further group validation options (new methods on the cobra.Command):

    • MarkFlagsDependsOn: 1 or more flags are dependentent upon another
    • MarkFlagDependsOnAny: a flag depends on at least 1 of a group of other flags

    These 2 options differ from MarkFlagsRequiredTogether and MarkFlagsMutuallyExclusive in a key aspect, that being that the relationship is 1 way, ie:

    • for MarkFlagsDependsOn: Flags A and B depends on Flag X, but X is not dependent on A or B.
    • for MarkFlagDependsOnAny: A is dependent at least 1 of X or Y, but X and Y ore not dependent on A.

    I have tried to minimise the amount of code changes in this PR. If I had free will, I would have made all the code consistent, but that would have resulted in more code changes. If you would prefer for me to make existing code consistent with new, then please let me know and I will update.

    More detailed explaination of changes:

    • setting annotations: 2 new unexported functions has been defined markAnnotation and setFlagAnnotation which mimmicks how annotations are added for MarkFlagsRequiredTogether and MarkFlagsMutuallyExclusive (referred to as non special flag validators). For those 2 non special validators, code is duplicated and the only difference between the 2 implemenations is the error message that is defined for the panic, if the flag can't be found. markAnnotation/setFlagAnnotation avoid the duplication, by using a format parameter. Ideally, the non special validators should be updated to use markAnnotation, but I avoided this to reduce on code churn.
    • special status: for the non special validators, all parameters in the group have identical status. The new special validators (MarkFlagsDependsOn and MarkFlagDependsOnAny) impose a different status to the first flag in the group. For MarkFlagsDependsOn, the first flag is the dependee, that all other flags in the group depend on. For MarkFlagDependsOnAny, the first flag depends on at least one of the other flags being present.

    More on special status: To support this, a new collection specialGroupInfoCollection and associated structs specialStatusInfoData and specialGroupInfo have been defined.

    The non special valdators use processFlagForGroupAnnotation which internally defines a map of string to bool, indicating whether a flag is present or not. For the new special validators, this is not enough. For a particluar group, we need to distinguish which flag in the group is the special one. So:

    • specialGroupInfoCollection: maps the group name to a specialGroupInfo
    • specialGroupInfo: contains special which indicates which is the special flag, others the remaing flags. To maintain similarilty with existing code, we also have a member of type specialStatusInfoData
    • specialStatusInfoData: simply maps a flag name to a boolean value equivalent to isSet

    Defined 2 new group validator functions: validateDependsOnFlagGroups and validateDependsOnAnyFlagGroups, both of which use the newly defined struct specialGroupInfoCollection for validation which are equivalent to the valitdators that exist for non special group validators validateRequiredFlagGroups and validateExclusiveFlagGroups.

    TODO: still need completions tests for MarkFlagsDependsOn. There is no completions functionality for MarkFlagDependsOnAny, because if flag A is dependent on X or Y, we can't mark either as required using MarkFlagRequired and we can't hide either of them by setting the Hidden property to true.

    size/XL 
    opened by plastikfan 6
  • Update gopkg.in/yaml.v2 to gopkg.in/yaml.v3

    Update gopkg.in/yaml.v2 to gopkg.in/yaml.v3

    API v3 was released in 2019 [1]. Update from the v2 API, no changes to the packages's use needed and no breaking changes expected.

    [1] https://ubuntu.com/blog/api-v3-of-the-yaml-package-for-go-is-available

    area/docs-generation size/XS 
    opened by tklauser 1
  • failed parse ~ to $HOME when use = in flag assignment

    failed parse ~ to $HOME when use = in flag assignment

    I want to open file with filepath assigned in flag

    This is my code

    package main
    
    import (
    	"fmt"
    	"os"
    
    	"github.com/spf13/cobra"
    )
    
    var (
    	file string
    
    	rootCmd = &cobra.Command{
    		Use:   "",
    		Short: "",
    		Long:  "",
    		Run: func(cmd *cobra.Command, args []string) {
    			if _, err := os.Stat(file); os.IsNotExist(err) {
    				fmt.Println(err.Error())
    			} else {
    				fmt.Println(file)
    			}
    		},
    	}
    )
    
    func init() {
    	rootCmd.PersistentFlags().StringVarP(&file, "file", "f", "", "file path")
    }
    
    func main() {
    	if err := rootCmd.Execute(); err != nil {
    		fmt.Fprintln(os.Stderr, err)
    	}
    }
    

    And the execute results are:

    without =, successed parse ~ to $HOME

    [email protected]# ./main --file ~/.kube/config
    /root/.kube/config
    

    with =, failed parse ~ to $HOME

    [email protected]-VFP625S5# ./main --file=~/.kube/config
    stat ~/.kube/config: no such file or directory
    

    Is that any ways can make it parse ~ successful with = ?

    opened by zhuwint 0
  • markdown documents and help command should show information about deprecated flags

    markdown documents and help command should show information about deprecated flags

    Currently, the generated markdown and the help command do not give any information about deprecated flags in the output and in the markdown. So, this might cause the user's not to know about the flags that are deprecated and might face some issues in the long run.

    opened by tharun208 0
Releases(v1.5.0)
  • v1.5.0(Jun 21, 2022)

    Spring 2022 Release 🌥️

    Hello everyone! Welcome to another release of cobra. Completions continue to get better and better. This release adds a few really cool new features. We also continue to patch versions of our dependencies as they become available via dependabot. Happy coding!

    Active help 👐🏼

    Shout out to @marckhouzam for a big value add: Active Help https://github.com/spf13/cobra/pull/1482. With active help, a program can provide some inline warnings or hints for users as they hit tab. Now, your CLIs can be even more intuitive to use!

    Currently active help is only supported for bash V2 and zsh. Marc wrote a whole guide on how to do this, so make sure to give it a good read to learn how you can add this to your cobra code! https://github.com/spf13/cobra/blob/master/active_help.md

    Group flags 🧑🏼‍🤝‍🧑🏼

    Cobra now has the ability to mark flags as required or exclusive as a group. Shout out to our newest maintainer @johnSchnake for this! https://github.com/spf13/cobra/pull/1654 Let's say you have a username flag that MUST be partnered with a password flag. Well, now, you can enforce those as being required together:

    rootCmd.Flags().StringVarP(&u, "username", "u", "", "Username (required if password is set)")
    rootCmd.Flags().StringVarP(&pw, "password", "p", "", "Password (required if username is set)")
    rootCmd.MarkFlagsRequiredTogether("username", "password")
    

    Flags may also be marked as "mutally exclusive" with the MarkFlagsMutuallyExclusive(string, string ... ) command API. Refer to our user guide documentation for further info!

    Completions 👀

    • Add backwards-compatibility tests for legacyArgs() by @marckhouzam in https://github.com/spf13/cobra/pull/1547
    • feat: Add how to load completions in your current zsh session by @ondrejsika in https://github.com/spf13/cobra/pull/1608
    • Introduce FixedCompletions by @emersion in https://github.com/spf13/cobra/pull/1574
    • Add shell completion to flag groups by @marckhouzam in https://github.com/spf13/cobra/pull/1659
    • Modify brew prefix path in macOS system by @imxw in https://github.com/spf13/cobra/pull/1719
    • perf(bash-v2): use backslash escape string expansion for tab by @scop in https://github.com/spf13/cobra/pull/1682
    • style(bash-v2): out is not an array variable, do not refer to it as such by @scop in https://github.com/spf13/cobra/pull/1681
    • perf(bash-v2): standard completion optimizations by @scop in https://github.com/spf13/cobra/pull/1683
    • style(bash): out is not an array variable, do not refer to it as such by @scop in https://github.com/spf13/cobra/pull/1684
    • perf(bash-v2): short-circuit descriptionless candidate lists by @scop in https://github.com/spf13/cobra/pull/1686
    • perf(bash-v2): speed up filtering entries with descriptions by @scop in https://github.com/spf13/cobra/pull/1689
    • perf(bash-v2): speed up filtering menu-complete descriptions by @scop in https://github.com/spf13/cobra/pull/1692
    • fix(bash-v2): skip empty completions when filtering descriptions by @scop in https://github.com/spf13/cobra/pull/1691
    • perf(bash-v2): read directly to COMPREPLY on descriptionless short circuit by @scop in https://github.com/spf13/cobra/pull/1700
    • fix: Don't complete _command on zsh by @twpayne in https://github.com/spf13/cobra/pull/1690
    • Improve fish_completions code quality by @t29kida in https://github.com/spf13/cobra/pull/1515
    • Fix handling of descriptions for bash v3 by @marckhouzam in https://github.com/spf13/cobra/pull/1735
    • undefined or nil Args default to ArbitraryArgs by @umarcor in https://github.com/spf13/cobra/pull/1612
    • Add Command.SetContext by @joshcarp in https://github.com/spf13/cobra/pull/1551
    • Wrap printf tab with quotes by @PapaCharlie in https://github.com/spf13/cobra/pull/1665

    Documentation 📝

    • Fixed typos in completions docs - @cuishuang https://github.com/spf13/cobra/pull/1625
    • Removed CHANGELOG.md as it isn't updated - @johnSchnake https://github.com/spf13/cobra/pull/1634
    • Minor typo fix in shell_completion.md - @danieldn https://github.com/spf13/cobra/pull/1678
    • Changed branch name in the cobra generator link to 'main' - @skywalker2909 https://github.com/spf13/cobra/pull/1645
    • Fix Command.Context comment by @katexochen in https://github.com/spf13/cobra/pull/1639
    • Change appropriate links from http:// to https:// where applicable - @deining https://github.com/spf13/cobra/pull/1695

    Testing & CI ⚙️

    • Test on Golang 1.18 - @umarcor https://github.com/spf13/cobra/pull/1635
    • Use RICHGO_FORCE_COLOR - @umarcor https://github.com/spf13/cobra/pull/1647
    • Adds size labeler GitHub action by @jpmcb in https://github.com/spf13/cobra/pull/1610
    • Update stale-bot settings - @jpmcb https://github.com/spf13/cobra/pull/1609

    Beep boop, bot commits 🤖

    • Bumped golangci/golangci-lint-action from 3.1.0 to 3.2.0 - @dependabot https://github.com/spf13/cobra/pull/1697
    • Bump codelytv/pr-size-labeler from 1.8.0 to 1.8.1 - @dependabot https://github.com/spf13/cobra/pull/1661
    • Bump actions/stale from 1 to 5 by @dependabot in https://github.com/spf13/cobra/pull/1618
    • Bump actions/cache from 2 to 3 by @dependabot in https://github.com/spf13/cobra/pull/1640
    • Bump actions/labeler from 3 to 4 by @dependabot in https://github.com/spf13/cobra/pull/1620
    • Bump golangci/golangci-lint-action from 2 to 3.1.0 by @dependabot in https://github.com/spf13/cobra/pull/1615
    • Bump actions/checkout from 2 to 3 by @dependabot in https://github.com/spf13/cobra/pull/1619
    • Bump github.com/cpuguy83/go-md2man/v2 from 2.0.1 to 2.0.2 by @dependabot in https://github.com/spf13/cobra/pull/1688
    • Bump actions/setup-go from 2 to 3 by @dependabot in https://github.com/spf13/cobra/pull/1660

    Misc 💭

    • Use errors.Is() to check for errors - @Luap99 https://github.com/spf13/cobra/pull/1730
    • Prefer ReplaceAll instead of Replace(..., -1) by @WhyNotHugo in https://github.com/spf13/cobra/pull/1530
    • Add Kubescape to projects - @avinashupadhya99 https://github.com/spf13/cobra/pull/1642
    • Add Pulumi as a project using cobra by @iwahbe in https://github.com/spf13/cobra/pull/1720
    • Add Polygon Edge as a project using Cobra by @zivkovicmilos in https://github.com/spf13/cobra/pull/1672

    Shoutout to ALL our contributors (and all the new first time contributors!!) - great work everyone!! Cobra and it's huge impact wouldn't be possible without you 👏🏼 🚀 🐍

    Full Changelog: https://github.com/spf13/cobra/compare/v1.4.0...v1.5.0

    Source code(tar.gz)
    Source code(zip)
  • v1.4.0(Mar 10, 2022)

    Winter 2022 Release ❄️

    Another season, another release!

    Goodbye viper! 🐍 🚀

    The core Cobra library no longer requires Viper and all of its indirect dependencies. This means that Cobra's dependency tree has been drastically thinned! The Viper dependency was included because of the cobra CLI generation tool. This tool has migrated to spf13/cobra-cli.

    It's pretty unlikely you were importing and using the bootstrapping CLI tool as part of your application (after all, it's just a tool to get going with core cobra).

    But if you were, replace occurrences of

    "github.com/spf13/cobra/cobra"
    

    with

    "github.com/spf13/cobra-cli"
    

    And in your go.mod, you'll want to also include this dependency:

    github.com/spf13/cobra-cli v1.3.0
    

    Again, the maintainers do not anticipate this being a breaking change to users of the core cobra library, so minimal work should be required for users to integrate with this new release. Moreover, this means the dependency tree for your application using Cobra should no longer require dependencies that were inherited from Viper. Huzzah! 🥳

    If you'd like to read more

    • issue: https://github.com/spf13/cobra/issues/1597
    • PR: https://github.com/spf13/cobra/pull/1604

    Documentation 📝

    • Update Go Doc link and badge in README: https://github.com/spf13/cobra/pull/1593
    • Fix to install command, now targets @latest: https://github.com/spf13/cobra/pull/1576
    • Added MAINTAINERS file: https://github.com/spf13/cobra/pull/1545

    Other 💭

    • Bumped license year to 2022 in golden files: https://github.com/spf13/cobra/pull/1575
    • Added Pixie to projects: https://github.com/spf13/cobra/pull/1581
    • Updated labeler for new labeling scheme: https://github.com/spf13/cobra/pull/1613 & syntax fix: https://github.com/spf13/cobra/pull/1624

    Shoutout to our awesome contributors helping to make this cobra release possible!! @spf13 @marckhouzam @johnSchnake @jpmcb @liggitt @umarcor @hiljusti @marians @shyim @htroisi

    Source code(tar.gz)
    Source code(zip)
  • v1.3.0(Dec 14, 2021)

    v1.3.0 - The Fall 2021 release 🍁

    Completion fixes & enhancements 💇🏼

    In v1.2.0, we introduced a new model for completions. Thanks to everyone for trying it, giving feedback, and providing numerous fixes! Continue to work with the new model as the old one (as noted in code comments) will be deprecated in a coming release.

    • DisableFlagParsing now triggers custom completions for flag names #1161
    • Fixed unbound variables in bash completions causing edge case errors #1321
    • help completion formatting improvements & fixes #1444
    • All completions now follow the help example: short desc are now capitalized and removes extra spacing from long description #1455
    • Typo fixes in bash & zsh completions #1459
    • Fixed mixed tab/spaces indentation in completion scripts. Now just 4 spaces #1473
    • Support for different bash completion options. Bash completions v2 supports descriptions and requires descriptions to be removed for menu-complete, menu-complete-backward and insert-completions. These descriptions are now purposefully removed in support of this model. #1509
    • Fix for invalid shell completions when using ~/.cobra.yaml. Log message Using config file: ~/.cobra.yaml now printed to stderr #1510
    • Removes unnecessary trailing spaces from completion command descriptions #1520
    • Option to hide default completion command #1541
    • Remove __complete command for programs without subcommands #1563

    Generator changes ⚙️

    Thanks to @spf13 for providing a number of changes to the Cobra generator tool, streamlining it for new users!

    • The Cobra generator now won't automatically include Viper and cleans up a number of unused imports when not using Viper.
    • The Cobra generator's default license is now none
    • The Cobra generator now works with Go modules
    • Documentation to reflect these changes

    New Features ⭐

    • License can be specified by their SPDX identifiers #1159
    • MatchAll allows combining several PositionalArgs to work in concert. This now allows for enabling composing PositionalArgs #896

    Bug Fixes 🐛

    • Fixed multiple error message from cobra init boilerplates #1463 #1552 #1557

    Testing 👀

    • Now testing golang 1.16.x and 1.17.x in CI #1425
    • Fix for running diff test to ignore CR for windows #949
    • Added helper functions and reduced code reproduction in args_test #1426
    • Now using official golangci-lint github action #1477

    Security 🔏

    • Added GitHub dependabot #1427
    • Now using Viper v1.10.0
      • There is a known CVE in an indirect dependency from viper: https://github.com/spf13/cobra/issues/1538. This will be patched in a future release

    Documentation 📝

    • Multiple projects added to the projects_using_cobra.md file: #1377 #1501 #1454
    • Removed ToC from main readme file as it is now automagically displayed by GitHub #1429
    • Documentation correct for when the --author flag is specified #1009
    • shell_completions.md has an easier to use snippet for copying and pasting shell completions #1372

    Other 💭

    • Bump version of cpuguy83/go-md2man to v2.0.1 #1460
    • Removed lesser typo from the GPL-2.0 license #880
    • Fixed spelling errors #1514

    Thank you to all our amazing contributors ⭐🐍🚀

    Source code(tar.gz)
    Source code(zip)
  • v1.2.1(Jul 2, 2021)

    Bug fixes

    • Quickfix for https://github.com/spf13/cobra/issues/1437 after v1.2.0 where parallel use of the cmd.RegisterFlagCompletionFunc() (and subsequent map) now works correctly and flag completions now work again
    Source code(tar.gz)
    Source code(zip)
  • v1.2.0(Jul 1, 2021)

    :stars: v1.2.0 - The completions release

    Welcome to v1.2.0 of Cobra! This release focuses on code completions, several critical bug fixes, some documentation updates, and security bumps. Upgrading should be simple but please take note of the introduction of bash completions V2 and their default use. The v1 completions library is still available, but will be deprecated in the future. Please open an issue with any problems!


    New Features

    • Automatically adds a completion command for shell completions. If a completion command is already provided, uses that instead. This will automatically provide shell completions for bash, zsh, fish, and PowerShell https://github.com/spf13/cobra/pull/1192
      • Users can configure the command auto creation:
        • disable the creation of the completion command
        • disable completion descriptions
        • disable the --no-descriptions flag for "always on" completion descriptions
    • Introduction of bash completions V2, a uniform completion approach which include completion descriptions. The V1 bash completions are still available but will be deprecated in a later release - https://github.com/spf13/cobra/pull/1146
      • Note that projects providing completion through a different command name (say a command named "complete") will continue to use v1 for their own command but will also provide cobra's implicit "completion" command which will use v2, unless of course, these projects take the time to disable the default "completion" command as noted above.
    • Commands now support context being passed to completions - https://github.com/spf13/cobra/pull/1265
      • An example can be found here: https://github.com/spf13/cobra/pull/1265#issuecomment-734551031
    • Removed dependency onmitchellh/go-homedir in favor of core Go os.UserHomeDir() - https://github.com/spf13/cobra/commit/8eaca5f0f49ad747a0722d39dca7a75c34abd21a

    Bug Fixes

    • Fix trailing whitespace not being handled in powershell completion scripts https://github.com/spf13/cobra/pull/1342
    • Bash completion variable leak fix https://github.com/spf13/cobra/pull/1352
    • Fish shell completions correctly ignore trailing empty lines https://github.com/spf13/cobra/pull/1284
    • PowerShell completions fix for "no file comp directive" - https://github.com/spf13/cobra/pull/1363
    • Custom completions now correctly handle multiple shorthand flags together - https://github.com/spf13/cobra/pull/1258
    • zsh completions now correctly handle ShellDirectiveCompletionNoSpace and file completion all the time - https://github.com/spf13/cobra/pull/1213
    • Multiple fixes / improvements to the fish shell support - https://github.com/spf13/cobra/pull/1249
    • Fix home directory config not loading correctly - https://github.com/spf13/cobra/pull/1282
    • Fix for RegisterFlagCompletionFunc as a global var not working in multi-threaded programs: https://github.com/spf13/cobra/pull/1423
    • Custom completions correctly do not complete flags after args when interspersed is false #1308

    Testing

    • Deprecated Travis CI. Now fully using Github Actions - https://github.com/spf13/cobra/commit/d0f318d45bdb46e3c1bc314c6096674426f1a620
    • Added test cases and enhancements (thank you to everyone for taking the time to add tests to your PRs!)
    • Shoutout to @marckhouzam and @Luap99 for their hard work on a cobra command completions testing library. Check out the repo here!

    Security

    • Bump viper to 1.8.1. This corrects several issues with vulnerabilities existing in the dependency tree - https://github.com/spf13/cobra/pull/1433

    Other

    • Add PR labeler with pull_request_target to enable tests to run from forks - https://github.com/spf13/cobra/pull/1338
    • CI using MSYS2 windows machines pull latest - https://github.com/spf13/cobra/pull/1366
    • Multiple small fixes to spelling / documentation - https://github.com/spf13/cobra/pull/1349 https://github.com/spf13/cobra/pull/1417 https://github.com/spf13/cobra/pull/1434

    Thank you to all our amazing contributors :snake::rocket:

    Source code(tar.gz)
    Source code(zip)
  • v1.1.3(Feb 10, 2021)

  • v1.1.2(Feb 10, 2021)

    Notable Changes

    • Bump license year to 2021 in golden files (#1309) @Bowbaq
    • Enhance PowerShell completion with custom comp (#1208) @Luap99
    • Update gopkg.in/yaml.v2 to v2.4.0: The previous breaking change in yaml.v2 v2.3.0 has been reverted, see go-yaml/yaml#670
    • Documentation readability improvements (#1228 etc.) @zaataylor etc.
    • Use golangci-lint: Repair warnings and errors resulting from linting (#1044) @umarcor
    Source code(tar.gz)
    Source code(zip)
  • v1.1.1(Oct 18, 2020)

    • Fix: yaml.v2 2.3.0 contained a unintended breaking change. This release reverts to yaml.v2 v2.2.8 which has recent critical CVE fixes, but does not have the breaking changes. See https://github.com/spf13/cobra/pull/1259 for context.
    • Fix: correct internal formatting for go-md2man v2 (which caused man page generation to be broken). See https://github.com/spf13/cobra/issues/1049 for context.
    Source code(tar.gz)
    Source code(zip)
  • v1.1.0(Oct 14, 2020)

    Notable Changes

    • Extend Go completions and revamp zsh comp (#1070)
    • Fix man page doc generation - no auto generated tag when cmd.DisableAutoGenTag = true (#1104)
    • Add completion for help command (#1136)
    • Complete subcommands when TraverseChildren is set (#1171)
    • Fix stderr printing functions (#894)
    • fix: fish output redirection (#1247)
    Source code(tar.gz)
    Source code(zip)
  • v1.0.0(Apr 10, 2020)

    v1.0.0

    Announcing v1.0.0 of Cobra. :tada:

    Notable Changes

    • Fish completion (including support for Go custom completion) @marckhouzam
    • API (urgent): Rename BashCompDirectives to ShellCompDirectives @marckhouzam
    • Remove/replace SetOutput on Command - deprecated @jpmcb
    • add support for autolabel stale PR @xchapter7x
    • Add Labeler Actions @xchapter7x
    • Custom completions coded in Go (instead of Bash) @marckhouzam
    • Partial Revert of #922 @jharshman
    • Add Makefile to project @jharshman
    • Correct documentation for InOrStdin @desponda
    • Apply formatting to templates @jharshman
    • Revert change so help is printed on stdout again @marckhouzam
    • Update md2man to v2.0.0 @pdf
    • update viper to v1.4.0 @umarcor
    • Update cmd/root.go example in README.md @jharshman
    Source code(tar.gz)
    Source code(zip)
  • v0.0.7(Mar 27, 2020)

  • v0.0.4(May 18, 2019)

  • v0.0.3(May 15, 2018)

  • v0.0.2(Mar 29, 2018)

Owner
Steve Francia
@golang product lead at @google • Author, Speaker, Developer • Creator of @gohugoio, Cobra, Viper & spf13-vim • former @docker & @mongodb
Steve Francia
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

Chris Walz 5.8k Aug 4, 2022
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

梁辰风 0 Dec 30, 2021
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

Zachary Yedidia 19.9k Jul 27, 2022
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

James Mills 45 May 29, 2021
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

Yash Handa 901 Jul 30, 2022
👀 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

Takumasa Sakao 3.5k Aug 4, 2022
🚀 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/

null 3 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

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

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

Daniel-Constantin Mierla 128 Jul 29, 2022
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

Qiu 3 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

Elm 4 Jan 8, 2022
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

Aniruddha Chattopadhyay 0 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

许嘉华 0 Dec 21, 2021
Symfony-cli - The Symfony CLI tool For Golang

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

Symfony CLI 341 Jul 29, 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

Dipto Chakrabarty 2 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

Leonardo Brombilla Antunes 0 Jan 2, 2022
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

Develatio 2 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 par

Maxym 0 Jan 4, 2022