flags

package
v0.0.0-...-e2c53ed Latest Latest
Warning

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

Go to latest
Published: Mar 26, 2024 License: Apache-2.0 Imports: 12 Imported by: 13

README

Package cloudeng.io/cmdutil/flags

import cloudeng.io/cmdutil/flags

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.

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:

  1. for strings, the length is > 0.
  2. 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
func ExpandEnv(e string) string

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
func ParseFlagTag(t string) (name, value, usage string, err error)

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:

,,

where is the name of the flag, is an optional literal default value for the flag and the detailed description for the flag. may be left empty, but and 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.

Types

Type ColonRangeSpec
type ColonRangeSpec struct {
	RangeSpec
}

ColonRangeSpec is like RangeSpec except that : is the separator.

Methods
func (crs *ColonRangeSpec) Set(v string) error

Set implements flag.Value.

func (crs *ColonRangeSpec) String() string

String implements flag.Value.

Type ColonRangeSpecs
type ColonRangeSpecs []ColonRangeSpec

ColonRangeSpecs represents comma separated list of ColonRangeSpec's.

Methods
func (crs *ColonRangeSpecs) Set(val string) error

Set implements flag.Value.

func (crs *ColonRangeSpecs) String() string

String implements flag.Value.

Type Commas
type Commas struct {
	Values   []string
	Validate func(string) error
}

Commas represents the values for flags that contain comma separated values. The optional validate function is applied to each sub value separately.

Methods
func (c *Commas) Set(v string) error

Set implements flag.Value.

func (c *Commas) String() string

String inplements flag.Value.

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.

Methods
func (ire *ErrInvalidRange) Error() string

Error implements error.

func (ire ErrInvalidRange) Is(target error) bool

Is implements errors.Is.

Type ErrMap
type ErrMap struct {
	// contains filtered or unexported fields
}
Methods
func (me *ErrMap) Error() string

Error implements error.

func (me ErrMap) Is(target error) bool

Is implements errors.Is.

Type IntRangeSpec
type IntRangeSpec struct {
	From, To      int
	RelativeToEnd bool
	ExtendsToEnd  bool
}

IntRangeSpec represents ranges whose values must be integers.

Methods
func (ir *IntRangeSpec) Set(val string) error

Set implements flag.Value.

func (ir *IntRangeSpec) String() string

String implements flag.Value.

Type IntRangeSpecs
type IntRangeSpecs []IntRangeSpec

IntRangeSpecs represents a comma separated list of IntRangeSpec's.

Methods
func (irs *IntRangeSpecs) Set(val string) error

Set implements flag.Value.

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.

Methods
func (ef Map) Default(val interface{}) Map
func (ef *Map) Get() interface{}

Value implements flag.Getter.

func (ef Map) Register(name string, val interface{}) Map
func (ef *Map) Set(v string) error

Set implements flag.Value.

func (ef *Map) String() string

String implements flag.Value.

Type OneOf
type OneOf string

OneOf represents a string that can take only one of a fixed set of values.

Methods
func (ef OneOf) Validate(value string, values ...string) error

Validate ensures that the instance of OneOf has one of the specified set values.

Type RangeSpec
type RangeSpec struct {
	From, To      string
	RelativeToEnd bool
	ExtendsToEnd  bool
}

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.
Methods
func (rs *RangeSpec) Set(v string) error

Set implements flag.Value.

func (rs RangeSpec) String() string

String implements flag.Value.

Type RangeSpecs
type RangeSpecs []RangeSpec

RangeSpecs represents comma separated list of RangeSpec's.

Methods
func (rs *RangeSpecs) Set(val string) error

Set implements flag.Value.

func (rs *RangeSpecs) String() string

String implements flag.Value.

Type Repeating
type Repeating struct {
	Values   []string
	Validate func(string) error
}

Repeating represents the values from multiple instances of the same command line argument.

Methods
func (r *Repeating) Get() interface{}

Get inplements flag.Getter.

func (r *Repeating) Set(v string) error

Set inplements flag.Value.

func (r *Repeating) String() string

String inplements flag.Value.

Type SetMap
type SetMap struct {
	// contains filtered or unexported fields
}

SetMaps represents flag variables, indexed by their address, whose value has someone been set.

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

Methods
func (sm *SetMap) IsSet(field interface{}) (string, bool)

