Documentation ¶
Overview ¶
Package docopt parses command-line arguments based on a help message.
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)
Index ¶
Examples ¶
Constants ¶
This section is empty.
Variables ¶
var DefaultParser = &Parser{ HelpHandler: PrintHelpAndExit, OptionsFirst: false, SkipHelpFlags: false, }
var NoHelpHandler = func(err error, usage string) {}
Functions ¶
func Parse
deprecated
func Parse(doc string, argv []string, help bool, version string, optionsFirst bool, exit ...bool) (map[string]interface{}, error)
Deprecated: Parse is provided for backward compatibility with the original docopt.go package. Please rather make use of ParseDoc, ParseArgs, or use your own custom Parser.
Types ¶
type LanguageError ¶
type LanguageError struct {
// contains filtered or unexported fields
}
LanguageError records an error with the doc string.
func (LanguageError) Error ¶
func (e LanguageError) Error() string
type Opts ¶
type Opts map[string]interface{}
Opts is a map of command line options to their values, with some convenience methods for value type conversion (bool, float64, int, string). For example, to get an option value as an int:
opts, _ := docopt.ParseDoc("Usage: sleep <seconds>") secs, _ := opts.Int("<seconds>")
Additionally, Opts.Bind allows you easily populate a struct's fields with the values of each option value. See below for examples.
Lastly, you can still treat Opts as a regular map, and do any type checking and conversion that you want to yourself. For example:
if s, ok := opts["<binary>"].(string); ok { if val, err := strconv.ParseUint(s, 2, 64); err != nil { ... } }
Note that any non-boolean option / flag will have a string value in the underlying map.
func ParseArgs ¶
ParseArgs parses custom arguments based on the interface described in doc. If you provide a non-empty version string, then this will be displayed when the --version flag is found. This method uses the default parser options.
Example ¶
usage := `Usage: example tcp [<host>...] [--force] [--timeout=<seconds>] example serial <port> [--baud=<rate>] [--timeout=<seconds>] example --help | --version` // Parse the command line `example tcp 127.0.0.1 --force` argv := []string{"tcp", "127.0.0.1", "--force"} opts, _ := ParseArgs(usage, argv, "0.1.1rc") // Sort the keys of the options map var keys []string for k := range opts { keys = append(keys, k) } sort.Strings(keys) // Print the option keys and values for _, k := range keys { fmt.Printf("%9s %v\n", k, opts[k]) }
Output: --baud <nil> --force true --help false --timeout <nil> --version false <host> [127.0.0.1] <port> <nil> serial false tcp true
func ParseDoc ¶
ParseDoc parses os.Args[1:] based on the interface described in doc, using the default parser options.
func (Opts) Bind ¶
Bind populates the fields of a given struct with matching option values. Each key in Opts will be mapped to an exported field of the struct pointed to by `v`, as follows:
abc int // Unexported field, ignored Abc string // Mapped from `--abc`, `<abc>`, or `abc` // (case insensitive) A string // Mapped from `-a`, `<a>` or `a` // (case insensitive) Abc int `docopt:"XYZ"` // Mapped from `XYZ` Abc bool `docopt:"-"` // Mapped from `-` Abc bool `docopt:"-x,--xyz"` // Mapped from `-x` or `--xyz` // (first non-zero value found)
Tagged (annotated) fields will always be mapped first. If no field is tagged with an option's key, Bind will try to map the option to an appropriately named field (as above).
Bind also handles conversion to bool, float, int or string types.
Example ¶
usage := `Usage: example tcp [<host>...] [--force] [--timeout=<seconds>] example serial <port> [--baud=<rate>] [--timeout=<seconds>] example --help | --version` // Parse the command line `example serial 443 --baud=9600` argv := []string{"serial", "443", "--baud=9600"} opts, _ := ParseArgs(usage, argv, "0.1.1rc") var conf struct { Tcp bool Serial bool Host []string Port int Force bool Timeout int Baud int } opts.Bind(&conf) if conf.Serial { fmt.Printf("port: %d, baud: %d", conf.Port, conf.Baud) }
Output: port: 443, baud: 9600
type Parser ¶
type Parser struct { // HelpHandler is called when we encounter bad user input, or when the user // asks for help. // By default, this calls os.Exit(0) if it handled a built-in option such // as -h, --help or --version. If the user errored with a wrong command or // options, we exit with a return code of 1. HelpHandler func(err error, usage string) // OptionsFirst requires that option flags always come before positional // arguments; otherwise they can overlap. OptionsFirst bool // SkipHelpFlags tells the parser not to look for -h and --help flags and // call the HelpHandler. SkipHelpFlags bool }