Convert Figma logo to code with AI

spf13 logocobra

A Commander for modern Go CLI interactions

37,918
2,841
37,918
291

Top Related Projects

1,730

A Go library for implementing command-line interfaces.

3,493

CONTRIBUTIONS ONLY: A Go (golang) command line and flag parser

go command line option parser

A command-line arguments parser that will make you smile.

1,981

Struct-based argument parsing in Go

Quick Overview

Cobra is a powerful library for creating modern CLI applications in Go. It provides a simple interface to create powerful modern CLI applications, as well as a program to generate applications and command files. Cobra is used in many Go projects and is one of the most popular CLI libraries in the Go ecosystem.

Pros

  • Easy to use and intuitive API for creating complex command-line interfaces
  • Supports nested subcommands, flags, and positional arguments
  • Automatic generation of help and usage documentation
  • Integrates well with other popular Go libraries like viper for configuration management

Cons

  • Learning curve for more advanced features and customizations
  • May be overkill for very simple CLI applications
  • Limited built-in support for interactive prompts (though can be extended)
  • Some users report occasional issues with flag parsing in complex scenarios

Code Examples

  1. Creating a simple root command:
package main

import (
    "fmt"
    "github.com/spf13/cobra"
)

func main() {
    var rootCmd = &cobra.Command{
        Use:   "app",
        Short: "A brief description of your application",
        Run: func(cmd *cobra.Command, args []string) {
            fmt.Println("Hello, Cobra!")
        },
    }

    rootCmd.Execute()
}
  1. Adding a flag to a command:
var name string

rootCmd.Flags().StringVarP(&name, "name", "n", "", "Your name")
rootCmd.Run = func(cmd *cobra.Command, args []string) {
    if name != "" {
        fmt.Printf("Hello, %s!\n", name)
    } else {
        fmt.Println("Hello, World!")
    }
}
  1. Creating a subcommand:
var versionCmd = &cobra.Command{
    Use:   "version",
    Short: "Print the version number",
    Run: func(cmd *cobra.Command, args []string) {
        fmt.Println("Version 1.0")
    },
}

rootCmd.AddCommand(versionCmd)

Getting Started

To start using Cobra in your Go project:

  1. Install Cobra:

    go get -u github.com/spf13/cobra@latest
    
  2. Initialize a new Cobra-based application:

    cobra-cli init myapp
    cd myapp
    
  3. Add a new command:

    cobra-cli add serve
    
  4. Build and run your application:

    go build
    ./myapp
    

This will create a basic Cobra application structure with a root command and a "serve" subcommand. You can now customize the commands and add your application logic.

Competitor Comparisons

1,730

A Go library for implementing command-line interfaces.

Pros of cli

  • Simpler API with less boilerplate code
  • Better suited for smaller projects or quick CLI prototypes
  • Easier to understand and implement for beginners

Cons of cli

  • Less feature-rich compared to Cobra
  • Limited built-in support for flags and command nesting
  • Fewer advanced features like shell completions or man page generation

Code Comparison

cli:

c := cli.NewCLI("app", "1.0.0")
c.Args = os.Args[1:]
c.Commands = map[string]cli.CommandFactory{
    "foo": fooCommandFactory,
}

Cobra:

var rootCmd = &cobra.Command{
    Use:   "app",
    Short: "A brief description of your application",
}
func Execute() {
    cobra.CheckErr(rootCmd.Execute())
}

Summary

cli is a lightweight and straightforward library for building command-line interfaces in Go. It's ideal for smaller projects or rapid prototyping. Cobra, on the other hand, offers a more comprehensive set of features and is better suited for larger, more complex CLI applications. Cobra provides built-in support for nested commands, flags, and advanced features like shell completions and man page generation. While cli has a simpler API and is easier to get started with, it may lack some of the advanced functionality that Cobra offers out of the box.

3,493

CONTRIBUTIONS ONLY: A Go (golang) command line and flag parser

Pros of Kingpin

  • More concise API, requiring less boilerplate code
  • Built-in support for environment variables
  • Easier to define mutually exclusive flags

Cons of Kingpin

  • Less active development and community support
  • Fewer advanced features compared to Cobra (e.g., shell completions)
  • Limited built-in documentation generation capabilities

Code Comparison

Kingpin:

app := kingpin.New("chat", "A command-line chat application")
send := app.Command("send", "Send a message")
message := send.Arg("message", "Message to send").Required().String()

Cobra:

var rootCmd = &cobra.Command{
    Use:   "chat",
    Short: "A command-line chat application",
}
var sendCmd = &cobra.Command{
    Use:   "send [message]",
    Short: "Send a message",
    Args:  cobra.ExactArgs(1),
}

Both Cobra and Kingpin are popular command-line interface (CLI) libraries for Go. Cobra is more widely used and offers a richer feature set, including automatic help generation and shell completions. Kingpin, on the other hand, provides a more streamlined API and built-in support for environment variables. The choice between the two depends on the specific requirements of your project and personal preference for API style.

go command line option parser

Pros of go-flags

  • More flexible tag-based approach for defining flags
  • Supports automatic generation of man pages
  • Allows for more complex flag types and custom parsing

Cons of go-flags

  • Less intuitive for newcomers compared to Cobra's command-based structure
  • Lacks built-in support for persistent flags across subcommands
  • Documentation is not as extensive as Cobra's

