commander

package module
v0.6.0 Latest Latest
Warning

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

Go to latest
Published: Mar 10, 2017 License: MIT Imports: 8 Imported by: 38

README

go-commander

Build Status License Go Report Card

v0.6.0 status

The solution for Go command-line interfaces, drive by <docopt>, inspired by <commander>

Installation

To use commander in your Go code:

import "github.com/WindomZ/go-commander"

To install commander according to your $GOPATH:

go get github.com/WindomZ/go-commander

Examples

Quick example

Such as the following help message

Usage:
  quick_example tcp <host> <port> [--timeout=<seconds>]
  quick_example serial <port> [--baud=9600] [--timeout=<seconds>]
  quick_example -h | --help
  quick_example --version

To coding with go-commander just like this:

import "github.com/WindomZ/go-commander"

// quick_example
commander.Program.
	Command("quick_example").
	Version("0.1.1rc")

// quick_example tcp <host> <port> [--timeout=<seconds>]
commander.Program.
	Command("tcp <host> <port>").
	Option("--timeout=<seconds>")

// quick_example serial <port> [--baud=9600] [--timeout=<seconds>]
commander.Program.
	Command("serial <port>").
	Option("--baud=9600").
	Option("--timeout=<seconds>")
Counted example

Such as the following help message

Usage:
  counted_example [-v...]
  counted_example go [go]
  counted_example (--path=<path>)...
  counted_example <file> <file>
  counted_example -h | --help
  counted_example --version

To coding with go-commander just like this:

import "github.com/WindomZ/go-commander"

// counted_example -v...
commander.Program.
	Command("counted_example").
	Option("-v...")

// counted_example go [go]
commander.Program.
	Command("go [go]")

// counted_example (--path=<path>)...
commander.Program.
	LineOption("(--path=<path>)...")

// counted_example <file> <file>
commander.Program.
	LineArgument("<file> <file>")
Calculator example

Such as the following help message

simple calculator example

Usage:
  calculator_example <value> ( ( + | - | * | / ) <value> )...
  calculator_example <function> <value> [( , <value> )]...
  calculator_example -h | --help
  calculator_example --version

Examples:
  calculator_example 1 + 2 + 3 + 4 + 5
  calculator_example 1 + 2 '*' 3 / 4 - 5    # note quotes around '*'
  calculator_example sum 10 , 20 , 30 , 40

To coding with go-commander just like this:

import "github.com/WindomZ/go-commander"

// calculator_example
commander.Program.
	Command("calculator_example").
	Version("0.0.1").
	Description("simple calculator example")

// calculator_example <value> ( ( + | - | * | / ) <value> )...
commander.Program.
	LineArgument("<value> ( ( + | - | * | / ) <value> )...").
	Action(func(c *commander.Context) error {
		if c.Contain("<function>") {
			return nil
		}
		var result int
		values := c.Doc.GetStrings("<value>")
		for index, value := range values {
			if i, err := strconv.Atoi(value); err != nil {
			} else if index == 0 {
				result = i
			} else {
				switch c.Args.Get(index*2 - 1) {
				case "+":
					result += i
				case "-":
					result -= i
				case "*":
					result *= i
				case "/":
					result /= i
				}
			}
		}
		fmt.Println(c.Args.String(), "=", result)
		return nil
	})

// calculator_example <function> <value> [( , <value> )]...
commander.Program.
	LineArgument("<function> <value> [( , <value> )]...").
	Action(func(c *commander.Context) error {
		var result int
		switch c.Doc.GetString("<function>") {
		case "sum":
			values := c.Doc.GetStrings("<value>")
			for _, value := range values {
				if i, err := strconv.Atoi(value); err == nil {
					result += i
				}
			}
		}
		fmt.Println(c.Args.String(), "=", result)
		return nil
	})

// Examples: ...
commander.Program.
	Annotation(
		"Examples",
		[]string{
			"calculator_example 1 + 2 + 3 + 4 + 5",
			"calculator_example 1 + 2 '*' 3 / 4 - 5    # note quotes around '*'",
			"calculator_example sum 10 , 20 , 30 , 40",
		},
	)

