flags

package module
v1.6.1 Latest Latest
Warning

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

Go to latest
Published: Jun 15, 2024 License: BSD-3-Clause Imports: 16 Imported by: 12,247

README

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

GoDoc

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
  • Supports namespaces for (nested) option groups

The flags package uses structs, reflection and struct field tags to allow users to specify command line options. This results in very simple and concise 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 flag restricted to a pre-defined set of strings
	Animal string `long:"animal" choice:"cat" choice:"dog"`

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

	// Example of env variable
	Thresholds  []int     `long:"thresholds" default:"1" default:"2" env:"THRESHOLD_VALUES"  env-delim:","`
}

// 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",
	"--animal", "dog", // anything other than "cat" or "dog" will raise an error
	"-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)
}

fmt.Printf("Verbosity: %v\n", opts.Verbose)
fmt.Printf("Offset: %d\n", opts.Offset)
fmt.Printf("Name: %s\n", opts.Name)
fmt.Printf("Animal: %s\n", opts.Animal)
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 built-in flag package but provides more options and uses reflection to provide a convenient and succinct way of specifying command line options.

Supported features

The following features are supported in go-flags:

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
Option default values from ENVIRONMENT_VARIABLES, including slice and map 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
Supports namespaces for (nested) option groups

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
Windows style options can be disabled at build time using the "forceposix"
build tag

Basic usage

The flags package uses structs, reflection and struct field tags to allow users to specify command line options. This results in very simple and concise 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

The following is a list of tags for struct fields supported by go-flags:

short:            the short name of the option (single character)
long:             the long name of the option
required:         if non empty, makes the option required to appear on the command
                  line. If a required option is not present, the parser will
                  return ErrRequired (optional)
description:      the description of the option (optional)
long-description: the long description of the option. Currently only
                  displayed in generated man pages (optional)
no-flag:          if non-empty, this field is ignored as an option (optional)

optional:       if non-empty, makes the argument of the option optional. When an
                argument is optional it can only be specified using
                --option=argument (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)
env:            the default value of the option is overridden from the
                specified environment variable, if one has been defined.
                (optional)
env-delim:      the 'env' default value from environment is split into
                multiple values with the given delimiter string, use with
                slices and maps (optional)
value-name:     the name of the argument value (to be shown in the help)
                (optional)
choice:         limits the values for an option to a set of values.
                Repeat this tag once for each allowable value.
                e.g. `long:"animal" choice:"cat" choice:"dog"`
hidden:         if non-empty, the option is not visible in the help or man page.

base: a base (radix) used to convert strings to integer values, the
      default base is 10 (i.e. decimal) (optional)

ini-name:       the explicit ini option name (optional)
no-ini:         if non-empty this field is ignored as an ini option
                (optional)

group:                when specified on a struct field, makes the struct
                      field a separate group with the given name (optional)
namespace:            when specified on a group struct field, the namespace
                      gets prepended to every option's long name and
                      subgroup's namespace of this group, separated by
                      the parser's namespace delimiter (optional)
env-namespace:        when specified on a group struct field, the env-namespace
                      gets prepended to every option's env key and
                      subgroup's env-namespace of this group, separated by
                      the parser's env-namespace delimiter (optional)
command:              when specified on a struct field, makes the struct
                      field a (sub)command with the given name (optional)
subcommands-optional: when specified on a command struct field, makes
                      any subcommands of that command optional (optional)
alias:                when specified on a command struct field, adds the
                      specified name as an alias for the command. Can be
                      be specified multiple times to add more than one
                      alias (optional)
positional-args:      when specified on a field with a struct type,
                      uses the fields of that struct to parse remaining
                      positional command line arguments into (in order
                      of the fields). If a field has a slice type,
                      then all remaining arguments will be added to it.
                      Positional arguments are optional by default,
                      unless the "required" tag is specified together
                      with the "positional-args" tag. The "required" tag
                      can also be set on the individual rest argument
                      fields, to require only the first N positional
                      arguments. If the "required" tag is set on the
                      rest arguments slice, then its value determines
                      the minimum amount of rest arguments that needs to
                      be provided (e.g. `required:"2"`) (optional)
positional-arg-name:  used on a field in a positional argument struct; name
                      of the positional argument placeholder to be shown in
                      the help (optional)

