flags

package module
v0.0.0-...-5388f80 Latest Latest
Warning

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

Go to latest
Published: Dec 18, 2014 License: BSD-3-Clause Imports: 15 Imported by: 7

README

go-flags: a go library for parsing command line arguments

This library provides similar functionality to the builtin flag library of go, but provides much more functionality and nicer formatting. From the documentation:

Package flags provides an extensive command line option parser. The flags package is similar in functionality to the go builtin flag package but provides more options and uses reflection to provide a convenient and succinct way of specifying command line options.

Supported features:

  • Options with short names (-v)
  • Options with long names (--verbose)
  • Options with and without arguments (bool v.s. other type)
  • Options with optional arguments and default values
  • Multiple option groups each containing a set of options
  • Generate and print well-formatted help message
  • Passing remaining command line arguments after -- (optional)
  • Ignoring unknown command line options (optional)
  • Supports -I/usr/include -I=/usr/include -I /usr/include option argument specification
  • Supports multiple short options -aux
  • Supports all primitive go types (string, int{8..64}, uint{8..64}, float)
  • Supports same option multiple times (can store in slice or last option counts)
  • Supports maps
  • Supports function callbacks

The flags package uses structs, reflection and struct field tags to allow users to specify command line options. This results in very simple and consise specification of your application options. For example:

type Options struct {
    Verbose []bool `short:"v" long:"verbose" description:"Show verbose debug information"`
}

This specifies one option with a short name -v and a long name --verbose. When either -v or --verbose is found on the command line, a 'true' value will be appended to the Verbose field. e.g. when specifying -vvv, the resulting value of Verbose will be {[true, true, true]}.

Slice options work exactly the same as primitive type options, except that whenever the option is encountered, a value is appended to the slice.

Map options from string to primitive type are also supported. On the command line, you specify the value for such an option as key:value. For example

type Options struct {
    AuthorInfo string[string] `short:"a"`
}

Then, the AuthorInfo map can be filled with something like -a name:Jesse -a "surname:van den Kieboom".

Available field tags:

  • short: the short name of the option (single character)
  • long: the long name of the option
  • description: the description of the option (optional)
  • optional: whether an argument of the option is optional (optional)
  • default: the default argument value if the option occurs without an argument (optional)
  • base: a base used to convert strings to integer values (optional)
  • value-name: the name of the argument value (to be shown in the help, optional)

Either short: or long: must be specified to make the field eligible as an option.

Example:

var opts struct {
	// Slice of bool will append 'true' each time the option
	// is encountered (can be set multiple times, like -vvv)
	Verbose []bool `short:"v" long:"verbose" description:"Show verbose debug information"`

	// Example of automatic marshalling to desired type (uint)
	Offset uint `long:"offset" description:"Offset"`

	// Example of a callback, called each time the option is found.
	Call func(string) `short:"c" description:"Call phone number"`
}

// Callback which will invoke callto:<argument> to call a number.
// Note that this works just on OS X (and probably only with
// Skype) but it shows the idea.
opts.Call = func(num string) {
	cmd := exec.Command("open", "callto:" + num)
	cmd.Start()
	cmd.Process.Release()
}

// Parse flags
args, err := flags.Parse(&opts)

if err != nil {
	os.Exit(1)
}

fmt.Printf("Verbosity: %d\n", len(opts.Verbose))
fmt.Printf("Offset: %d\n", opts.Offset)
fmt.Printf("Remaining args: %s\n", strings.Join(args, " "))

// Output: Verbosity: 0
// Offset: 0
// Remaining args:

More information can be found in the godocs: http://go.pkgdoc.org/github.com/jessevdk/go-flags

Documentation

Overview

Package flags provides an extensive command line option parser. The flags package is similar in functionality to the go builtin flag package but provides more options and uses reflection to provide a convenient and succinct way of specifying command line options.

Supported features:

Options with short names (-v)
Options with long names (--verbose)
Options with and without arguments (bool v.s. other type)
Options with optional arguments and default values
Multiple option groups each containing a set of options
Generate and print well-formatted help message
Passing remaining command line arguments after -- (optional)
Ignoring unknown command line options (optional)
Supports -I/usr/include -I=/usr/include -I /usr/include option argument specification
Supports multiple short options -aux
Supports all primitive go types (string, int{8..64}, uint{8..64}, float)
Supports same option multiple times (can store in slice or last option counts)
Supports maps
Supports function callbacks

The flags package uses structs, reflection and struct field tags to allow users to specify command line options. This results in very simple and consise specification of your application options. For example:

type Options struct {
    Verbose []bool `short:"v" long:"verbose" description:"Show verbose debug information"`
}

This specifies one option with a short name -v and a long name --verbose. When either -v or --verbose is found on the command line, a 'true' value will be appended to the Verbose field. e.g. when specifying -vvv, the resulting value of Verbose will be {[true, true, true]}.