Code Comparison

go-flags example:

type Options struct {
    Verbose []bool `short:"v" long:"verbose" description:"Show verbose debug information"`
    Name    string `short:"n" long:"name" description:"A name" required:"true"`
}

var opts Options
_, err := flags.Parse(&opts)

Cobra example:

var rootCmd = &cobra.Command{
    Use:   "app",
    Short: "A brief description of your application",
    Run: func(cmd *cobra.Command, args []string) {
        // Your logic here
    },
}

rootCmd.PersistentFlags().BoolP("verbose", "v", false, "verbose output")
rootCmd.Flags().StringP("name", "n", "", "A name")
rootCmd.MarkFlagRequired("name")

Both libraries offer powerful CLI parsing capabilities, but Cobra provides a more structured approach with its command-based system, while go-flags offers more flexibility in flag definition through struct tags.

A command-line arguments parser that will make you smile.

Pros of docopt.go

  • Simpler syntax for defining command-line interfaces
  • Automatically generates help messages based on the usage pattern
  • Supports a wide range of argument types and patterns out of the box

Cons of docopt.go

  • Less flexible for complex command structures
  • Limited built-in support for subcommands
  • Fewer additional features compared to Cobra (e.g., shell completions, man page generation)

Code Comparison

docopt.go:

usage := `Naval Fate.

Usage:
  naval_fate ship new <name>...
  naval_fate ship <name> move <x> <y> [--speed=<kn>]
  naval_fate ship shoot <x> <y>
  naval_fate mine (set|remove) <x> <y> [--moored|--drifting]
  naval_fate -h | --help
  naval_fate --version`

arguments, _ := docopt.Parse(usage, nil, true, "Naval Fate 2.0", false)

Cobra:

var rootCmd = &cobra.Command{
  Use:   "naval_fate",
  Short: "A brief description of your application",
  Long: `A longer description...`,
}

func init() {
  rootCmd.AddCommand(shipCmd)
  rootCmd.AddCommand(mineCmd)
}
1,981

Struct-based argument parsing in Go

Pros of go-arg

  • Simpler and more lightweight, with a focus on ease of use
  • Automatically generates help text based on struct tags
  • Supports nested structs for organizing complex command-line options

Cons of go-arg

  • Less feature-rich compared to Cobra's extensive functionality
  • Limited support for subcommands and complex command hierarchies
  • Smaller community and ecosystem around the project

Code Comparison

go-arg:

type Args struct {
    Foo string `arg:"required,-f" help:"foo option"`
    Bar int
}

func main() {
    var args Args
    arg.MustParse(&args)
}

Cobra:

var rootCmd = &cobra.Command{
    Use:   "app",
    Short: "A brief description of your application",
    Run: func(cmd *cobra.Command, args []string) {
        // Your logic here
    },
}

func main() {
    rootCmd.Execute()
}

Both go-arg and Cobra are popular command-line argument parsing libraries for Go. go-arg offers a simpler approach, using struct tags to define arguments and automatically generate help text. It's lightweight and easy to use for straightforward CLI applications. Cobra, on the other hand, provides a more comprehensive solution with support for complex command hierarchies, persistent flags, and a rich set of features. It's better suited for larger applications with multiple subcommands and advanced CLI requirements. The choice between the two depends on the complexity of your application and your specific needs.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

cobra logo

Cobra is a library for creating powerful modern CLI applications.

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

Go Reference Go Report Card Slack

Overview

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

Cobra provides:

  • Easy subcommand-based CLIs: app server, app fetch, etc.
  • Fully POSIX-compliant flags (including short & long versions)
  • Nested subcommands
  • Global, local and cascading flags
  • Intelligent suggestions (app srver... did you mean app server?)
  • Automatic help generation for commands and flags
  • Grouping help for subcommands
  • Automatic help flag recognition of -h, --help, etc.
  • Automatically generated shell autocomplete for your application (bash, zsh, fish, powershell)
  • Automatically generated man pages for your application
  • Command aliases so you can change things without breaking them
  • The flexibility to define your own help, usage, etc.
  • Optional seamless integration with viper for 12-factor apps

Concepts

Cobra is built on a structure of commands, arguments & flags.

Commands represent actions, Args are things and Flags are modifiers for those actions.

The best applications read like sentences when used, and as a result, users intuitively know how to interact with them.

The pattern to follow is APPNAME VERB NOUN --ADJECTIVE or APPNAME COMMAND ARG --FLAG.

A few good real world examples may better illustrate this point.

In the following example, 'server' is a command, and 'port' is a flag:

hugo server --port=1313

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

git clone URL --bare

Commands

Command is the central point of the application. Each interaction that the application supports will be contained in a Command. A command can have children commands and optionally run an action.

In the example above, 'server' is the command.

More about cobra.Command

Flags

A flag is a way to modify the behavior of a command. Cobra supports fully POSIX-compliant flags as well as the Go flag package. A Cobra command can define flags that persist through to children commands and flags that are only available to that command.

In the example above, 'port' is the flag.

Flag functionality is provided by the pflag library, a fork of the flag standard library which maintains the same interface while adding POSIX compliance.

Installing

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

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

Next, include Cobra in your application:

import "github.com/spf13/cobra"

Usage

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

It can be installed by running:

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

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

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

License

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