Categorygithub.com/jessevdk/go-flags
modulepackage
1.6.1
Repository: https://github.com/jessevdk/go-flags.git
Documentation: pkg.go.dev

# 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

# Packages

# Functions

IniParse is a convenience function to parse command line options with default settings from an ini formatted file.
NewIniParser creates a new ini parser for a given Parser.
NewNamedParser creates a new parser.
NewParser creates a new parser.
Parse is a convenience function to parse command line options with default settings.
ParseArgs is a convenience function to parse command line options with default settings.
WroteHelp is a helper to test the error from ParseArgs() to determine if the help message was written.

# Constants

AllowBoolValues allows a user to assign true/false to a boolean value rather than raising an error stating it cannot have an argument.
Default is a convenient default set of options which should cover most of the uses of the flags package.
ErrCommandRequired indicates that a command was required but not specified.
ErrDuplicatedFlag indicates that a short or long flag has been defined more than once.
ErrExpectedArgument indicates that an argument was expected.
ErrHelp indicates that the built-in help was shown (the error contains the help message).
ErrInvalidChoice indicates an invalid option value which only allows a certain number of choices.
ErrInvalidTag indicates an invalid tag or invalid use of an existing tag.
ErrMarshal indicates a marshalling error while converting values.
ErrNoArgumentForBool indicates that an argument was given for a boolean flag (which don't not take any arguments).
ErrRequired indicates that a required flag was not provided.
ErrShortNameTooLong indicates that a short flag name was specified, longer than one character.
ErrTag indicates an error while parsing flag tags.
ErrUnknown indicates a generic error.
ErrUnknownCommand indicates that an unknown command was specified.
ErrUnknownFlag indicates an unknown flag.
ErrUnknownGroup indicates an unknown group.
HelpFlag adds a default Help Options group to the parser containing -h and --help options.
IgnoreUnknown ignores any unknown options and passes them as remaining command line arguments instead of generating an error.
IniCommentDefaults indicates that if IniIncludeDefaults is used options with default values are written but commented out.
IniDefault provides a default set of options.
IniIncludeComments indicates that comments containing the description of an option should be written.
IniIncludeDefaults indicates that default values should be written.
IniNone indicates no options.
None indicates no options.
PassAfterNonOption passes all arguments after the first non option as remaining command line arguments.
PassDoubleDash passes all arguments after a double dash, --, as remaining command line arguments (i.e.
PrintErrors prints any errors which occurred during parsing to os.Stderr.

# Variables

ErrNotPointerToStruct indicates that a provided data container is not a pointer to a struct.

# Structs

Arg represents a positional argument on the command line.
Command represents an application command.
Completion is a type containing information of a completion.
Error represents a parser error.
Group represents an option group.
IniError contains location information on where an error occurred.
IniParser is a utility to read and write flags options from and to ini formatted strings.
Option flag information.
A Parser provides command line option parsing.

# Interfaces

Commander is an interface which can be implemented by any command added in the options.
Completer is an interface which can be implemented by types to provide custom command line argument completion.
Marshaler is the interface implemented by types that can marshal themselves to a string representation of the flag.
SplitArgument represents the argument value of an option that was passed using an argument separator.
Unmarshaler is the interface implemented by types that can unmarshal a flag argument to themselves.
Usage is an interface which can be implemented to show a custom usage string in the help message shown for a command.
ValueValidator is the interface implemented by types that can validate a flag argument themselves.

# Type aliases

ErrorType represents the type of error.
Filename is a string alias which provides filename completion.
IniOptions for writing.
Options provides parser options that change the behavior of the option parser.