IsSet returns true if the supplied flag variable's value has been set, either via a string literal in the struct or via the valueDefaults argument to RegisterFlagsInStructWithSetMap.

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.

Methods
func (tf *Time) Get() interface{}

Value implements flag.Getter.

func (tf *Time) IsDefault() bool

IsSet returns true if the value has been set.

func (tf *Time) Set(v string) error

Set implements flag.Value.

func (tf *Time) String() string

String implements flag.Value.

Examples

ExampleRegisterFlagsInStruct
ExampleMap
ExampleRangeSpecs

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

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:

  1. for strings, the length is > 0.
  2. 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

func ExpandEnv(e string) string

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

func ParseFlagTag(t string) (name, value, usage string, err error)

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

type Commas struct {
	Values   []string
	Validate func(string) error
}

Commas represents the values for flags that contain comma separated values. The optional validate function is applied to each sub value separately.

func (*Commas) Set

func (c *Commas) Set(v string) error

Set implements flag.Value.

func (*Commas) String

func (c *Commas) String() string

String inplements flag.Value.

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

func (ire *ErrInvalidRange) Error() string

Error implements error.

func (ErrInvalidRange) Is

func (ire ErrInvalidRange) Is(target error) bool

Is implements errors.Is.

type ErrMap

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

func (*ErrMap) Error

func (me *ErrMap) Error() string

Error implements error.

func (ErrMap) Is

func (me ErrMap) Is(target error) bool

Is implements errors.Is.

type IntRangeSpec

type IntRangeSpec struct {
	From, To      int
	RelativeToEnd bool
	ExtendsToEnd  bool
}

IntRangeSpec represents ranges whose values must be integers.

func (*IntRangeSpec) Set

func (ir *IntRangeSpec) Set(val string) error

Set implements flag.Value.

func (*IntRangeSpec) String

func (ir *IntRangeSpec) String() string

String implements flag.Value.

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

func (Map) Default

func (ef Map) Default(val interface{}) Map

func (*Map) Get

func (ef *Map) Get() interface{}

Value implements flag.Getter.

func (Map) Register

func (ef Map) Register(name string, val interface{}) Map

func (*Map) Set

func (ef *Map) Set(v string) error

Set implements flag.Value.

func (*Map) String

func (ef *Map) String() string

String implements flag.Value.

type OneOf

type OneOf string

OneOf represents a string that can take only one of a fixed set of values.

func (OneOf) Validate

func (ef OneOf) Validate(value string, values ...string) error

Validate ensures that the instance of OneOf has one of the specified set values.

type RangeSpec

type RangeSpec struct {
	From, To      string
	RelativeToEnd bool
	ExtendsToEnd  bool
}

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.

func (*RangeSpec) Set

func (rs *RangeSpec) Set(v string) error

Set implements flag.Value.

func (RangeSpec) String

func (rs RangeSpec) String() string

String implements flag.Value.

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

func (*RangeSpecs) Set

func (rs *RangeSpecs) Set(val string) error

Set implements flag.Value.

func (*RangeSpecs) String

func (rs *RangeSpecs) String() string

String implements flag.Value.

type Repeating

type Repeating struct {
	Values   []string
	Validate func(string) error
}

Repeating represents the values from multiple instances of the same command line argument.

func (*Repeating) Get

func (r *Repeating) Get() interface{}

Get inplements flag.Getter.

func (*Repeating) Set

func (r *Repeating) Set(v string) error

Set inplements flag.Value.

func (*Repeating) String

func (r *Repeating) String() string

String inplements flag.Value.

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.

func (*SetMap) IsSet

func (sm *SetMap) IsSet(field interface{}) (string, bool)

IsSet returns true if the supplied flag variable's value has been set, either via a string literal in the struct or via the valueDefaults argument to RegisterFlagsInStructWithSetMap.

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.

func (*Time) Get

func (tf *Time) Get() interface{}

Value implements flag.Getter.

func (*Time) IsDefault

func (tf *Time) IsDefault() bool

IsSet returns true if the value has been set.

func (*Time) Set

func (tf *Time) Set(v string) error

Set implements flag.Value.

func (*Time) String

func (tf *Time) String() string

String implements flag.Value.

Jump to

Keyboard shortcuts

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