Documentation ¶
Overview ¶
Package param implements command-line parameter parsing in the GNU style. It is different and adds capabilities beyond the standard flag package, the only difference being the extra argument to Parse. Command line param syntax: -f // single letter flag -fg // two single letter flags together --flag // multiple letter flag --flag x // non-present flags only -f x // non-present flags only -fx // if f is a non-present flag, x is its argument. The last three forms are not permitted for boolean flags because the meaning of the command cmd -f * will change if there is a file called 0, false, etc. There is currently no way to turn off a boolean flag. Flag parsing stops after the terminator "--", or just before the first non-flag argument ("-" is a non-flag argument) if the interspersed argument to Parse is false.
TODOs:
- add flag for printing out all the possible flags for ease of tab completion
- parse the _POSIX_OPTION_ORDER environment variable for ignoring the flag forder, see https://www.gnu.org/software/libc/manual/html_node/Standard-Environment.html
- add thin space for all the double wide chars for alignment
Example ¶
// These examples demonstrate more intricate uses of the params package. package main import ( "errors" "fmt" "github.com/pschou/go-params" "strings" "time" ) // Example 1: A single string params called "species" with default value "gopher". var species = params.String("species", "gopher", "the species we are studying", "TEXT") // Example 2: Two paramss sharing a variable, so we can have a shorthand. // The order of initialization is undefined, so make sure both use the // same default value. They must be set up with an init function. var gopherType string func init() { const ( defaultGopher = "pocket" usage = "the variety of gopher" ) params.StringVar(&gopherType, "gopher_type", defaultGopher, usage, "TYPE") params.StringVar(&gopherType, "g", defaultGopher, usage+" (shorthand)", "") } // Example 3: A user-defined params type, a slice of durations. type interval []time.Duration // String is the method to format the params's value, part of the params.Value interface. // The String method's output will be used in diagnostics. func (i *interval) String() string { return fmt.Sprint(*i) } // Set is the method to set the params value, part of the params.Value interface. // Set's argument is a string to be parsed to set the params. // It's a comma-separated list, so we split it. func (i *interval) Set(value []string) error { // If we wanted to allow the params to be set multiple times, // accumulating values, we would delete this if statement. // That would permit usages such as // -deltaT 10s -deltaT 15s // and other combinations. if len(*i) > 0 { return errors.New("interval params already set") } for _, dt := range strings.Split(value[0], ",") { duration, err := time.ParseDuration(dt) if err != nil { return err } *i = append(*i, duration) } return nil } // Define a params to accumulate durations. Because it has a special type, // we need to use the Var function and therefore create the params during // init. var intervalFlag interval func init() { // Tie the command-line params to the intervalFlag variable and // set a usage message. params.Var(&intervalFlag, "deltaT", "comma-separated list of intervals to use between events", "VALS", 1) } func main() { // All the interesting pieces are with the variables declared above, but // to enable the params package to see the paramss defined there, one must // execute, typically at the start of main (not init!): // params.Parse() // We don't run it here because this is not a main function and // the testing suite has already parsed the paramss. }
Output:
Index ¶
- Variables
- func Arg(i int) string
- func Args() []string
- func Bool(name string, value bool, usage string, typeExp string) *bool
- func BoolVar(p *bool, name string, value bool, usage string, typeExp string)
- func Duration(name string, value time.Duration, usage string, typeExp string) *time.Duration
- func DurationVar(p *time.Duration, name string, value time.Duration, usage string, ...)
- func FlagFunc(name, usage string, typeExp string, argsNeeded int, fn func([]string) error)
- func Float64(name string, value float64, usage string, typeExp string) *float64
- func Float64Var(p *float64, name string, value float64, usage string, typeExp string)
- func GroupingSet(grouping string)
- func Int(name string, value int, usage string, typeExp string) *int
- func Int64(name string, value int64, usage string, typeExp string) *int64
- func Int64Var(p *int64, name string, value int64, usage string, typeExp string)
- func IntVar(p *int, name string, value int, usage string, typeExp string)
- func NArg() int
- func NFlag() int
- func Parse()
- func Parsed() bool
- func Pres(name string, usage string) *bool
- func PresVar(p *bool, name string, usage string)
- func PrintDefaults()
- func Set(name string, value []string) error
- func SetAllowIntersperse(allowIntersperse bool)
- func String(name string, value string, usage string, typeExp string) *string
- func StringSlice(name string, usage string, typeExp string, perFlag int) *[]string
- func StringSliceVar(p *([]string), name string, usage string, typeExp string, perFlag int)
- func StringVar(p *string, name string, value string, usage string, typeExp string)
- func Uint(name string, value uint, usage string, typeExp string) *uint
- func Uint64(name string, value uint64, usage string, typeExp string) *uint64
- func Uint64Var(p *uint64, name string, value uint64, usage string, typeExp string)
- func UintVar(p *uint, name string, value uint, usage string, typeExp string)
- func Var(value Value, name string, usage string, typeExp string, argsNeeded int)
- func Visit(fn func(*Flag))
- func VisitAll(fn func(*Flag))
- type ErrorHandling
- type Flag
- type FlagSet
- func (f *FlagSet) Arg(i int) string
- func (f *FlagSet) Args() []string
- func (f *FlagSet) Bool(name string, value bool, usage string, typeExp string) *bool
- func (f *FlagSet) BoolVar(p *bool, name string, value bool, usage string, typeExp string)
- func (f *FlagSet) Duration(name string, value time.Duration, usage string, typeExp string) *time.Duration
- func (f *FlagSet) DurationVar(p *time.Duration, name string, value time.Duration, usage string, ...)
- func (f *FlagSet) ErrorHandling() ErrorHandling
- func (f *FlagSet) FlagFunc(name, usage string, typeExp string, argsNeeded int, fn func([]string) error)
- func (f *FlagSet) Float64(name string, value float64, usage string, typeExp string) *float64
- func (f *FlagSet) Float64Var(p *float64, name string, value float64, usage string, typeExp string)
- func (f *FlagSet) GroupingSet(grouping string)
- func (f *FlagSet) Init(name string, errorHandling ErrorHandling)
- func (f *FlagSet) Int(name string, value int, usage string, typeExp string) *int
- func (f *FlagSet) Int64(name string, value int64, usage string, typeExp string) *int64
- func (f *FlagSet) Int64Var(p *int64, name string, value int64, usage string, typeExp string)
- func (f *FlagSet) IntVar(p *int, name string, value int, usage string, typeExp string)
- func (f *FlagSet) Lookup(name string) *Flag
- func (f *FlagSet) NArg() int
- func (f *FlagSet) NFlag() int
- func (f *FlagSet) Name() string
- func (f *FlagSet) Output() io.Writer
- func (f *FlagSet) Parse(arguments []string) error
- func (f *FlagSet) Parsed() bool
- func (f *FlagSet) Pres(name string, usage string) *bool
- func (f *FlagSet) PresVar(p *bool, name string, usage string)
- func (f *FlagSet) PrintDefaults()
- func (f *FlagSet) Set(name string, value []string) error
- func (f *FlagSet) SetAllowIntersperse(allowIntersperse bool)
- func (f *FlagSet) SetOutput(output io.Writer)
- func (f *FlagSet) String(name string, value string, usage string, typeExp string) *string
- func (f *FlagSet) StringSlice(name string, usage string, typeExp string, perFlag int) *[]string
- func (f *FlagSet) StringSliceVar(p *([]string), name string, usage string, typeExp string, perFlag int)
- func (f *FlagSet) StringVar(p *string, name string, value string, usage string, typeExp string)
- func (f *FlagSet) Uint(name string, value uint, usage string, typeExp string) *uint
- func (f *FlagSet) Uint64(name string, value uint64, usage string, typeExp string) *uint64
- func (f *FlagSet) Uint64Var(p *uint64, name string, value uint64, usage string, typeExp string)
- func (f *FlagSet) UintVar(p *uint, name string, value uint, usage string, typeExp string)
- func (f *FlagSet) Var(value Value, flagStr string, usage string, typeExp string, args int)
- func (f *FlagSet) Visit(fn func(*Flag))
- func (f *FlagSet) VisitAll(fn func(*Flag))
- type Getter
- type Param
- type Value
Examples ¶
Constants ¶
This section is empty.
Variables ¶
var CommandLine = NewFlagSet("", ExitOnError)
CommandLine is the default set of command-line flags, parsed from os.Args. The top-level functions such as BoolVar, Arg, and so on are wrappers for the methods of CommandLine.
var Default = "Default: "
Word for default
var ErrHelp = errors.New("help requested")
ErrHelp is the error returned if the -help or -h flag is invoked but no such flag is defined.
var Usage = func() { if len(CommandLine.Title) > 0 { fmt.Fprintf(CommandLine.Output(), "%s\n\n", CommandLine.Title) } post := "" if len(CommandLine.Params) > 0 { post = "[options...] [args...]" } else if len(CommandLine.formal) > 1 { post = "[options...]" } else { post = "[option]" } fmt.Fprintf(CommandLine.Output(), "Usage: %s %s\n", path.Base(os.Args[0]), post) PrintDefaults() }
Usage prints to standard error a usage message documenting all defined command-line flags. The function is a variable that may be changed to point to a custom function.
Functions ¶
func Arg ¶
Arg returns the i'th command-line argument. Arg(0) is the first remaining argument after flags have been processed.
func Bool ¶
Bool defines a bool flag with specified name, default value, and usage string. The return value is the address of a bool variable that stores the value of the flag.
func BoolVar ¶
BoolVar defines a bool flag with specified name, default value, and usage string. The argument p points to a bool variable in which to store the value of the flag.
func Duration ¶
Duration defines a time.Duration flag with specified name, default value, and usage string. The return value is the address of a time.Duration variable that stores the value of the flag.
func DurationVar ¶
DurationVar defines a time.Duration flag with specified name, default value, and usage string. The argument p points to a time.Duration variable in which to store the value of the flag.
func FlagFunc ¶
FlagFunc defines a flag with the specified name and usage string. Each time the flag is seen, fn is called with the value of the flag. If fn returns a non-nil error, it will be treated as a flag value parsing error.
func Float64 ¶
Float64 defines a float64 flag with specified name, default value, and usage string. The return value is the address of a float64 variable that stores the value of the flag.
func Float64Var ¶
Float64Var defines a float64 flag with specified name, default value, and usage string. The argument p points to a float64 variable in which to store the value of the flag.
func GroupingSet ¶
func GroupingSet(grouping string)
GroupingSet creates a grouping set for new flags added. This is helpful if there are many flags and they can be organized in smaller groupings.
func Int ¶
Int defines an int flag with specified name, default value, and usage string. The return value is the address of an int variable that stores the value of the flag.
func Int64 ¶
Int64 defines an int64 flag with specified name, default value, and usage string. The return value is the address of an int64 variable that stores the value of the flag.
func Int64Var ¶
Int64Var defines an int64 flag with specified name, default value, and usage string. The argument p points to an int64 variable in which to store the value of the flag.
func IntVar ¶
IntVar defines an int flag with specified name, default value, and usage string. The argument p points to an int variable in which to store the value of the flag.
func NArg ¶
func NArg() int
NArg is the number of arguments remaining after flags have been processed.
func Parse ¶
func Parse()
Parse parses the command-line flags from os.Args[1:]. Must be called after all flags are defined and before flags are accessed by the program. If AllowIntersperse is set, arguments and flags can be interspersed, that is flags can follow positional arguments.
func Pres ¶
Pres defines a present flag with specified name and usage string. The return value is the address of a bool variable that stores true if seen.
func PresVar ¶
PresVar defines a present flag with specified name and usage string. The return value is the address of a bool variable that stores true if seen.
func PrintDefaults ¶
func PrintDefaults()
PrintDefaults prints to standard error the default values of all defined command-line flags.
func SetAllowIntersperse ¶
func SetAllowIntersperse(allowIntersperse bool)
SetAllowIntersperse tells the parser if flags can be interspersed with other arguments. If AllowIntersperse is set to true, arguments and flags can be interspersed, that is flags can follow positional arguments.
Example of true:
prog -flag1 input1 input2 -flag2
Example of false: (default)
prog -flag1 -flag2 input1 input2
func String ¶
String defines a string flag with specified name, default value, and usage string. The return value is the address of a string variable that stores the value of the flag.
func StringSlice ¶
StringSlice defines a string flag with specified name, default value, and usage string. The return value is the address of a string variable that stores the value of the flag.
Example ¶
fs := params.NewFlagSet("ExampleFunc", params.ContinueOnError) fs.SetOutput(os.Stdout) var install, remove []string fs.StringSliceVar(&install, "i install", "List of packages to install", "PACKAGES", -1) fs.StringSliceVar(&remove, "r remove", "List of packages to install", "PACKAGES", -1) fs.Parse([]string{"--install", "a", "b", "-r", "c", "-i", "d"}) fmt.Printf("{install: %#v, remove: %#v}\n\n", install, remove) fs.PrintDefaults() // {install: []string{"a", "b", "d"}, remove: []string{"c"}} // // Options: // -i, --install PACKAGES List of packages to install // -r, --remove PACKAGES List of packages to install
Output:
func StringSliceVar ¶
StringSliceVar defines a string flag with specified name, default value, and usage string. The argument p points to a string variable in which to store the value of the flag.
func StringVar ¶
StringVar defines a string flag with specified name, default value, and usage string. The argument p points to a string variable in which to store the value of the flag.
func Uint ¶
Uint defines a uint flag with specified name, default value, and usage string. The return value is the address of a uint variable that stores the value of the flag.
func Uint64 ¶
Uint64 defines a uint64 flag with specified name, default value, and usage string. The return value is the address of a uint64 variable that stores the value of the flag.
func Uint64Var ¶
Uint64Var defines a uint64 flag with specified name, default value, and usage string. The argument p points to a uint64 variable in which to store the value of the flag.
func UintVar ¶
UintVar defines a uint flag with specified name, default value, and usage string. The argument p points to a uint variable in which to store the value of the flag.
func Var ¶
Var defines a flag with the specified name and usage string. The type and value of the flag are represented by the first argument, of type Value, which typically holds a user-defined implementation of Value. For instance, the caller could create a flag that turns a comma-separated string into a slice of strings by giving the slice the methods of Value; in particular, Set would decompose the comma-separated string into the slice.
Types ¶
type ErrorHandling ¶
type ErrorHandling int
ErrorHandling defines how to handle flag parsing errors.
const ( ContinueOnError ErrorHandling = iota ExitOnError PanicOnError )
type Flag ¶
type Flag struct { Name []string // name as it appears on command line Usage string // help message Value Value // value as set DefValue string // default value TypeExpected string // helpful hint on what is expected ArgsNeeded int // arg count wanted Grouping string // organize flags into groups Options func(string, string) []string // function to return possible outcomes for bash completion }
A Flag represents the state of a flag.
type FlagSet ¶
type FlagSet struct { // Usage is the function called when an error occurs while parsing flags. // The field is a function (not a method) that may be changed to point to // a custom error handler. Usage func() Title string Params []Param // argument parsers for after flags // SetUsageIndent tells the DefaultPrinter how many spaces to add to before // printing the usage for each flag. By default this is 0 and determined by // the maximum comma seperated name length. Indent int // beginning of line space UsageIndent int // usage column position UsageSpace int // minimum number of spaces required before usage TypeSpace int // minimum number of spaces required before input type string ShowGroupings bool // Show the flags in groups GroupingHeaders func(string, int) string // function used to generate headers, like "Options:" ShowDefaultVal bool // Display the (Default: "") example // FlagKnownAs allows different projects to customise what their flags are // known as, e.g. 'flag', 'option', 'item'. All error/log messages // will use that name when referring to an individual items/flags in this set. // For example, if this value is 'option', the default message 'value for param' // will become 'value for option'. // Default value is 'flag'. FlagKnownAs string // contains filtered or unexported fields }
A FlagSet represents a set of defined flags.
func NewFlagSet ¶
func NewFlagSet(name string, errorHandling ErrorHandling) *FlagSet
NewFlagSet returns a new, empty parameter set with the specified name and error handling property.
func NewFlagSetWithFlagKnownAs ¶
func NewFlagSetWithFlagKnownAs(name string, errorHandling ErrorHandling, aka string) *FlagSet
NewFlagSetWithFlagKnownAs returns a new, empty parameter set with the specified name and error handling property. All error messages and other references to the individual params will use aka, for e.g. if aka = 'option', the message will be 'value for option' not 'value for param'.
func (*FlagSet) Arg ¶
Arg returns the i'th argument. Arg(0) is the first remaining argument after flags have been processed.
func (*FlagSet) Bool ¶
Bool defines a bool flag with specified name, default value, and usage string. The return value is the address of a bool variable that stores the value of the flag.
func (*FlagSet) BoolVar ¶
BoolVar defines a bool flag with specified name, default value, and usage string. The argument p points to a bool variable in which to store the value of the flag.
func (*FlagSet) Duration ¶
func (f *FlagSet) Duration(name string, value time.Duration, usage string, typeExp string) *time.Duration
Duration defines a time.Duration flag with specified name, default value, and usage string. The return value is the address of a time.Duration variable that stores the value of the flag.
func (*FlagSet) DurationVar ¶
func (f *FlagSet) DurationVar(p *time.Duration, name string, value time.Duration, usage string, typeExp string)
DurationVar defines a time.Duration flag with specified name, default value, and usage string. The argument p points to a time.Duration variable in which to store the value of the flag.
func (*FlagSet) ErrorHandling ¶
func (f *FlagSet) ErrorHandling() ErrorHandling
ErrorHandling returns the error handling behavior of the flag set.
func (*FlagSet) FlagFunc ¶
func (f *FlagSet) FlagFunc(name, usage string, typeExp string, argsNeeded int, fn func([]string) error)
FlagFunc defines a flag with the specified name and usage string. Each time the flag is seen, fn is called with the value of the flag. If fn returns a non-nil error, it will be treated as a flag value parsing error.
func (*FlagSet) Float64 ¶
Float64 defines a float64 flag with specified name, default value, and usage string. The return value is the address of a float64 variable that stores the value of the flag.
func (*FlagSet) Float64Var ¶
Float64Var defines a float64 flag with specified name, default value, and usage string. The argument p points to a float64 variable in which to store the value of the flag.
func (*FlagSet) GroupingSet ¶
GroupingSet creates a grouping set for new flags added. This is helpful if there are many flags and they can be organized in smaller groupings.
func (*FlagSet) Init ¶
func (f *FlagSet) Init(name string, errorHandling ErrorHandling)
Init sets the name and error handling property for a parameter set. By default, the zero FlagSet uses an empty name and the ContinueOnError error handling policy.
func (*FlagSet) Int ¶
Int defines an int flag with specified name, default value, and usage string. The return value is the address of an int variable that stores the value of the flag.
func (*FlagSet) Int64 ¶
Int64 defines an int64 flag with specified name, default value, and usage string. The return value is the address of an int64 variable that stores the value of the flag.
func (*FlagSet) Int64Var ¶
Int64Var defines an int64 flag with specified name, default value, and usage string. The argument p points to an int64 variable in which to store the value of the flag.
func (*FlagSet) IntVar ¶
IntVar defines an int flag with specified name, default value, and usage string. The argument p points to an int variable in which to store the value of the flag.
func (*FlagSet) Lookup ¶
Lookup returns the Flag structure of the named flag, returning nil if none exists.
func (*FlagSet) Output ¶
Output returns the destination for usage and error messages. os.Stderr is returned if output was not set or was set to nil.
func (*FlagSet) Parse ¶
Parse parses flag definitions from the argument list, which should not include the command name. Must be called after all flags in the FlagSet are defined and before flags are accessed by the program. The return value will be ErrHelp if --help or -h was set but not defined. If AllowIntersperse is set, arguments and flags can be interspersed, that is flags can follow positional arguments.
func (*FlagSet) Pres ¶
PresVar defines a present flag with specified name and usage string. The return value is the address of a bool variable that stores true if seen.
func (*FlagSet) PresVar ¶
PresVar defines a present flag with specified name and usage string. The return value is the address of a bool variable that stores true if seen.
func (*FlagSet) PrintDefaults ¶
func (f *FlagSet) PrintDefaults()
PrintDefaults prints, to standard error unless configured otherwise, the default values of all defined flags in the set. If there is more than one name for a given flag, the usage information and default value from the shortest will be printed (or the least alphabetically if there are several equally short flag names).
func (*FlagSet) SetAllowIntersperse ¶
SetAllowIntersperse tells the parser if flags can be interspersed with other arguments. If AllowIntersperse is set to true, arguments and flags can be interspersed, that is flags can follow positional arguments.
Example of true:
prog -flag1 input1 input2 -flag2
Example of false: (default)
prog -flag1 -flag2 input1 input2
func (*FlagSet) SetOutput ¶
SetOutput sets the destination for usage and error messages. If output is nil, os.Stderr is used.
func (*FlagSet) String ¶
String defines a string flag with specified name, default value, and usage string. The return value is the address of a string variable that stores the value of the flag.
func (*FlagSet) StringSlice ¶
StringSlice defines a string flag with specified name, default value, and usage string. The return value is the address of a string variable that stores the value of the flag.
func (*FlagSet) StringSliceVar ¶
func (f *FlagSet) StringSliceVar(p *([]string), name string, usage string, typeExp string, perFlag int)
StringSliceVar defines a string flag with specified name, default value, and usage string. The argument p points to a string variable in which to store the value of the flag.
func (*FlagSet) StringVar ¶
StringVar defines a string flag with specified name, default value, and usage string. The argument p points to a string variable in which to store the value of the flag.
func (*FlagSet) Uint ¶
Uint defines a uint flag with specified name, default value, and usage string. The return value is the address of a uint variable that stores the value of the flag.
func (*FlagSet) Uint64 ¶
Uint64 defines a uint64 flag with specified name, default value, and usage string. The return value is the address of a uint64 variable that stores the value of the flag.
func (*FlagSet) Uint64Var ¶
Uint64Var defines a uint64 flag with specified name, default value, and usage string. The argument p points to a uint64 variable in which to store the value of the flag.
func (*FlagSet) UintVar ¶
UintVar defines a uint flag with specified name, default value, and usage string. The argument p points to a uint variable in which to store the value of the flag.
func (*FlagSet) Var ¶
Var defines a flag with the specified name and usage string. The type and value of the flag are represented by the first argument, of type Value, which typically holds a user-defined implementation of Value. For instance, the caller could create a flag that turns a comma-separated string into a slice of strings by giving the slice the methods of Value; in particular, Set would decompose the comma-separated string into the slice.
type Getter ¶
type Getter interface { Value Get() interface{} }
Getter is an interface that allows the contents of a Value to be retrieved. It wraps the Value interface, rather than being part of it, because it appeared after Go 1 and its compatibility rules. All Value types provided by this package satisfy the Getter interface.
type Param ¶
type Param struct { Usage string // help message Value Value // value as set DefValue string // default value TypeExpected string // helpful hint on what is expected Options []string // Available options for tab-fill OptionsFunc func(flagsSeen []Flag, argsSeen []string) []string // Get options for bash completion Test func(flagsSeen []Flag, argsSeen []string) (bool, error) // Options }
type Value ¶
Value is the interface to the dynamic value stored in a flag. (The default value is represented as a string.)
Example ¶
package main import ( "fmt" "github.com/pschou/go-params" "net/url" ) type URLValue struct { URL *url.URL } func (v URLValue) String() string { if v.URL != nil { return v.URL.String() } return "" } func (v URLValue) Set(s []string) error { if u, err := url.Parse(s[0]); err != nil { return err } else { *v.URL = *u } return nil } var u = &url.URL{} func main() { fs := params.NewFlagSet("ExampleValue", params.ExitOnError) fs.Var(&URLValue{u}, "url", "The URL to parse", "ADDRESS", 1) fs.Parse([]string{"--url", "https://golang.org/pkg/flag/"}) fmt.Printf(`{scheme: %q, host: %q, path: %q}`, u.Scheme, u.Host, u.Path) }
Output: {scheme: "https", host: "golang.org", path: "/pkg/flag/"}