Get the terminal output:

calculator_example 1 + 2 + 3 + 4 + 5
# output: 15

calculator_example 1 + 2 '*' 3 / 4 - 5
# output: -3

calculator_example sum 10 , 20 , 30 , 40
# output: 100

License

The MIT License

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrNil     error = errors.New("error nil")
	ErrCommand       = errors.New("error command")
	ErrOption        = errors.New("error option")
)

Functions

func ContainArgument

func ContainArgument(str string) (ok bool)

ContainArgument str contain docopt argument format

func ContainCommand

func ContainCommand(str string) (ok bool)

ContainCommand str contain docopt command format

func ContainOption

func ContainOption(str string) (ok bool)

ContainOption str contain docopt option format

func RegexpArgument

func RegexpArgument(str string) []string

RegexpArgument Regular screening out docopt arguments

func RegexpCommand

func RegexpCommand(str string) []string

RegexpCommand Regular screening out docopt commands

func RegexpOption

func RegexpOption(str string) []string

RegexpOption Regular screening out docopt options

Types

type Action

type Action func(c *Context) Result // default internal function

The following are ACTION functions, chose one if you like it.

type Action1

type Action1 func(c *Context) error

type Action2

type Action2 func(c *Context)

type Action3

type Action3 func(m map[string]interface{}) error

type Argument

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

Argument Implementation of command line parameter

func (Argument) Name

func (a Argument) Name() string

func (Argument) OptionString

func (a Argument) OptionString() string

func (Argument) UsageString

func (a Argument) UsageString() string

type Arguments

type Arguments []*Argument

Arguments Implementation of command line parameters

func (Arguments) Get

func (a Arguments) Get() (r []string)

func (Arguments) IsEmpty

func (a Arguments) IsEmpty() bool

func (Arguments) OptionsString

func (a Arguments) OptionsString() (r []string)

func (*Arguments) Set

func (a *Arguments) Set(usage string)

func (Arguments) UsagesString

func (a Arguments) UsagesString() (r []string)

type Command

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

Command Command line command implementation

func (*Command) Action

func (c *Command) Action(action interface{}, keys ...[]string) Commander

func (*Command) Annotation

func (c *Command) Annotation(title string, contents []string) Commander

func (*Command) Command

func (c *Command) Command(usage string, args ...interface{}) Commander

func (*Command) Description

func (c *Command) Description(desc string) Commander

func (Command) GetHelpMessage

func (c Command) GetHelpMessage() string

func (*Command) Line added in v0.6.0

func (c *Command) Line(usage string, args ...interface{}) *Command

func (*Command) LineArgument

func (c *Command) LineArgument(usage string, args ...interface{}) Commander

func (*Command) LineOption

func (c *Command) LineOption(usage string, args ...interface{}) Commander

func (Command) Name

func (c Command) Name() string

func (Command) Names

func (c Command) Names() []string

func (*Command) Option

func (c *Command) Option(usage string, args ...interface{}) Commander

func (Command) OptionsString

func (c Command) OptionsString() (r []string)

func (Command) Parse

func (c Command) Parse(args ...[]string) (*Context, error)

func (Command) ShowHelpMessage

func (c Command) ShowHelpMessage() string

func (*Command) Usage added in v0.6.0

func (c *Command) Usage(usage string, args ...interface{}) Commander

func (Command) UsagesString

func (c Command) UsagesString() (r []string)

func (Command) Valid

func (c Command) Valid() bool

func (*Command) Version

func (c *Command) Version(ver string) Commander

type Commander

type Commander interface {
	Version(ver string) Commander
	Description(desc string) Commander
	Annotation(title string, contents []string) Commander
	Action(action interface{}, keys ...[]string) Commander
	Command(usage string, args ...interface{}) Commander
	Option(usage string, args ...interface{}) Commander
	LineArgument(usage string, args ...interface{}) Commander
	LineOption(usage string, args ...interface{}) Commander
	UsagesString() []string
	OptionsString() []string
	GetHelpMessage() string
	ShowHelpMessage() string
	Parse(argv ...[]string) (*Context, error)
}

Commander Command line implementation

var Program Commander = newCommander()

type Commands

type Commands []*Command

Commands Command line commands implementation

func (Commands) OptionsString

func (c Commands) OptionsString() (r []string)

type Context

type Context struct {
	Args ContextArgs `json:"arguments"`
	Doc  DocoptMap   `json:"docopt"`
}

Context

func (Context) Contain

func (c Context) Contain(key string) bool

func (Context) String

func (c Context) String() string

type ContextArgs

type ContextArgs []string

func (ContextArgs) Get

func (c ContextArgs) Get(index int) string

func (ContextArgs) String

func (c ContextArgs) String() string

func (ContextArgs) StringSeparator added in v0.6.0

func (c ContextArgs) StringSeparator(sep string, offsets ...int) string

type DocoptMap

type DocoptMap map[string]interface{}

DocoptMap docopt returns a map of option names to the values

func Parse

func Parse(doc string, argv []string, help bool, version string,
	optionsFirst bool, exit ...bool) (DocoptMap, error)

func (DocoptMap) Contain

func (d DocoptMap) Contain(key string) bool

func (DocoptMap) Get

func (d DocoptMap) Get(key string) interface{}

func (DocoptMap) GetBool

func (d DocoptMap) GetBool(key string) (bool, bool)

func (DocoptMap) GetFloat

func (d DocoptMap) GetFloat(key string) (float32, bool)

func (DocoptMap) GetFloat64

func (d DocoptMap) GetFloat64(key string) (float64, bool)

func (DocoptMap) GetInt

func (d DocoptMap) GetInt(key string) (int, bool)

func (DocoptMap) GetInt64

func (d DocoptMap) GetInt64(key string) (int64, bool)

func (DocoptMap) GetMustBool

func (d DocoptMap) GetMustBool(key string) bool

func (DocoptMap) GetString

func (d DocoptMap) GetString(key string) string

func (DocoptMap) GetStrings

func (d DocoptMap) GetStrings(key string) []string

func (DocoptMap) Map

func (d DocoptMap) Map() map[string]interface{}

func (DocoptMap) String

func (d DocoptMap) String() string

type ErrFunc

type ErrFunc func(err error, obj interface{})

type Option

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

Option

func (*Option) Action

func (a *Option) Action(action interface{}, keys ...[]string)

Action set executive function to actor.action and actor.musts action like: func(c *Context) Result

func(c *Context) error
func(c *Context)
func(m map[string]interface{}) error

func (Option) IsOptional

func (o Option) IsOptional() bool

func (Option) IsRequired

func (o Option) IsRequired() bool

func (Option) Names

func (o Option) Names() []string

func (Option) OptionString

func (o Option) OptionString() (s string)

func (Option) UsageString

func (o Option) UsageString(ones ...bool) (s string)

func (Option) Valid

func (o Option) Valid() bool

type Options

type Options []*Option

func (Options) IsEmpty

func (o Options) IsEmpty() bool

func (Options) OptionsString

func (o Options) OptionsString() (r []string)

func (Options) UsagesString

func (o Options) UsagesString(ones ...bool) (r []string)

type Result

type Result interface {
	Code() int
	Error() error
	ErrorString() string
	Break() bool
}
var (
	ResultPass  Result = &ResultCode{}
	ResultBreak        = &ResultCode{_break: true}
)

func NewResult

func NewResult(text string) Result

func NewResultCode

func NewResultCode(code int, text ...string) Result

func NewResultError

func NewResultError(err error, codes ...int) Result

type ResultCode

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

func (ResultCode) Break

func (e ResultCode) Break() bool

func (ResultCode) Code

func (e ResultCode) Code() int

func (ResultCode) Error

func (e ResultCode) Error() error

func (ResultCode) ErrorString

func (e ResultCode) ErrorString() string

Directories

Path Synopsis
examples
counted_example command
naval_fate command
quick_example command

Jump to

Keyboard shortcuts

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