docopt

package module
v0.0.0-...-ee0de3b Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jan 11, 2018 License: MIT Imports: 7 Imported by: 83

README

docopt-go

Build Status Coverage Status GoDoc

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.

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

View Source
var DefaultParser = &Parser{
	HelpHandler:   PrintHelpAndExit,
	OptionsFirst:  false,
	SkipHelpFlags: false,
}
View Source
var NoHelpHandler = func(err error, usage string) {}
View Source
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)
	}
}
View Source
var PrintHelpOnly = func(err error, usage string) {
	if err != nil {
		fmt.Fprintln(os.Stderr, usage)
	} else {
		fmt.Println(usage)
	}
}

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

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.

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

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

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.

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

func (Opts) Bool

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

func (Opts) Float64

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

func (Opts) Int

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

func (Opts) String

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

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
}

func (*Parser) ParseArgs

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

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

UserError records an error with program arguments.

func (UserError) Error

func (e UserError) Error() string

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL