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
    area/*sh completion kind/enhancement 
    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
  • 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
    
    kind/stale 
    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
  • 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. :-)

    area/*sh completion kind/enhancement kind/stale 
    opened by anthonyfok 38
  • 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/enhancement kind/stale 
    opened by marckhouzam 38
  • 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
    kind/stale 
    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
  • Fix stderr printing functions

    Fix stderr printing functions

    Follow-up of #822

    This fixes stderr redirection.

    Closes: #1100

    @spf13 @eparis

    kind/bug 
    opened by alessio 29
  • Custom completions coded in Go (instead of Bash)

    Custom completions coded in Go (instead of Bash)

    This PR allows programs using Cobra to code their custom completions in Go directly inside the program itself.

    It is a port to Cobra of the custom completion solution introduced in Helm 3.1 (https://github.com/helm/helm/pull/7323).

    It is fully-backwards compatible. It also allows to use both the new Go custom completions and the existing Bash custom completions at the same time.

    The PR introduces a new hidden sub-command: __complete that is to be called by the auto-completion script. I chose the name with a double underscore prefix to make sure this command will not collide with any command of a program.

    Along the lines of the existing ValidArgs field, support is added for the ValidArgsFunction field. The program can register a function that will provide custom completion through this newly added field.

    For flags, the new function Command.RegisterFlagCompletionFunc() is added. The program can register a custom completion function for a flag using this new function.

    The bash completion script, before calling the completion *_custom_func, will now verify if Command.ValidArgsFunction has been specified. If so, the completion script will call the __complete command passing it all command-line arguments; the __complete command will call the function specified by Command.ValidArgsFunction to obtain completions from the program itself.

    To be as feature-rich as custom completions written in Bash, the PR also allows Go completions to control:

    • if a single completion should be followed by a space
    • if file completion should be performed when no completions are available

    Some advantages of using Go instead of Bash for custom completions:

    • Cobra users are Go developers
    • Access to the full program code base to perform completions instead of being limited to relying on externally-exposed functionality.
    • Debugging and development much easier because developers can directly call e.g., <program> __complete <cmd> ""<ENTER> to test the corresponding custom completion code
    • The Go debugger can even be used to troubleshoot custom completion code
    • Go tests can be written for the custom completion code
    • Flag parsing done automatically by Cobra (instead of having to be coded in bash in the completion script)
    • No need to make sure the custom completion code works for both bash and zsh (for those programs that share completions between the two)
    • No more issues with the use of shell tools (e.g., echo, cat, tail) that work differently on different OSes

    To illustrate a working program using this PR, I've ported Helm from its own solution to using this PR in Cobra: https://github.com/VilledeMontreal/helm/tree/feat/compInGoWithCobra Here is an example of using the new ValidArgsFunction field: https://github.com/VilledeMontreal/helm/blob/2c88891a96eb6cb27d124d5a6d750eee85abcc8c/cmd/helm/status.go#L55 and an example of using RegisterFlagCompletionFunc(): https://github.com/VilledeMontreal/helm/blob/2c88891a96eb6cb27d124d5a6d750eee85abcc8c/cmd/helm/root.go#L86

    Go tests have been added in Cobra for this PR and the documentation for bash_completion has been updated.

    area/*sh completion kind/enhancement 
    opened by marckhouzam 25
  • How to get sub command result back to parent?

    How to get sub command result back to parent?

    Looking through the documentation, I don't see a way to push a command's "result" back to a parent command, but it seems somewhat valuable to make the result available to the parent command. Is there a way to do this? I do see the side of it being limited in usage.

    My specific use case it so common formatting and a global JMESPath query can be executed on whatever the command result would be. At this time, it is just a ton of duplicate code and some global state, no huge deal, if trying to get that result back to the parent command. It relied on the PersistentPostRun[E] hooked to handle this automatically.

    opened by Jthomas54 0
  • go.mod: cpuguy83/go-md2man/v2 v2.0.1

    go.mod: cpuguy83/go-md2man/v2 v2.0.1

    full diff: https://github.com/cpuguy83/go-md2man/compare/v2.0.0...v2.0.1

    • Fix handling multiple definition descriptions
    • Fix inline markup causing table cells to split
    • Remove escaping tilde character (prevents tildes (~) from disappearing).
    • Do not escape dash, underscore, and ampersand (prevents ampersands (&) from disappearing).
    • Ignore unknown HTML tags to prevent noisy warnings
    area/doc-gen 
    opened by thaJeztah 2
  • Fix a typo in {bash,zsh}_completions.go

    Fix a typo in {bash,zsh}_completions.go

    subDir seems to be a typo. It is deep inside bash_completions.go used to generate bash completion scripts. I am not sure how to write a test for this.

    opened by favonia 3
  • Default `help` and `completion` command descriptions are inconsistent

    Default `help` and `completion` command descriptions are inconsistent

    As of v1.2.0, there are two commands that are included by default in every Cobra CLI. Their formatting is inconsistent, which is incredibly sloppy, especially considering that their descriptions can't be changed; to my knowledge these commands can only be hidden.

    First, one Short description is uppercased, and one is lowercased. Recommendation: Make them both uppercase.

    Available Commands:
      completion  generate the autocompletion script for the specified shell
      help        Help about any command
    

    Second, one Long description has an extra leading newline, and the other does not. Recommendation: Remove the extra newline.

    $ cmd completion -h
    
    Generate the autocompletion script for spotify for the specified shell.
    See each sub-command's help for details on how to use the generated script.
    
    ...
    
    $ cmd help -h
    Help provides help for any command in the application.
    Simply type cmd help [path to command] for full details.
    
    ...
    

    In conclusion, it looks like the new completion command did not even attempt to maintain consistent formatting. A good long term solution would be to allow users to edit these descriptions to match their preferred style.

    opened by brianstrauch 1
  • Skip flag completion for commands with disabled flag parsing

    Skip flag completion for commands with disabled flag parsing

    When a command disabled flag parsing, the shell completion for that command should not offer flags. This allows completions for args to be processed like normal. This behavior is particularly useful for invoking a CLI plugin that has its own sub commands, arguments, flags, and completion rules.

    Signed-off-by: Scott Andrews [email protected]

    area/*sh completion 
    opened by scothis 10
  • Completion: Capitalize short desc and remove extra space from long

    Completion: Capitalize short desc and remove extra space from long

    The help short desc is capitalized so we should follow its lead for consistency.

    opened by fcjr 3
  • Projects

    Projects

    Close #987 Close #1371 Close #1377 Close #1380 Close #1407 Close #1446 Close #1451

    This PR superseeds multiple PRs adding projects to projects_using_cobra.md.

    /cc @jpmcb @marckhouzam

    opened by umarcor 0
  • feat(completion): add default completion hidden if there are no subcmds

    feat(completion): add default completion hidden if there are no subcmds

    This is an alternate/superseding implementation for #1392.

    The default completion is useful also in cases where there are no subcommands, for example to provide completion for flags, and custom completions for their values.

    But when there are no subcommands, make it hidden. Simply adding it non-hidden would result in a help section to be added just for it which is just noise: the completion command is not the primary functionality of the program, yet it would be prominently displayed in help output. It would also get included among argument completions, which could be a source of confusion.

    opened by scop 2
  • RFE: Stricter handling of duplicate flags

    RFE: Stricter handling of duplicate flags

    TL:DR

    If a flag with the same flag name is defined both as a persistent flag in a parent, and as a local flag in a subcommand, Cobra AFAICS not strictly distinguish between the two.

    Why is This Needed

    For compatibility with previous versions that did not use Cobra, we need to accept command --flag $subcommand …; as well as command $subcommand --flag; this is deprecated, sometimes in in favor of command same-name --flag (i.e. the same flag name, for some subcommands), or command other-name --src-flag (a different flag name, for other subcommands), but the deprecated variant needs to be accepted and interpreted correctly. Admittedly that’s a pretty rare corner case.

    What Breaks:

    • We would like to distinguish between command --flag subcommand and command subcommand --flag, so that we can print a warning. The way merging and parsing flags is currently implemented (basically with local.AddFlagSet(parent)), that’s not the case; the local flag is always used and the parent’s persistent one is ignored. Setting TraverseChildren makes this work as expected, it seems - but https://github.com/spf13/cobra/blob/8eaca5f0f49ad747a0722d39dca7a75c34abd21a/user_guide.md#local-flag-on-parent-commands talks about local flags, not persistent flags, so this looks like an undocumented/unreliable implementation artifact.

    • We would like for --help to show only the non-deprecated --flag (on the same-name subcommand), but always hide the --flag in parent’s --help. That seems impossible to do, because --help is based on Command.LocalFlags, which is (merged flags - parent's persistent flags); this implementation can’t tell the difference between a --flag defined both on the local subcommand and inherited from the parent, and a --flag only inherited from the parent. This seems hard to fix, because Command.Flags is both the input everyone uses to define new flags, and the data structure affected by mergePersistentFlags, so any change to Flags would be caller-visible and possibly breaking. We could prevent inheritance of --flag by using a non-persistent flag on the root command, but that would break compatibility with existing users in other subcommands. What does work is using a separate local (non-persistent) flag on the root command and a separate local flag on the subcommand; then we can set the Hidden flag independently, but the downside is that this leaks all over the CLI codebase.

    Any pointers to how to achieve this cleanly with the documented API, or how a PR could like, would be welcome.

    Reproducer

    With github.com/spf13/[email protected] and github.com/spf13/[email protected] : this passes as is, but we’d like two of the test cases to have a different outcome.

    package main
    
    import (
    	"bytes"
    	"fmt"
    	"strings"
    
    	"github.com/spf13/cobra"
    )
    
    type options struct {
    	deprecatedFlag bool
    	sameNameFlag   bool
    	srcFlag        bool
    }
    
    func dummyRun(_ *cobra.Command, _ []string) {}
    
    func createApp() (*cobra.Command, *options) {
    	opts := options{}
    
    	rootCommand := &cobra.Command{Use: "main", Long: "Top-level main help"}
    	rootCommand.PersistentFlags().BoolVar(&opts.deprecatedFlag, "flag", false, "deprecated - use per-subcommand flags")
    	if err := rootCommand.PersistentFlags().MarkHidden("flag"); err != nil {
    		panic(`unable to mark "flag" as hidden`)
    	}
    
    	sameNameCmd := &cobra.Command{Use: "same-name", Long: "same-name help", Run: dummyRun}
    	sameNameCmd.Flags().BoolVar(&opts.sameNameFlag, "flag", false, "this is not deprecated")
    	rootCommand.AddCommand(sameNameCmd)
    
    	otherNameCmd := &cobra.Command{Use: "other-name", Long: "other-name help", Run: dummyRun}
    	otherNameCmd.Flags().BoolVar(&opts.srcFlag, "src-flag", false, "this is not deprecated either")
    	rootCommand.AddCommand(otherNameCmd)
    	return rootCommand, &opts
    }
    
    func main() {
    	for _, t := range []struct {
    		args     []string
    		expected options
    	}{
    		{[]string{"same-name"}, options{}}, // No flags
    		{[]string{"same-name", "--flag"}, options{sameNameFlag: true}},
    
    		// We’d like to instead get: {[]string{"--flag", "same-name"}, options{deprecatedFlag: true}},
    		{[]string{"--flag", "same-name"}, options{sameNameFlag: true}},
    
    		{[]string{"--flag", "other-name"}, options{deprecatedFlag: true}},
    		{[]string{"other-name", "--src-flag"}, options{srcFlag: true}},
    	} {
    		app, opts := createApp()
    		app.SetArgs(t.args)
    		if err := app.Execute(); err != nil {
    			panic(fmt.Sprintf("Execute failed for %#v", t.args))
    		}
    		if *opts != t.expected {
    			panic(fmt.Sprintf("Unexpected parsing results for %#v: %#v vs. %#v", t.args, opts, t.expected))
    		}
    	}
    
    	for _, t := range []struct {
    		args    []string
    		visible bool
    	}{
    		{[]string{"--help"}, false},
    		{[]string{"same-name", "--help"}, false}, // We’d like to have true here
    		{[]string{"other-name", "--help"}, false},
    	} {
    		app, _ := createApp()
    		stdout := bytes.Buffer{}
    		app.SetOut(&stdout)
    		app.SetArgs(t.args)
    		if err := app.Execute(); err != nil {
    			panic(fmt.Sprintf("Execute failed for %#v", t.args))
    		}
    		help := stdout.String()
    		visible := strings.Contains(help, "--flag")
    		if visible != t.visible {
    			panic(fmt.Sprintf("Unexpected visibility for %#v: %v vs. %v", t.args, visible, t.visible))
    		}
    	}
    }
    
    opened by mtrmac 0
Releases(v1.2.1)
  • 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 note please take note of the introduction of 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 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 and will be deprecated in a latter 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 9, 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
CLI - A package for building command line app with go

Command line interface Screenshot Key features Lightweight and easy to use. Defines flag by tag, e.g. flag name(short or/and long), description, defau

王仕晋 587 Jul 18, 2021
A versatile library for building CLI applications in Go

mow.cli Package cli provides a framework to build command line applications in Go with most of the burden of arguments parsing and validation placed o

Jawher Moussa 741 Jul 18, 2021
Make Highly Customized Boxes for your CLI

Box CLI Maker ?? Box CLI Maker is a Highly Customized Terminal Box Creator. Features Make Terminal Box in 8️⃣ inbuilt different styles 16 Inbuilt Colo

Swastik Baranwal 138 Jul 18, 2021
A command-line tool for Stripe

Stripe CLI The Stripe CLI helps you build, test, and manage your Stripe integration right from the terminal. With the CLI, you can: Securely test webh

Stripe 1.1k Jul 26, 2021
A Commander for modern Go CLI interactions

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 i

Steve Francia 22.5k Jul 26, 2021
a lightweight and simple cli package

▄████████ ▄█ ▄█ ███ ███ ███ ███ ███ █▀ ███ ███▌ ███ ███ ███▌ ███ ███ ███▌ ███ █▄ ███

seo.do 11 Jul 25, 2021
Arduino command line tool

arduino-cli Arduino CLI is an all-in-one solution that provides builder, Boards/Library Manager, uploader, discovery and many other tools needed to us

Arduino 3k Jul 23, 2021
Another CLI framework for Go. It works on my machine.

Command line interface framework Go framework for rapid command line application development

Ulrich Kautz 108 May 24, 2021
GitHub’s official command line tool

GitHub CLI gh is GitHub on the command line. It brings pull requests, issues, and other GitHub concepts to the terminal next to where you are already

GitHub CLI 24.1k Jul 21, 2021
FireFly Command Line Interface (CLI)

FireFly CLI The FireFly CLI can be used to create a local FireFly stacks for offline development of blockchain apps. This allows developers to rapidly

Kaleido 0 Jul 26, 2021
cross platform command line tool to list, notify and book vaccine using cowin API

Command line tool to List and Book Vaccine cowin-cli is a simple cli tool to book vaccines and list centers using the COWIN API. It also supports auto

Anoop S 35 Jul 1, 2021
Kong is a command-line parser for Go

Kong is a command-line parser for Go Introduction Help Help as a user of a Kong application Defining help in Kong Command handling Switch on the comma

Alec Thomas 589 Jul 24, 2021
A simple, fast, and fun package for building command line apps in Go

cli cli is a simple, fast, and fun package for building command line apps in Go. The goal is to enable developers to write fast and distributable comm

null 16.2k Jul 17, 2021
Simple and complete API for building command line applications in Go

Simple and complete API for building command line applications in Go Module cli provides a simple, fast and complete API for building command line app

teris.io 89 Jul 15, 2021