Top Related Projects
Create *beautiful* command-line interfaces with Python
A Commander for modern Go CLI interactions
A simple, fast, and fun package for building command line apps in Go
CONTRIBUTIONS ONLY: A Go (golang) command line and flag parser
go command line option parser
Struct-based argument parsing in Go
Quick Overview
docopt/docopt.go is a Go implementation of the docopt language for command-line interface description. It allows developers to define command-line interfaces using a simple and intuitive syntax, which is then used to automatically generate a parser for the application's arguments.
Pros
- Easy to use and understand syntax for defining command-line interfaces
- Automatically generates help messages based on the interface description
- Supports a wide range of command-line argument patterns
- Reduces boilerplate code for parsing command-line arguments
Cons
- May have a steeper learning curve for developers unfamiliar with the docopt syntax
- Less flexible than some other command-line parsing libraries for complex use cases
- Limited customization options for generated help messages
- Not as actively maintained as some other Go command-line libraries
Code Examples
- Basic usage:
package main
import (
"fmt"
"github.com/docopt/docopt-go"
)
func main() {
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
Options:
-h --help Show this screen.
--version Show version.
--speed=<kn> Speed in knots [default: 10].
--moored Moored (anchored) mine.
--drifting Drifting mine.`
arguments, _ := docopt.ParseDoc(usage)
fmt.Println(arguments)
}
- Accessing parsed arguments:
if arguments["ship"].(bool) && arguments["new"].(bool) {
names := arguments["<name>"].([]string)
fmt.Printf("Creating new ship(s): %v\n", names)
}
- Handling options with default values:
speed := arguments["--speed"]
if speed == nil {
speed = "10"
}
fmt.Printf("Ship speed: %s knots\n", speed)
Getting Started
To use docopt in your Go project:
-
Install the package:
go get github.com/docopt/docopt-go
-
Import the package in your Go file:
import "github.com/docopt/docopt-go"
-
Define your usage string and parse arguments:
usage := `Your program description and usage information here.` arguments, _ := docopt.ParseDoc(usage)
-
Access parsed arguments using the
arguments
map.
Competitor Comparisons
Create *beautiful* command-line interfaces with Python
Pros of docopt
- Written in Python, offering better integration with Python projects
- More mature and established project with a larger community
- Supports a wider range of programming languages through ports
Cons of docopt
- May have slower performance compared to Go implementation
- Less suitable for Go projects due to language mismatch
- Potentially more complex setup for non-Python environments
Code Comparison
docopt (Python):
from docopt import docopt
if __name__ == '__main__':
arguments = docopt(__doc__, version='Naval Fate 2.0')
print(arguments)
docopt.go (Go):
import "github.com/docopt/docopt-go"
func main() {
arguments, _ := docopt.ParseDoc(usage)
fmt.Println(arguments)
}
Key Differences
- Language: docopt is written in Python, while docopt.go is implemented in Go
- Usage: docopt.go is more suitable for Go projects, offering native integration
- Performance: docopt.go may have better performance in Go environments
- Ecosystem: docopt has a larger ecosystem and more language ports available
- Maintenance: docopt has more contributors and a longer history of updates
Conclusion
Choose docopt for Python projects or when working with multiple languages. Opt for docopt.go when developing Go applications or prioritizing performance in Go environments. Both libraries provide similar functionality, with the main differences being the implementation language and ecosystem support.
A Commander for modern Go CLI interactions
Pros of Cobra
- More feature-rich, offering subcommands, flags, and shell completions
- Actively maintained with frequent updates and a large community
- Integrates well with other popular Go libraries like Viper for configuration management
Cons of Cobra
- Steeper learning curve due to more complex API and concepts
- Requires more boilerplate code to set up commands and flags
- Potentially overkill for simple CLI applications
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)
fmt.Println(arguments)
Cobra:
var rootCmd = &cobra.Command{
Use: "naval_fate",
Short: "A brief description of your application",
Long: `A longer description...`,
}
var shipCmd = &cobra.Command{
Use: "ship",
Short: "Ship related commands",
}
func init() {
rootCmd.AddCommand(shipCmd)
}
A simple, fast, and fun package for building command line apps in Go
Pros of cli
- More actively maintained with frequent updates and contributions
- Offers a wider range of features, including subcommands and middleware support
- Provides better documentation and examples for easier adoption
Cons of cli
- Steeper learning curve due to more complex API and configuration options
- Requires more boilerplate code to set up basic command-line interfaces
- May be overkill for simple CLI applications with few commands
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)
cli:
app := &cli.App{
Name: "naval-fate",
Usage: "A naval battle simulation game",
Commands: []*cli.Command{
{
Name: "ship",
Usage: "Manage ships",
Subcommands: []*cli.Command{
{
Name: "new",
Usage: "Create a new ship",
Action: func(c *cli.Context) error {
// Implementation
},
},
// More subcommands...
},
},
// More commands...
},
}
CONTRIBUTIONS ONLY: A Go (golang) command line and flag parser
Pros of kingpin
- More flexible and feature-rich, offering advanced options like custom validators and hidden flags
- Better support for subcommands and nested command structures
- Provides a more idiomatic Go API with method chaining and fluent interface
Cons of kingpin
- Slightly more verbose syntax compared to docopt's concise approach
- Requires more code to set up complex command-line interfaces
- Learning curve may be steeper for developers new to Go or command-line parsing
Code Comparison
kingpin:
var (
verbose = kingpin.Flag("verbose", "Verbose mode.").Short('v').Bool()
name = kingpin.Arg("name", "Name of user.").Required().String()
)
func main() {
kingpin.Parse()
// Use flags and arguments
}
docopt:
usage := `Usage:
myapp [options] <name>
Options:
-v --verbose Verbose mode.`
args, _ := docopt.ParseDoc(usage)
verbose := args["--verbose"].(bool)
name := args["<name>"].(string)
Both libraries offer command-line parsing capabilities, but kingpin provides a more Go-idiomatic approach with stronger typing and better support for complex command structures. docopt, on the other hand, offers a more concise and declarative syntax that may be easier for simple use cases or for developers familiar with other docopt implementations.
go command line option parser
Pros of go-flags
- More flexible and feature-rich, supporting a wider range of flag types and options
- Better performance, especially for complex command-line interfaces
- Actively maintained with regular updates and improvements
Cons of go-flags
- Steeper learning curve due to more complex API and configuration options
- Requires more code to set up compared to docopt.go's simpler approach
- May be overkill for simple command-line applications
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)
docopt.go example:
usage := `Usage: example [-v...] -n <name>
Options:
-v, --verbose Show verbose debug information
-n, --name A name`
args, _ := docopt.ParseDoc(usage)
Both libraries offer command-line argument parsing for Go applications, but go-flags provides more advanced features and flexibility at the cost of increased complexity. docopt.go focuses on simplicity and ease of use, making it suitable for smaller projects or those requiring a quick implementation. The choice between the two depends on the specific needs of your project and the level of control you require over command-line argument parsing.
Struct-based argument parsing in Go
Pros of go-arg
- More idiomatic Go approach using struct tags
- Better type safety and compile-time checks
- Easier to integrate with existing Go code and structures
Cons of go-arg
- Less flexible for complex command-line interfaces
- Requires more Go-specific knowledge to use effectively
- May require more code for advanced use cases
Code Comparison
go-arg:
type Args struct {
Foo string `arg:"required,help:foo option"`
Bar int
}
func main() {
var args Args
arg.MustParse(&args)
}
docopt:
usage := `Usage: example [--foo=<value>] [--bar=<value>]`
arguments, _ := docopt.ParseDoc(usage)
foo := arguments["--foo"].(string)
bar, _ := arguments["--bar"].(int)
go-arg uses struct tags to define command-line arguments, providing a more Go-native approach. docopt relies on a usage string to define the interface, which can be more flexible but less type-safe. go-arg offers better integration with Go's type system, while docopt provides a more language-agnostic solution that may be easier for non-Go developers to understand.
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual CopilotREADME
docopt-go
An implementation of docopt in the Go programming language.
docopt helps you create beautiful command-line interfaces easily:
package main
import (
"fmt"
"github.com/docopt/docopt-go"
)
func main() {
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
Options:
-h --help Show this screen.
--version Show version.
--speed=<kn> Speed in knots [default: 10].
--moored Moored (anchored) mine.
--drifting Drifting mine.`
arguments, _ := docopt.ParseDoc(usage)
fmt.Println(arguments)
}
docopt parses command-line arguments based on a help message. Don't write parser code: a good help message already has all the necessary information in it.
Installation
â Use the alias "docopt-go". To use docopt in your Go code:
import "github.com/docopt/docopt-go"
To install docopt in your $GOPATH
:
$ go get github.com/docopt/docopt-go
API
Given a conventional command-line help message, docopt processes the arguments. See https://github.com/docopt/docopt#help-message-format for a description of the help message format.
This package exposes three different APIs, depending on the level of control required. The first, simplest way to parse your docopt usage is to just call:
docopt.ParseDoc(usage)
This will use os.Args[1:]
as the argv slice, and use the default parser options. If you want to provide your own version string and args, then use:
docopt.ParseArgs(usage, argv, "1.2.3")
If the last parameter (version) is a non-empty string, it will be printed when --version
is given in the argv slice. Finally, we can instantiate our own docopt.Parser
which gives us control over how things like help messages are printed and whether to exit after displaying usage messages, etc.
parser := &docopt.Parser{
HelpHandler: docopt.PrintHelpOnly,
OptionsFirst: true,
}
opts, err := parser.ParseArgs(usage, argv, "")
In particular, setting your own custom HelpHandler
function makes unit testing your own docs with example command line invocations much more enjoyable.
All three of these return a map of option names to the values parsed from argv, and an error or nil. You can get the values using the helpers, or just treat it as a regular map:
flag, _ := opts.Bool("--flag")
secs, _ := opts.Int("<seconds>")
Additionally, you can Bind
these to a struct, assigning option values to the
exported fields of that struct, all at once.
var config struct {
Command string `docopt:"<cmd>"`
Tries int `docopt:"-n"`
Force bool // Gets the value of --force
}
opts.Bind(&config)
More documentation is available at godoc.org.
Unit Testing
Unit testing your own usage docs is recommended, so you can be sure that for a given command line invocation, the expected options are set. An example of how to do this is in the examples folder.
Tests
All tests from the Python version are implemented and passing at Travis CI. New language-agnostic tests have been added to test_golang.docopt.
To run tests for docopt-go, use go test
.
Top Related Projects
Create *beautiful* command-line interfaces with Python
A Commander for modern Go CLI interactions
A simple, fast, and fun package for building command line apps in Go
CONTRIBUTIONS ONLY: A Go (golang) command line and flag parser
go command line option parser
Struct-based argument parsing in Go
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual Copilot