Slice options work exactly the same as primitive type options, except that whenever the option is encountered, a value is appended to the slice.

Map options from string to primitive type are also supported. On the command line, you specify the value for such an option as key:value. For example

type Options struct {
    AuthorInfo string[string] `short:"a"`
}

Then, the AuthorInfo map can be filled with something like -a name:Jesse -a "surname:van den Kieboom".

Available field tags:

short:       the short name of the option (single character)
long:        the long name of the option
description: the description of the option (optional)
optional:    whether an argument of the option is optional (optional)
default:     the default argument value if the option occurs without
             an argument (optional)
base:        a base used to convert strings to integer values (optional)
value-name:  the name of the argument value (to be shown in the help, optional)

Either short: or long: must be specified to make the field eligible as an option.

Example
var opts struct {
	// Slice of bool will append 'true' each time the option
	// is encountered (can be set multiple times, like -vvv)
	Verbose []bool `short:"v" long:"verbose" description:"Show verbose debug information"`

	// Example of automatic marshalling to desired type (uint)
	Offset uint `long:"offset" description:"Offset"`

	// Example of a callback, called each time the option is found.
	Call func(string) `short:"c" description:"Call phone number"`

	// Example of a required flag
	Name string `short:"n" long:"name" description:"A name" required:"true"`

	// Example of a value name
	File string `short:"f" long:"file" description:"A file" value-name:"FILE"`

	// Example of a pointer
	Ptr *int `short:"p" description:"A pointer to an integer"`

	// Example of a slice of strings
	StringSlice []string `short:"s" description:"A slice of strings"`

	// Example of a slice of pointers
	PtrSlice []*string `long:"ptrslice" description:"A slice of pointers to string"`

	// Example of a map
	IntMap map[string]int `long:"intmap" description:"A map from string to int"`
}

// Callback which will invoke callto:<argument> to call a number.
// Note that this works just on OS X (and probably only with
// Skype) but it shows the idea.
opts.Call = func(num string) {
	cmd := exec.Command("open", "callto:"+num)
	cmd.Start()
	cmd.Process.Release()
}

// Make some fake arguments to parse.
args := []string{
	"-vv",
	"--offset=5",
	"-n", "Me",
	"-p", "3",
	"-s", "hello",
	"-s", "world",
	"--ptrslice", "hello",
	"--ptrslice", "world",
	"--intmap", "a:1",
	"--intmap", "b:5",
	"arg1",
	"arg2",
	"arg3",
}

// Parse flags from `args'. Note that here we use flags.ParseArgs for
// the sake of making a working example. Normally, you would simply use
// flags.Parse(&opts) which uses os.Args
args, err := flags.ParseArgs(&opts, args)

if err != nil {
	panic(err)
	os.Exit(1)
}

fmt.Printf("Verbosity: %v\n", opts.Verbose)
fmt.Printf("Offset: %d\n", opts.Offset)
fmt.Printf("Name: %s\n", opts.Name)
fmt.Printf("Ptr: %d\n", *opts.Ptr)
fmt.Printf("StringSlice: %v\n", opts.StringSlice)
fmt.Printf("PtrSlice: [%v %v]\n", *opts.PtrSlice[0], *opts.PtrSlice[1])
fmt.Printf("IntMap: [a:%v b:%v]\n", opts.IntMap["a"], opts.IntMap["b"])
fmt.Printf("Remaining args: %s\n", strings.Join(args, " "))
Output:

Verbosity: [true true]
Offset: 5
Name: Me
Ptr: 3
StringSlice: [hello world]
PtrSlice: [hello world]
IntMap: [a:1 b:5]
Remaining args: arg1 arg2 arg3

Index

Examples

Constants

View Source
const (
	IniNone            IniOptions = 0
	IniIncludeDefaults            = 1 << iota
	IniIncludeComments
	IniDefault = IniIncludeComments
)
View Source
const (
	// No options
	None Options = 0

	// Add a default Help Options group to the parser containing -h and
	// --help options. When either -h or --help is specified on the command
	// line, a pretty formatted help message will be printed to os.Stderr.
	// The parser will return ErrHelp.
	HelpFlag = 1 << iota

	// Pass all arguments after a double dash, --, as remaining command line
	// arguments (i.e. they will not be parsed for flags)
	PassDoubleDash

	// Ignore any unknown options and pass them as remaining command line
	// arguments
	IgnoreUnknown

	// Print any errors which occured during parsing to os.Stderr
	PrintErrors

	// A convenient default set of options
	Default = HelpFlag | PrintErrors | PassDoubleDash
)
View Source
const (
	TIOCGWINSZ = 0x5413
)

Variables

View Source
var ErrNotPointerToStruct = errors.New("provided data is not a pointer to struct")

The provided container is not a pointer to a struct

View Source
var ErrShortNameTooLong = errors.New("short names can only be 1 character")

The provided short name is longer than a single character

Functions

func Parse

func Parse(data interface{}) ([]string, error)

Parse is a convenience function to parse command line options with default settings. The provided data is a pointer to a struct representing the default option group (named "Application Options"). For more control, use flags.NewParser.

func ParseArgs

func ParseArgs(data interface{}, args []string) ([]string, error)

ParseArgs is a convenience function to parse command line options with default settings. The provided data is a pointer to a struct representing the default option group (named "Application Options"). The args argument is the list of command line arguments to parse. If you just want to parse the default program command line arguments (i.e. os.Args), then use flags.Parse instead. For more control, use flags.NewParser.

func ParseIni

func ParseIni(filename string, data interface{}) error

ParseIni is a convenience function to parse command line options with default settings from an ini file. The provided data is a pointer to a struct representing the default option group (named "Application Options"). For more control, use flags.NewParser.

Types

type Command

type Command interface {
	Execute(args []string) error
}

type Commander

type Commander struct {
	Commands map[string]*Group
}

func (*Commander) EachCommand

func (x *Commander) EachCommand(cb func(command string, grp *Group))

type Error

type Error struct {
	// The type of error
	Type ErrorType

	// The error message
	Message string
}

Error represents a parser error. The error returned from Parse is of this type. The error contains both a Type and Message.

func (*Error) Error

func (e *Error) Error() string

Get the errors error message.

type ErrorType

type ErrorType uint

ErrorType represents the type of error.

const (
	// Unknown or generic error
	ErrUnknown ErrorType = iota

	// Expected an argument but got none
	ErrExpectedArgument

	// Unknown flag
	ErrUnknownFlag

	// Unknown group
	ErrUnknownGroup

	// Failed to marshal value
	ErrMarshal

	// The error contains the builtin help message
	ErrHelp

	// An argument for a boolean value was specified
	ErrNoArgumentForBool

	// A required flag was not specified
	ErrRequired
)

type Group

type Group struct {
	Commander

	// The name of the group.
	Name string

	Names    map[string]*Option
	IniNames map[string]*Option

	// A map of long names to option option descriptions.
	LongNames map[string]*Option

	// A map of short names to option option descriptions.
	ShortNames map[rune]*Option

	// A list of all the options in the group.
	Options []*Option

	// An error which occurred when creating the group.
	Error error

	// Groups embedded in this group
	EmbeddedGroups []*Group

	IsCommand       bool
	LongDescription string
	// contains filtered or unexported fields
}

An option group. The option group has a name and a set of options.

func NewGroup

func NewGroup(name string, data interface{}) *Group

NewGroup creates a new option group with a given name and underlying data container. The data container is a pointer to a struct. The fields of the struct represent the command line options (using field tags) and their values will be set when their corresponding options appear in the command line arguments.

type Ini

type Ini map[string]IniSection

type IniError

type IniError struct {
	Message    string
	File       string
	LineNumber uint
}

func (*IniError) Error

func (x *IniError) Error() string

type IniOptions

type IniOptions uint

type IniSection

type IniSection map[string]string

type Option

type Option struct {
	// The short name of the option (a single character). If not 0, the
	// option flag can be 'activated' using -<ShortName>. Either ShortName
	// or LongName needs to be non-empty.
	ShortName rune

	// The long name of the option. If not "", the option flag can be
	// activated using --<LongName>. Either ShortName or LongName needs
	// to be non-empty.
	LongName string

	// The description of the option flag. This description is shown
	// automatically in the builtin help.
	Description string

	// The default value of the option.
	Default string

	// If true, specifies that the argument to an option flag is optional.
	// When no argument to the flag is specified on the command line, the
	// value of Default will be set in the field this option represents.
	// This is only valid for non-boolean options.
	OptionalArgument bool

	// The optional value of the option. The optional value is used when
	// the option flag is marked as having an OptionalArgument. This means
	// that when the flag is specified, but no option argument is given,
	// the value of the field this option represents will be set to
	// OptionalValue. This is only valid for non-boolean options.
	OptionalValue string

	// If true, the option _must_ be specified on the command line. If the
	// option is not specified, the parser will generate an ErrRequired type
	// error.
	Required bool

	// A name for the value of an option shown in the Help as --flag [ValueName]
	ValueName string

	// The struct field which the option represents.
	Field reflect.StructField

	// The struct field value which the option represents.
	Value reflect.Value
	// contains filtered or unexported fields
}

Option flag information. Contains a description of the option, short and long name as well as a default value and whether an argument for this flag is optional.

func (*Option) Set

func (option *Option) Set(value *string) error

