flags

package
v0.0.0-...-ca6883d Latest Latest
Warning

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

Go to latest
Published: Oct 17, 2014 License: ISC, BSD-3-Clause Imports: 15 Imported by: 0

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]}.

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

More information can be found in the godocs: http://godoc.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

Additional features specific to Windows:

Options with short names (/v)
Options with long names (/verbose)
Windows-style options with arguments use a colon as the delimiter
Modify generated help message with Windows-style / options

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".

Finally, for full control over the conversion between command line argument values and options, user defined types can choose to implement the Marshaler and Unmarshaler interfaces.

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)
optional-value: the value of an optional option when the option occurs
                without an argument. This tag can be specified multiple
                times in the case of maps or slices (optional)
default:        the default value of an option. This tag can be specified
                multiple times in the case of slices or maps (optional).
default-mask:   when specified, this value will be displayed in the help
                instead of the actual default value. This is useful
                mostly for hiding otherwise sensitive information from
                showing up in the help. If default-mask takes the special
                value "-", then no default value will be shown at all
                (optional)
required:       whether an option is required to appear on the command
                line. If a required option is not present, the parser
                will return ErrRequired.
base:           a base (radix) used to convert strings to integer values,
                the default base is 10 (i.e. decimal) (optional)
value-name:     the name of the argument value (to be shown in the help,
                (optional)
group:          when specified on a struct field, makes the struct field
                a separate group with the given name (optional).
command:        when specified on a struct field, makes the struct field
                a (sub)command with the given name (optional).

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

Option groups:

Option groups are a simple way to semantically separate your options. The only real difference is in how your options will appear in the builtin generated help. All options in a particular group are shown together in the help under the name of the group.

There are currently three ways to specify option groups.

  1. Use NewNamedParser specifying the various option groups.
  2. Use AddGroup to add a group to an existing parser.
  3. Add a struct field to the toplevel options annotated with the group:"group-name" tag.

Commands:

The flags package also has basic support for commands. Commands are often used in monolithic applications that support various commands or actions. Take git for example, all of the add, commit, checkout, etc. are called commands. Using commands you can easily separate multiple functions of your application.

There are currently two ways to specifiy a command.

  1. Use AddCommand on an existing parser.
  2. Add a struct field to your options struct annotated with the command:"command-name" tag.

The most common, idiomatic way to implement commands is to define a global parser instance and implement each command in a separate file. These command files should define a go init function which calls AddCommand on the global parser.

When parsing ends and there is an active command and that command implements the Commander interface, then its Execute method will be run with the remaining command line arguments.

Command structs can have options which become valid to parse after the command has been specified on the command line. It is currently not valid to specify options from the parent level of the command after the command name has occurred. Thus, given a toplevel option "-v" and a command "add":

Valid:   ./app -v add
Invalid: ./app add -v
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 (
	// No options
	IniNone IniOptions = 0

	// Write default values
	IniIncludeDefaults = 1 << iota

	// Write comments containing the description of an option
	IniIncludeComments

	// Default options
	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

	// Pass all arguments after the first non option. This is equivalent
	// to strict POSIX processing
	PassAfterNonOption

	// A convenient default set of options
	Default = HelpFlag | PrintErrors | PassDoubleDash
)

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

Functions

func IniParse

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

IniParse 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.

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.

Types

type Command

type Command struct {
	// Embedded, see Group for more information
	*Group

	// The name by which the command can be invoked
	Name string

	// The active sub command (set by parsing) or nil
	Active *Command
	// contains filtered or unexported fields
}

func (*Command) AddCommand

func (c *Command) AddCommand(command string, shortDescription string, longDescription string, data interface{}) (*Command, error)

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. The provided data can implement the Command and Usage interfaces.

func (*Command) AddGroup

func (c *Command) AddGroup(shortDescription string, longDescription string, data interface{}) (*Group, error)

AddGroup adds a new group to the command 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 (*Command) Commands

func (c *Command) Commands() []*Command

Get a list of subcommands of this command.

func (*Command) Find

func (c *Command) Find(name string) *Command

Find locates the subcommand with the given name and returns it. If no such command can be found Find will return nil.

type Commander

type Commander interface {
	// Execute will be called for the last active (sub)command. The
	// args argument contains the remaining command line arguments. The
	// error that Execute returns will be eventually passed out of the
	// Parse method of the Parser.
	Execute(args []string) error
}

The command interface should be implemented by any command added in the options. When implemented, the Execute method will be called for the last specified (sub)command providing the remaining command line arguments.

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

	// A short flag name is longer than one character
	ErrShortNameTooLong
)

func (ErrorType) String

func (e ErrorType) String() string

type Group

type Group struct {
	// A short description of the group
	ShortDescription string

	// A long description of the group
	LongDescription string
	// contains filtered or unexported fields
}

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

func (*Group) AddGroup

func (g *Group) AddGroup(shortDescription string, longDescription string, data interface{}) (*Group, error)

AddGroup adds a new group to the command 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 (*Group) Find

func (g *Group) Find(shortDescription string) *Group

Group locates the subgroup with the given short description and returns it. If no such group can be found Find will return nil. Note that the description is matched case insensitively.

func (*Group) Groups

func (g *Group) Groups() []*Group

Get a list of subgroups in the group.

func (*Group) Options

func (g *Group) Options() []*Option

Get a list of options in the group.

type IniError

type IniError struct {
	Message    string
	File       string
	LineNumber uint
}

IniError contains location information on where in the ini file an error occured.

func (*IniError) Error

func (x *IniError) Error() string

Error provides a "file:line: message" formatted message of the ini error.

type IniOptions

type IniOptions uint

Options for writing ini files

type IniParser

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

IniParser is a utility to read and write flags options from and to ini files.

func NewIniParser

func NewIniParser(p *Parser) *IniParser

NewIniParser creates a new ini parser for a given Parser.

func (*IniParser) Parse

func (i *IniParser) Parse(reader io.Reader) error

Parse parses flags from an ini format. You can use ParseFile 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 or command 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)

Sections for nested groups and commands can be addressed using a dot `.' namespacing notation (i.e [subcommand.Options]). Group section names are matched case insensitive.

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

func (*IniParser) ParseFile

func (i *IniParser) ParseFile(filename string) error

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

func (*IniParser) Write

func (i *IniParser) Write(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 (*IniParser) WriteFile

func (i *IniParser) WriteFile(filename string, options IniOptions) error

WriteFile 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.

type Marshaler

type Marshaler interface {
	MarshalFlag() (string, error)
}

Marshaler is the interface implemented by types that can marshal themselves to a string representation of the flag.

type Option

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

	// 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 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

	// A mask value to show in the help instead of the default value. This
	// is useful for hiding sensitive information in the help, such as
	// passwords.
	DefaultMask string
	// 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) 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 {
	*Command

	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) *Parser

NewNamedParser creates a new parser. The appname is used to display the executable name in the builtin help message. Option groups and commands can be added to this parser by using AddGroup and AddCommand.

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) 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) 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) WriteManPage

func (p *Parser) WriteManPage(wr io.Writer)

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

type Unmarshaler

type Unmarshaler interface {
	UnmarshalFlag(value string) error
}

Unmarshaler is the interface implemented by types that can unmarshal a flag argument to themselves. The provided value is directly passed from the command line.

type Usage

type Usage interface {
	// Usage is called for commands to allow customized printing of command
	// usage in the generated help message.
	Usage() string
}

The usage interface can be implemented to show a custom usage string in the help message shown for a command.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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