Either the `short:` tag or the `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. All options in a particular group are shown together in the help under the name of the group. Namespaces can be used to specify option long names more precisely and emphasize the options affiliation to their 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 top-level 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 specify 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, in addition to the options of all the parent commands. I.e. considering a -v flag on the parser and an add command, the following are equivalent:

./app -v add
./app add -v

However, if the -v flag is defined on the add command, then the first of the two examples above would fail since the -v flag is not defined before the add command.

Completion

go-flags has builtin support to provide bash completion of flags, commands and argument values. To use completion, the binary which uses go-flags can be invoked in a special environment to list completion of the current command line argument. It should be noted that this `executes` your application, and it is up to the user to make sure there are no negative side effects (for example from init functions).

Setting the environment variable `GO_FLAGS_COMPLETION=1` enables completion by replacing the argument parsing routine with the completion routine which outputs completions for the passed arguments. The basic invocation to complete a set of arguments is therefore:

GO_FLAGS_COMPLETION=1 ./completion-example arg1 arg2 arg3

where `completion-example` is the binary, `arg1` and `arg2` are the current arguments, and `arg3` (the last argument) is the argument to be completed. If the GO_FLAGS_COMPLETION is set to "verbose", then descriptions of possible completion items will also be shown, if there are more than 1 completion items.

To use this with bash completion, a simple file can be written which calls the binary which supports go-flags completion:

_completion_example() {
    # All arguments except the first one
    args=("${COMP_WORDS[@]:1:$COMP_CWORD}")

    # Only split on newlines
    local IFS=$'\n'

    # Call completion (note that the first element of COMP_WORDS is
    # the executable itself)
    COMPREPLY=($(GO_FLAGS_COMPLETION=1 ${COMP_WORDS[0]} "${args[@]}"))
    return 0
}

complete -F _completion_example completion-example

Completion requires the parser option PassDoubleDash and is therefore enforced if the environment variable GO_FLAGS_COMPLETION is set.

Customized completion for argument values is supported by implementing the flags.Completer interface for the argument value type. An example of a type which does so is the flags.Filename type, an alias of string allowing simple filename completion. A slice or array argument value whose element type implements flags.Completer will also be completed.

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

	// Example of a filename (useful for completion)
	Filename Filename `long:"filename" description:"A filename"`

	// Example of positional arguments
	Args struct {
		ID   string
		Num  int
		Rest []string
	} `positional-args:"yes" required:"yes"`
}

// 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",
	"--filename", "hello.go",
	"id",
	"10",
	"remaining1",
	"remaining2",
}

// 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
_, err := ParseArgs(&opts, args)

if err != nil {
	panic(err)
}

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("Filename: %v\n", opts.Filename)
fmt.Printf("Args.ID: %s\n", opts.Args.ID)
fmt.Printf("Args.Num: %d\n", opts.Args.Num)
fmt.Printf("Args.Rest: %v\n", opts.Args.Rest)
Output:

Verbosity: [true true]
Offset: 5
Name: Me
Ptr: 3
StringSlice: [hello world]
PtrSlice: [hello world]
IntMap: [a:1 b:5]
Filename: hello.go
Args.ID: id
Args.Num: 10
Args.Rest: [remaining1 remaining2]

Index

Examples

Constants

View Source
const (
	// IniNone indicates no options.
	IniNone IniOptions = 0

	// IniIncludeDefaults indicates that default values should be written.
	IniIncludeDefaults = 1 << iota

	// IniCommentDefaults indicates that if IniIncludeDefaults is used
	// options with default values are written but commented out.
	IniCommentDefaults

	// IniIncludeComments indicates that comments containing the description
	// of an option should be written.
	IniIncludeComments

	// IniDefault provides a default set of options.
	IniDefault = IniIncludeComments
)
View Source
const (
	// None indicates no options.
	None Options = 0

	// HelpFlag adds a default Help Options group to the parser containing
	// -h and --help options. When either -h or --help is specified on the
	// command line, the parser will return the special error of type
	// ErrHelp. When PrintErrors is also specified, then the help message
	// will also be automatically printed to os.Stdout.
	HelpFlag = 1 << iota

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

	// IgnoreUnknown ignores any unknown options and passes them as
	// remaining command line arguments instead of generating an error.
	IgnoreUnknown

	// PrintErrors prints any errors which occurred during parsing to
	// os.Stderr. In the special case of ErrHelp, the message will be printed
	// to os.Stdout.
	PrintErrors

	// PassAfterNonOption passes all arguments after the first non option
	// as remaining command line arguments. This is equivalent to strict
	// POSIX processing.
	PassAfterNonOption

	// AllowBoolValues allows a user to assign true/false to a boolean value
	// rather than raising an error stating it cannot have an argument.
	AllowBoolValues

	// Default is a convenient default set of options which should cover
	// most of the uses of the flags package.
	Default = HelpFlag | PrintErrors | PassDoubleDash
)

Variables

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

ErrNotPointerToStruct indicates that a provided data container is not a pointer to a struct. Only pointers to structs are valid data containers for options.

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

func WroteHelp added in v1.5.0

func WroteHelp(err error) bool

WroteHelp is a helper to test the error from ParseArgs() to determine if the help message was written. It is safe to call without first checking that error is nil.

Types

type Arg

type Arg struct {
	// The name of the positional argument (used in the help)
	Name string

	// A description of the positional argument (used in the help)
	Description string

	// The minimal number of required positional arguments
	Required int

	// The maximum number of required positional arguments
	RequiredMaximum int
	// contains filtered or unexported fields
}

Arg represents a positional argument on the command line.

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

	// Whether subcommands are optional
	SubcommandsOptional bool

	// Aliases for the command
	Aliases []string

	// Whether positional arguments are required
	ArgsRequired bool

	// Whether to pass all arguments after the first non option as remaining
	// command line arguments. This is equivalent to strict POSIX processing.
	// This is command-local version of PassAfterNonOption Parser flag. It
	// cannot be turned off when PassAfterNonOption Parser flag is set.
	PassAfterNonOption bool
	// contains filtered or unexported fields
}

Command represents an application command. Commands can be added to the parser (which itself is a command) and are selected/executed when its name is specified on the command line. The Command type embeds a Group and therefore also carries a set of command specific options.

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

func (c *Command) Args() []*Arg

Args returns a list of positional arguments associated with this command.

func (*Command) Commands

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

Commands returns 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.

func (*Command) FindOptionByLongName

func (c *Command) FindOptionByLongName(longName string) (option *Option)

FindOptionByLongName finds an option that is part of the command, or any of its parent commands, by matching its long name (including the option namespace).

func (*Command) FindOptionByShortName

func (c *Command) FindOptionByShortName(shortName rune) (option *Option)

FindOptionByShortName finds an option that is part of the command, or any of its parent commands, by matching its long name (including the option namespace).

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
}

Commander is an interface which can 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 Completer

type Completer interface {
	// Complete receives a prefix representing a (partial) value
	// for its type and should provide a list of possible valid
	// completions.
	Complete(match string) []Completion
}

Completer is an interface which can be implemented by types to provide custom command line argument completion.

type Completion

type Completion struct {
	// The completed item
	Item string

	// A description of the completed item (optional)
	Description string
}

Completion is a type containing information of a completion.

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

Error returns the error's message

type ErrorType

type ErrorType uint

ErrorType represents the type of error.

const (
	// ErrUnknown indicates a generic error.
	ErrUnknown ErrorType = iota

	// ErrExpectedArgument indicates that an argument was expected.
	ErrExpectedArgument

	// ErrUnknownFlag indicates an unknown flag.
	ErrUnknownFlag

	// ErrUnknownGroup indicates an unknown group.
	ErrUnknownGroup

	// ErrMarshal indicates a marshalling error while converting values.
	ErrMarshal

	// ErrHelp indicates that the built-in help was shown (the error
	// contains the help message).
	ErrHelp

	// ErrNoArgumentForBool indicates that an argument was given for a
	// boolean flag (which don't not take any arguments).
	ErrNoArgumentForBool

	// ErrRequired indicates that a required flag was not provided.
	ErrRequired

	// ErrShortNameTooLong indicates that a short flag name was specified,
	// longer than one character.
	ErrShortNameTooLong

	// ErrDuplicatedFlag indicates that a short or long flag has been
	// defined more than once
	ErrDuplicatedFlag

	// ErrTag indicates an error while parsing flag tags.
	ErrTag

	// ErrCommandRequired indicates that a command was required but not
	// specified
	ErrCommandRequired

	// ErrUnknownCommand indicates that an unknown command was specified.
	ErrUnknownCommand

	// ErrInvalidChoice indicates an invalid option value which only allows
	// a certain number of choices.
	ErrInvalidChoice

	// ErrInvalidTag indicates an invalid tag or invalid use of an existing tag
	ErrInvalidTag
)

func (ErrorType) Error added in v1.5.0

func (e ErrorType) Error() string

func (ErrorType) String

func (e ErrorType) String() string

type Filename

type Filename string

Filename is a string alias which provides filename completion.

func (*Filename) Complete

func (f *Filename) Complete(match string) []Completion

Complete returns a list of existing files with the given prefix.

type Group

type Group struct {
	// A short description of the group. The
	// short description is primarily used in the built-in generated help
	// message
	ShortDescription string

	// A long description of the group. The long
	// description is primarily used to present information on commands
	// (Command embeds Group) in the built-in generated help and man pages.
	LongDescription string

	// The namespace of the group
	Namespace string

	// The environment namespace of the group
	EnvNamespace string

	// If true, the group is not displayed in the help or man page
	Hidden bool
	// contains filtered or unexported fields
}

Group represents an option group. Option groups can be used to logically group options together under a description. Groups are only used to provide more structure to options both for the user (as displayed in the help message) and for you, since groups can be nested.

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) AddOption added in v1.5.0

func (g *Group) AddOption(option *Option, data interface{})

AddOption adds a new option to this group.

func (*Group) Find

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

Find 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) FindOptionByLongName

func (g *Group) FindOptionByLongName(longName string) *Option

FindOptionByLongName finds an option that is part of the group, or any of its subgroups, by matching its long name (including the option namespace).

func (*Group) FindOptionByShortName

func (g *Group) FindOptionByShortName(shortName rune) *Option

FindOptionByShortName finds an option that is part of the group, or any of its subgroups, by matching its short name.

func (*Group) Groups

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

Groups returns the list of groups embedded in this group.

func (*Group) Options

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

Options returns the list of options in this group.

type IniError

type IniError struct {
	// The error message.
	Message string

	// The filename of the file in which the error occurred.
	File string

	// The line number at which the error occurred.
	LineNumber uint
}

IniError contains location information on where an error occurred.

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

IniOptions for writing

type IniParser

type IniParser struct {
	ParseAsDefaults bool // override default flags
	// contains filtered or unexported fields
}

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

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 format. 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)

Write writes the current values of all the flags to an ini format. See Parse 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 Write for more information. The returned error occurs when the specified file could not be opened for writing.

type Marshaler

type Marshaler interface {
	// MarshalFlag marshals a flag value to its string representation.
	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 built-in 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

	// The optional environment default value key name.
	EnvDefaultKey string

	// The optional delimiter string for EnvDefaultKey values.
	EnvDefaultDelim 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 OptionalValue 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

	// If non empty, only a certain set of values is allowed for an option.
	Choices []string

	// If true, the option is not displayed in the help or man page
	Hidden bool
	// 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) EnvKeyWithNamespace added in v1.5.0

func (option *Option) EnvKeyWithNamespace() string

EnvKeyWithNamespace returns the option's env key with the group namespaces prepended by walking up the option's group tree. Namespaces and the env key itself are separated by the parser's namespace delimiter. If the env key is empty an empty string is returned.

func (*Option) Field

func (option *Option) Field() reflect.StructField

Field returns the reflect struct field of the option.

func (*Option) IsSet

func (option *Option) IsSet() bool

IsSet returns true if option has been set

func (*Option) IsSetDefault added in v1.2.0

func (option *Option) IsSetDefault() bool

IsSetDefault returns true if option has been set via the default option tag

func (*Option) LongNameWithNamespace

func (option *Option) LongNameWithNamespace() string

LongNameWithNamespace returns the option's long name with the group namespaces prepended by walking up the option's group tree. Namespaces and the long name itself are separated by the parser's namespace delimiter. If the long name is empty an empty string is returned.

func (*Option) Set added in v1.6.0

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

String converts an option to a human friendly readable string describing the option.

func (*Option) Value

func (option *Option) Value() interface{}

Value returns the option value as an interface{}.

type Options

type Options uint

Options provides parser options that change the behavior of the option parser.

type Parser

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

	// A usage string to be displayed in the help message.
	Usage string

	// Option flags changing the behavior of the parser.
	Options Options

	// NamespaceDelimiter separates group namespaces and option long names
	NamespaceDelimiter string

	// EnvNamespaceDelimiter separates group env namespaces and env keys
	EnvNamespaceDelimiter string

	// UnknownOptionsHandler is a function which gets called when the parser
	// encounters an unknown option. The function receives the unknown option
	// name, a SplitArgument which specifies its value if set with an argument
	// separator, and the remaining command line arguments.
	// It should return a new list of remaining arguments to continue parsing,
	// or an error to indicate a parse failure.
	UnknownOptionHandler func(option string, arg SplitArgument, args []string) ([]string, error)

	// CompletionHandler is a function gets called to handle the completion of
	// items. By default, the items are printed and the application is exited.
	// You can override this default behavior by specifying a custom CompletionHandler.
	CompletionHandler func(items []Completion)

	// CommandHandler is a function that gets called to handle execution of a
	// command. By default, the command will simply be executed. This can be
	// overridden to perform certain actions (such as applying global flags)
	// just before the command is executed. Note that if you override the
	// handler it is your responsibility to call the command.Execute function.
	//
	// The command passed into CommandHandler may be nil in case there is no
	// command to be executed when parsing has finished.
	CommandHandler func(command Commander, args []string) error
	// 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 built-in 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 if the PrintErrors option is enabled. 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 SplitArgument

type SplitArgument interface {
	// String returns the option's value as a string, and a boolean indicating
	// if the option was present.
	Value() (string, bool)
}

SplitArgument represents the argument value of an option that was passed using an argument separator.

type Unmarshaler

type Unmarshaler interface {
	// UnmarshalFlag unmarshals a string value representation to the flag
	// value (which therefore needs to be a pointer receiver).
	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
}

Usage is an interface which can be implemented to show a custom usage string in the help message shown for a command.

type ValueValidator added in v1.5.0

type ValueValidator interface {
	// IsValidValue returns an error if the provided string value is valid for
	// the flag.
	IsValidValue(value string) error
}

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

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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