Set the value of an option to the specified value. An error will be returned if the specified value could not be converted to the corresponding option value type.

func (*Option) String

func (option *Option) String() string

Convert an option to a human friendly readable string describing the option.

type Options

type Options uint

Parser options

type Parser

type Parser struct {
	Commander

	// The option groups available to the parser
	Groups    []*Group
	GroupsMap map[string]*Group

	// The parser application name
	ApplicationName string

	// The application short description
	Description string

	// The usage (e.g. [OPTIONS] <filename>)
	Usage string

	Options Options
	// contains filtered or unexported fields
}

A Parser provides command line option parsing. It can contain several option groups each with their own set of options.

func NewNamedParser

func NewNamedParser(appname string, options Options, groups ...*Group) *Parser

NewNamedParser creates a new parser. The appname is used to display the executable name in the builtin help message. An initial set of option groups can be specified when constructing a parser, but you can also add additional option groups later (see Parser.AddGroup).

func NewParser

func NewParser(data interface{}, options Options) *Parser

NewParser creates a new parser. It uses os.Args[0] as the application name and then calls Parser.NewNamedParser (see Parser.NewNamedParser for more details). The provided data is a pointer to a struct representing the default option group (named "Application Options"), or nil if the default group should not be added. The options parameter specifies a set of options for the parser.

func (*Parser) AddCommand

func (p *Parser) AddCommand(command string, description string, longDescription string, data interface{}) *Parser

AddCommand adds a new command to the parser with the given name and data. The data needs to be a pointer to a struct from which the fields indicate which options are in the command.

func (*Parser) AddGroup

func (p *Parser) AddGroup(name string, data interface{}) *Parser

AddGroup adds a new group to the parser with the given name and data. The data needs to be a pointer to a struct from which the fields indicate which options are in the group.

func (*Parser) EachGroup

func (p *Parser) EachGroup(cb func(int, *Group))

func (*Parser) EachGroupWithTopLevel

func (p *Parser) EachGroupWithTopLevel(cb func(int, *Group))

func (*Parser) Parse

func (p *Parser) Parse() ([]string, error)

Parse parses the command line arguments from os.Args using Parser.ParseArgs. For more detailed information see ParseArgs.

func (*Parser) ParseArgs

func (p *Parser) ParseArgs(args []string) ([]string, error)

ParseArgs parses the command line arguments according to the option groups that were added to the parser. On successful parsing of the arguments, the remaining, non-option, arguments (if any) are returned. The returned error indicates a parsing error and can be used with PrintError to display contextual information on where the error occurred exactly.

When the common help group has been added (AddHelp) and either -h or --help was specified in the command line arguments, a help message will be automatically printed. Furthermore, the special error type ErrHelp is returned. It is up to the caller to exit the program if so desired.

func (*Parser) ParseIni

func (p *Parser) ParseIni(reader io.Reader) error

ParseIni parses flags from an ini format. You can use ParseIniFile as a convenience function to parse from a filename instead of a general io.Reader.

The format of the ini file is as follows:

[Option group name] option = value

Each section in the ini file represents an option group in the flags parser. The default flags parser option group (i.e. when using flags.Parse) is named 'Application Options'. The ini option name is matched in the following order:

1. Compared to the ini-name tag on the option struct field (if present) 2. Compared to the struct field name 3. Compared to the option long name (if present) 4. Compared to the option short name (if present)

The returned errors can be of the type flags.Error or flags.IniError.

func (*Parser) ParseIniFile

func (p *Parser) ParseIniFile(filename string) error

ParseIniFile parses flags from an ini formatted file. See ParseIni for more information on the ini file foramt. The returned errors can be of the type flags.Error or flags.IniError.

func (*Parser) WriteHelp

func (p *Parser) WriteHelp(writer io.Writer)

WriteHelp writes a help message containing all the possible options and their descriptions to the provided writer. Note that the HelpFlag parser option provides a convenient way to add a -h/--help option group to the command line parser which will automatically show the help messages using this method.

func (*Parser) WriteIni

func (p *Parser) WriteIni(writer io.Writer, options IniOptions)

WriteIni writes the current values of all the flags to an ini format. See ParseIni for more information on the ini file format. You typically call this only after settings have been parsed since the default values of each option are stored just before parsing the flags (this is only relevant when IniIncludeDefaults is _not_ set in options).

func (*Parser) WriteIniToFile

func (p *Parser) WriteIniToFile(filename string, options IniOptions) error

WriteIniToFile writes the flags as ini format into a file. See WriteIni for more information. The returned error occurs when the specified file could not be opened for writing.

func (*Parser) WriteManPage

func (x *Parser) WriteManPage(wr io.Writer, description string)

WriteManPage writes a basic man page in groff format to the specified writer.

Jump to

Keyboard shortcuts

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