Documentation ¶
Overview ¶
Package flags provides support for working with flag variables, and for managing flag variables by embedding them in structs. A field in a struct can be annotated with a tag that is used to identify it as a variable to be registered with a flag that contains the name of the flag, an initial default value and the usage message. This makes it convenient to colocate flags with related data structures and to avoid large numbers of global variables as are often encountered with complex, multi-level command structures.
Index ¶
- func AllSet(args ...interface{}) bool
- func AtMostOneSet(args ...interface{}) bool
- func ExactlyOneSet(args ...interface{}) bool
- func ExpandEnv(e string) string
- func ParseFlagTag(t string) (name, value, usage string, err error)
- func RegisterFlagsInStruct(fs *flag.FlagSet, tag string, structWithFlags interface{}, ...) error
- type ColonRangeSpec
- type ColonRangeSpecs
- type Commas
- type ErrInvalidRange
- type ErrMap
- type IntRangeSpec
- type IntRangeSpecs
- type Map
- type OneOf
- type RangeSpec
- type RangeSpecs
- type Repeating
- type SetMap
- type Time
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func AllSet ¶
func AllSet(args ...interface{}) bool
AllSet is like ExactlyOne except that it returns true if all of its arguments are set.
func AtMostOneSet ¶
func AtMostOneSet(args ...interface{}) bool
AtMostOneSet is like ExactlyOne except that it returns true if zero or one of its arguments are set.
func ExactlyOneSet ¶
func ExactlyOneSet(args ...interface{}) bool
ExactlyOneSet will return true if exactly one of its arguments is 'set', where 'set' means:
- for strings, the length is > 0.
- fo slices, arrays and maps, their length is > 0.
ExactlyOneSet will panic if any of the arguments are not one of the above types.
func ExpandEnv ¶
ExpandEnv is like os.ExpandEnv but supports 'pseudo' environment variables that have OS specific handling as follows:
On Windows $HOME and $PATH are replaced by and $HOMEDRIVE:\\$HOMEPATH and $Path respectively. On Windows /'s are replaced with \'s.
func ParseFlagTag ¶
ParseFlagTag parses the supplied string into a flag name, default literal value and description components. It is used by CreatenAndRegisterFlagsInStruct to parse the field tags.
The tag format is:
<name>,<default-value>,<usage>
where <name> is the name of the flag, <default-value> is an optional literal default value for the flag and <usage> the detailed description for the flag. <default-value> may be left empty, but <name> and <usage> must be supplied. All fields can be quoted if they need to contain a comma.
Default values may contain shell variables as per flags.ExpandEnv. So $HOME/.configdir may be used on both UNIX and Windows for example.
func RegisterFlagsInStruct ¶
func RegisterFlagsInStruct(fs *flag.FlagSet, tag string, structWithFlags interface{}, valueDefaults map[string]interface{}, usageDefaults map[string]string) error
RegisterFlagsInStruct will selectively register fields in the supplied struct as flags of the appropriate type with the supplied flag.FlagSet. Fields are selected if they have tag of the form `cmdline:"name::<literal>,<usage>"` associated with them, as defined by ParseFlagTag above. In addition to literal default values specified in the tag it is possible to provide computed default values via the valuesDefaults, and also defaults that will appear in the usage string for help messages that override the actual default value. The latter is useful for flags that have a default that is system dependent that is not informative in the usage statement. For example --home-dir which should default to /home/user but the usage message would more usefully say --home-dir=$HOME. Both maps are keyed by the name of the flag, not the field.
Embedded (anonymous) structs may be used provided that they are not themselves tagged. For example:
type CommonFlags struct { A int `cmdline:"a,,use a"` B int `cmdline:"b,,use b"` } flagSet := struct{ CommonFlags C bool `cmdline:"c,,use c"` }
will result in three flags, --a, --b and --c. Note that embedding as a pointer is not supported.
Example ¶
package main import ( "flag" "fmt" "path/filepath" "cloudeng.io/cmdutil/flags" ) func main() { eg := struct { A int `flag:"int-flag,-1,intVar flag"` B string `flag:"string-flag,'some,value,with,a,comma',stringVar flag"` O int H string `flag:"config,$HOME/config,config file in home directotyr"` }{ O: 23, } flagSet := &flag.FlagSet{} err := flags.RegisterFlagsInStruct(flagSet, "flag", &eg, nil, nil) if err != nil { panic(err) } fmt.Println(eg.A) fmt.Println(eg.B) if err := flagSet.Parse([]string{"--int-flag=42"}); err != nil { panic(err) } fmt.Println(eg.A) fmt.Println(eg.B) if got, want := eg.H, filepath.Join(flags.ExpandEnv("$HOME"), "config"); got != want { fmt.Printf("got %v, want %v", got, want) } }
Output: -1 some,value,with,a,comma 42 some,value,with,a,comma
Types ¶
type ColonRangeSpec ¶
type ColonRangeSpec struct {
RangeSpec
}
ColonRangeSpec is like RangeSpec except that : is the separator.
func (*ColonRangeSpec) Set ¶
func (crs *ColonRangeSpec) Set(v string) error
Set implements flag.Value.
func (*ColonRangeSpec) String ¶
func (crs *ColonRangeSpec) String() string
String implements flag.Value.
type ColonRangeSpecs ¶
type ColonRangeSpecs []ColonRangeSpec
ColonRangeSpecs represents comma separated list of ColonRangeSpec's.
func (*ColonRangeSpecs) Set ¶
func (crs *ColonRangeSpecs) Set(val string) error
Set implements flag.Value.
func (*ColonRangeSpecs) String ¶
func (crs *ColonRangeSpecs) String() string
String implements flag.Value.
type Commas ¶
Commas represents the values for flags that contain comma separated values. The optional validate function is applied to each sub value separately.
type ErrInvalidRange ¶
type ErrInvalidRange struct {
// contains filtered or unexported fields
}
ErrInvalidRange represents the error generated for an invalid range. Use errors.Is to test for it.
func (ErrInvalidRange) Is ¶
func (ire ErrInvalidRange) Is(target error) bool
Is implements errors.Is.
type IntRangeSpec ¶
IntRangeSpec represents ranges whose values must be integers.
type IntRangeSpecs ¶
type IntRangeSpecs []IntRangeSpec
IntRangeSpecs represents a comma separated list of IntRangeSpec's.
func (*IntRangeSpecs) Set ¶
func (irs *IntRangeSpecs) Set(val string) error
Set implements flag.Value.
func (*IntRangeSpecs) String ¶
func (irs *IntRangeSpecs) String() string
String implements flag.Value.
type Map ¶
type Map struct {
// contains filtered or unexported fields
}
Map represents a mapping of strings to values that implements flag.Value and can be used for command line flag values. It must be appropriately initialized with name, value pairs and a default value using its Register and Default methods.
Example ¶
package main import ( "fmt" "cloudeng.io/cmdutil/flags" ) func main() { type dependEnum int const ( Dependencies dependEnum = iota Dependents ) mp := flags.Map{}. Register("dependencies", Dependencies). Register("dependents", Dependents). Default(Dependencies) if err := mp.Set("dependents"); err != nil { panic(err) } fmt.Println(mp.String()) fmt.Println(mp.Get().(dependEnum)) }
Output: dependents 1
type OneOf ¶
type OneOf string
OneOf represents a string that can take only one of a fixed set of values.
type RangeSpec ¶
RangeSpec represents a specification for a 'range' such as that used to specify pages to be printed or table columns to be accessed. It implements flag.Value.
Each range is of the general form:
<from>[-<to>] | -<from>[-<to>|-] | <from>-
which allows for the following:
<from> : a single item <from>-<to> : a range of one or more items -<from> : a single item, relative to the end -<from>-<to> : a range, whose start and end are indexed relative the end -<from>- : a range, relative to the end that extends to the end <from>- : a range that extends to the end
Note that the interpretation of these ranges is left to users of this type. For example, intepreting these values as pages in a document could lead to the following:
3 : page 3 2-4 : pages 2 through 4 4-2 : pages 4 through 2 -2 : second to last page -4-2 : fourth from last to second from last -2-4 : second from last to fourth from last -2- : second to last and all following pages 2- : page 2 and all following pages.
type RangeSpecs ¶
type RangeSpecs []RangeSpec
RangeSpecs represents comma separated list of RangeSpec's.
Example ¶
package main import ( "fmt" "cloudeng.io/cmdutil/flags" ) func main() { irs := flags.IntRangeSpecs{} if err := irs.Set("1-2,3-4,-5,8-"); err != nil { panic(err) } fmt.Println(irs) }
Output: [{1 2 false false} {3 4 false false} {5 0 true false} {8 0 false true}]
type Repeating ¶
Repeating represents the values from multiple instances of the same command line argument.
type SetMap ¶
type SetMap struct {
// contains filtered or unexported fields
}
SetMaps represents flag variables, indexed by their address, whose value has someone been set.
func RegisterFlagsInStructWithSetMap ¶
func RegisterFlagsInStructWithSetMap(fs *flag.FlagSet, tag string, structWithFlags interface{}, valueDefaults map[string]interface{}, usageDefaults map[string]string) (*SetMap, error)
RegisterFlagsInStructWithSetMap is like RegisterFlagsInStruct but returns a SetMap which can be used to determine which flag variables have been initialized either with a literal in the struct tag or via the valueDefaults argument.
type Time ¶
type Time struct {
// contains filtered or unexported fields
}
Time represents a time.Time that can be used as a flag.Value. The time can be expressed in time.RFC3339, time.DateTime, time.TimeOnly or time.DateOnly formats.