docopt.go: github.com/docopt/docopt.go Index | Examples | Files | Directories

package docopt

import "github.com/docopt/docopt.go"

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

Package Files

doc.go docopt.go error.go opts.go pattern.go token.go

Variables

var DefaultParser = &Parser{
    HelpHandler:   PrintHelpAndExit,
    OptionsFirst:  false,
    SkipHelpFlags: false,
}
var NoHelpHandler = func(err error, usage string) {}
var PrintHelpAndExit = func(err error, usage string) {
    if err != nil {
        fmt.Fprintln(os.Stderr, usage)
        os.Exit(1)
    } else {
        fmt.Println(usage)
        os.Exit(0)
    }
}
var PrintHelpOnly = func(err error, usage string) {
    if err != nil {
        fmt.Fprintln(os.Stderr, usage)
    } else {
        fmt.Println(usage)
    }
}

func Parse Uses

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.

type LanguageError Uses

type LanguageError struct {
    // contains filtered or unexported fields
}

LanguageError records an error with the doc string.

func (LanguageError) Error Uses

func (e LanguageError) Error() string

type Opts Uses

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 Uses

func ParseArgs(doc string, argv []string, version string) (Opts, error)

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.

Code:

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 Uses

func ParseDoc(doc string) (Opts, error)

ParseDoc parses os.Args[1:] based on the interface described in doc, using the default parser options.

func (Opts) Bind Uses

func (o Opts) Bind(v interface{}) error

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.

Code:

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

func (Opts) Bool Uses

func (o Opts) Bool(key string) (b bool, err error)

func (Opts) Float64 Uses

func (o Opts) Float64(key string) (f float64, err error)

func (Opts) Int Uses

func (o Opts) Int(key string) (i int, err error)

func (Opts) String Uses

func (o Opts) String(key string) (s string, err error)

type Parser Uses

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
}

func (*Parser) ParseArgs Uses

func (p *Parser) ParseArgs(doc string, argv []string, version string) (Opts, error)

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.

type UserError Uses

type UserError struct {
    Usage string
    // contains filtered or unexported fields
}

UserError records an error with program arguments.

func (UserError) Error Uses

func (e UserError) Error() string

Directories

PathSynopsis
examples
examples/arguments
examples/calculator
examples/config_file
examples/counted
examples/fake-git
examples/fake-git/branch
examples/fake-git/checkout
examples/fake-git/clone
examples/fake-git/push
examples/fake-git/remote
examples/naval_fate
examples/odd_even
examples/options
examples/options_shortcut
examples/quick
examples/type_assert
examples/unit_test

Package docopt imports 7 packages (graph) and is imported by 46 packages. Updated 2018-01-11. Refresh now. Tools for package owners.