nonstdlib: github.com/turbinelabs/nonstdlib/flag Index | Examples | Files | Directories

package flag

import "github.com/turbinelabs/nonstdlib/flag"

Package flag provides convenience methods for dealing with golang flag.FlagSets

Index

Examples

Package Files

choice.go flag.go flagset.go fromenv.go gen_flagset.go gen_prefixed_flagset.go hostport.go mock_fromenv.go prefixed_flagset.go strings.go timestamp.go

Constants

const TimestampConversionFencepost = int64(95617584000)

TimestampConversionFencepost represents an integer time value. Values larger than this are assumed to be in milliseconds since the Unix epoch. Treated as millisecons since the epoch, this timestamp represents 1973-01-11T16:26:24Z. Treated as seconds, this timestamp represents 5000-01-01:00:00:00Z.

func Enumerate Uses

func Enumerate(flagset *flag.FlagSet) []*flag.Flag

Enumerate returns a slice containing all Flags in the Flagset

func EnvKey Uses

func EnvKey(parts ...string) string

EnvKey produces a namespaced environment variable key, concatenates a prefix and key with an infix underscore, replacing all non-alphanumeric, non-underscore characters with underscores, and upper-casing the entire string

func IsSet Uses

func IsSet(flagset *flag.FlagSet, name string) bool

IsSet indicates whether a given Flag in a FlagSet has been set or not. The name should be the same value (case-sensitive) as that passed to the FlagSet methods for constructing flags.

type Choice Uses

type Choice struct {
    // Populated from the command line.
    Choice *string

    // All possible values allowed to appear in Choice.
    AllowedValues []string
}

Choice conforms to the flag.Value and flag.Getter interfaces, and can be used populate a slice of strings from a flag.Flag.

func NewChoice Uses

func NewChoice(allowedValues ...string) Choice

NewChoice produces a Choice with a set of allowed values.

Code:

var choice Choice // typically a field in a struct
choice = NewChoice("a", "b", "c")

flagset := flag.NewFlagSet("example", flag.PanicOnError)
flagset.Var(
    &choice,
    "x",
    "Flag help. Allowed values: "+choice.ValidValuesDescription(),
)

flagset.Parse([]string{"-x=c"})

fmt.Println(choice.String())

Output:

c

func (*Choice) Get Uses

func (cv *Choice) Get() interface{}

Get retrieves the current value of the Choice as an interface{}.

func (*Choice) Set Uses

func (cv *Choice) Set(value string) error

Set sets the current value of the Choice, returning an error if the value is not one of the available choices.

func (*Choice) String Uses

func (cv *Choice) String() string

String returns the current value of the Choice.

func (*Choice) ValidValuesDescription Uses

func (cv *Choice) ValidValuesDescription() string

ValidValuesDescription returns a string describing the allowed values for this Choice. For example: "a", "b", or "c".

func (Choice) WithDefault Uses

func (cv Choice) WithDefault(value string) Choice

WithDefault assigns a default value. If value is not a valid choice it is ignored.

type ConstrainedValue Uses

type ConstrainedValue interface {
    flag.Value

    // ValidValuesDescription provides a description of the value
    // values for this ContrainedValue suiteable for use in flag
    // usage text.
    ValidValuesDescription() string
}

ConstrainedValue is a flag.Value with constraints on it assigned value. Typically the constraints limit a flag to a given set of strings.

type FlagSet Uses

type FlagSet interface {
    // Scope creates a new scoped FlagSet. The name of any flag
    // added to the new FlagSet is prefixed with the given
    // prefix. In the flag's uage, the expression "{{NAME}}", is
    // replaced with the given description.
    Scope(prefix, description string) FlagSet

    // GetScope retrieves this FlagSet's scoping prefix, including
    // a trailing period.
    GetScope() string

    // Unwrap returns the flag.FlagSet underlying this FlagSet.
    Unwrap() *flag.FlagSet

    // Var defines a flag with the specified name and usage. The
    // flag's type and value are derived from value. See
    // flag.FlagSet.Var for more information.
    Var(value flag.Value, name string, usage string)

    // HostPortVar defines a HostPort flag with the specified name,
    // default value, and usage string. The argument hp points to a
    // HostPort variable in which to store the value of the flag.
    // The flag accepts "host:port" strings.
    HostPortVar(hp *HostPort, name string, value HostPort, usage string)

    // HostPort defines a HostPort flag with the specified name,
    // default value, and usage string. The return value is the
    // address of a HostPort variable that stores the value of the
    // flag. The flag accepts "host:port" strings.
    HostPort(name string, value HostPort, usage string) *HostPort

    // BoolVar defines a bool flag with the specified name,
    // default value, and usage. The flag's value is stored in p.
    BoolVar(p *bool, name string, value bool, usage string)

    // Bool defines a bool flag with the specified name,
    // default value, and usage. The return value is a pointer
    // to a variable that stores the flag's value.
    Bool(name string, value bool, usage string) *bool

    // DurationVar defines a time.Duration flag with the specified name,
    // default value, and usage. The flag's value is stored in p.
    DurationVar(p *time.Duration, name string, value time.Duration, usage string)

    // Duration defines a time.Duration flag with the specified name,
    // default value, and usage. The return value is a pointer
    // to a variable that stores the flag's value.
    Duration(name string, value time.Duration, usage string) *time.Duration

    // Float64Var defines a float64 flag with the specified name,
    // default value, and usage. The flag's value is stored in p.
    Float64Var(p *float64, name string, value float64, usage string)

    // Float64 defines a float64 flag with the specified name,
    // default value, and usage. The return value is a pointer
    // to a variable that stores the flag's value.
    Float64(name string, value float64, usage string) *float64

    // IntVar defines a int flag with the specified name,
    // default value, and usage. The flag's value is stored in p.
    IntVar(p *int, name string, value int, usage string)

    // Int defines a int flag with the specified name,
    // default value, and usage. The return value is a pointer
    // to a variable that stores the flag's value.
    Int(name string, value int, usage string) *int

    // Int64Var defines a int64 flag with the specified name,
    // default value, and usage. The flag's value is stored in p.
    Int64Var(p *int64, name string, value int64, usage string)

    // Int64 defines a int64 flag with the specified name,
    // default value, and usage. The return value is a pointer
    // to a variable that stores the flag's value.
    Int64(name string, value int64, usage string) *int64

    // StringVar defines a string flag with the specified name,
    // default value, and usage. The flag's value is stored in p.
    StringVar(p *string, name string, value string, usage string)

    // String defines a string flag with the specified name,
    // default value, and usage. The return value is a pointer
    // to a variable that stores the flag's value.
    String(name string, value string, usage string) *string

    // UintVar defines a uint flag with the specified name,
    // default value, and usage. The flag's value is stored in p.
    UintVar(p *uint, name string, value uint, usage string)

    // Uint defines a uint flag with the specified name,
    // default value, and usage. The return value is a pointer
    // to a variable that stores the flag's value.
    Uint(name string, value uint, usage string) *uint

    // Uint64Var defines a uint64 flag with the specified name,
    // default value, and usage. The flag's value is stored in p.
    Uint64Var(p *uint64, name string, value uint64, usage string)

    // Uint64 defines a uint64 flag with the specified name,
    // default value, and usage. The return value is a pointer
    // to a variable that stores the flag's value.
    Uint64(name string, value uint64, usage string) *uint64
}

FlagSet represents an optionally scoped *flag.FlagSet.

func Wrap Uses

func Wrap(fs *flag.FlagSet) FlagSet

Wrap converts an existing *flag.FlagSet into a FlagSet with no scope.

type FromEnv Uses

type FromEnv interface {
    // Prefix returns the environment key prefix, eg "SOME_PREFIX_"
    Prefix() string

    // Fill parses all registered flags in the FlagSet, and if they are not already
    // set it attempts to set their values from environment variables. Environment
    // variables take the name of the flag but are UPPERCASE, have the given prefix,
    // and non-alphanumeric+underscore chars are replaced by underscores.
    //
    // For example:
    //  some-flag -> SOME_PREFIX_SOME_FLAG
    //
    // the provided map[string]string is also populated with the keys and values
    // added to the FlagSet.
    Fill() error

    // Filled returns a map of the environment keys and values for flags currently
    // filled from the environment. Values for flags marked sensitive will be
    // redacted
    Filled() map[string]string

    // AllFlags returns a slice containing all Flags in the underlying Flagset
    AllFlags() []*flag.Flag
}

FromEnv supports operations on a FlagSet based on environment variables. In particular, FromEnv allows one to fill a FlagSet from the environment and then inspect the results.

func NewFromEnv Uses

func NewFromEnv(fs *flag.FlagSet, scopes ...string) FromEnv

NewFromEnv produces a FromEnv, using the provided FlagSet and scopes. The scopes are used to produce the environment key prefix, by uppercasing, replacing non-alphanumeric+underscore characters with underscores, and concatenating with underscores.

For example:

{"foo-foo", "bar.bar", "baz"} -> "FOO_FOO_BAR_BAR_BAZ"

type HostPort Uses

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

HostPort represents the value of a TCP host:port flag.

func NewHostPort Uses

func NewHostPort(s string) HostPort

NewHostPort constructs a HostPort from the given string. If the given argument is not a valid HostPort, a HostPort matching ":0" is returned.

func NewHostPortWithDefaultPort Uses

func NewHostPortWithDefaultPort(s string, getPort func() int) HostPort

NewHostPortWithDefaultPort constructs a HostPort from the given host:port and a port lookup function. This makes the port portion of the host:port string optional both in this constructor and in command line flags. The port lookup function is used to resolve the port during a call Addr(), String(), or ParsedHostPort() unless command line flags have specified an explicit port name or number.

func (*HostPort) Addr Uses

func (hp *HostPort) Addr() string

Addr returns a "host:port" string suitable for use by net.Dial or net.Listen.

func (*HostPort) Get Uses

func (hp *HostPort) Get() interface{}

Get implements flag.Getter.

func (*HostPort) ParsedHostPort Uses

func (hp *HostPort) ParsedHostPort() (string, int)

ParsedHostPort returns the host string (including brackets if they were originally present), and a numeric port.

func (*HostPort) Set Uses

func (hp *HostPort) Set(s string) error

Set implements flag.Value.

func (*HostPort) String Uses

func (hp *HostPort) String() string

type MockFromEnv Uses

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

MockFromEnv is a mock of FromEnv interface

func NewMockFromEnv Uses

func NewMockFromEnv(ctrl *gomock.Controller) *MockFromEnv

NewMockFromEnv creates a new mock instance

func (*MockFromEnv) AllFlags Uses

func (m *MockFromEnv) AllFlags() []*flag.Flag

AllFlags mocks base method

func (*MockFromEnv) EXPECT Uses

func (m *MockFromEnv) EXPECT() *MockFromEnvMockRecorder

EXPECT returns an object that allows the caller to indicate expected use

func (*MockFromEnv) Fill Uses

func (m *MockFromEnv) Fill() error

Fill mocks base method

func (*MockFromEnv) Filled Uses

func (m *MockFromEnv) Filled() map[string]string

Filled mocks base method

func (*MockFromEnv) Prefix Uses

func (m *MockFromEnv) Prefix() string

Prefix mocks base method

type MockFromEnvMockRecorder Uses

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

MockFromEnvMockRecorder is the mock recorder for MockFromEnv

func (*MockFromEnvMockRecorder) AllFlags Uses

func (mr *MockFromEnvMockRecorder) AllFlags() *gomock.Call

AllFlags indicates an expected call of AllFlags

func (*MockFromEnvMockRecorder) Fill Uses

func (mr *MockFromEnvMockRecorder) Fill() *gomock.Call

Fill indicates an expected call of Fill

func (*MockFromEnvMockRecorder) Filled Uses

func (mr *MockFromEnvMockRecorder) Filled() *gomock.Call

Filled indicates an expected call of Filled

func (*MockFromEnvMockRecorder) Prefix Uses

func (mr *MockFromEnvMockRecorder) Prefix() *gomock.Call

Prefix indicates an expected call of Prefix

type Strings Uses

type Strings struct {
    // Populated from the command line.
    Strings []string

    // All possible values allowed to appear in Strings. An empty
    // slice means any value is allowed in Strings.
    AllowedValues []string

    // Delimiter used to parse the string from the command line.
    Delimiter string
    // contains filtered or unexported fields
}

Strings conforms to the flag.Value and flag.Getter interfaces, and can be used populate a slice of strings from a flag.Flag. After command line parsing, the values can be retrieved via the Strings field. This implementation of flag.Value accepts multiple values via a single flag (e.g., "-flag=a,b"), via repetition of the flag (e.g., "-flag=a -flag=b"), or a combination of the two styles. Use ResetDefault to configure default values or to prepare Strings for re-use.

Code:

var strings Strings // typically a field in a struct
strings = Strings{Delimiter: ";"}

flagset := flag.NewFlagSet("example", flag.PanicOnError)
flagset.Var(
    &strings,
    "x",
    "Flag help. Allowed values: "+strings.ValidValuesDescription(),
)

flagset.Parse([]string{"-x=one;two"})

for _, selected := range strings.Strings {
    fmt.Println(selected)
}

Output:

one
two

func NewStrings Uses

func NewStrings() Strings

NewStrings produces a Strings with the default delimiter (",").

Code:

var strings Strings // typically a field in a struct
strings = NewStrings()

flagset := flag.NewFlagSet("example", flag.PanicOnError)
flagset.Var(
    &strings,
    "x",
    "Flag help.",
)

flagset.Parse([]string{"-x=a,b,c"})

for _, selected := range strings.Strings {
    fmt.Println(selected)
}

Output:

a
b
c

func NewStringsWithConstraint Uses

func NewStringsWithConstraint(allowedValues ...string) Strings

NewStringsWithConstraint produces a Strings with a set of allowed values and the default delimiter (",").

Code:

var strings Strings // typically a field in a struct
strings = NewStringsWithConstraint("choice1", "option2", "possibility3")

flagset := flag.NewFlagSet("example", flag.PanicOnError)
flagset.Var(
    &strings,
    "x",
    "Flag help. Allowed values: "+strings.ValidValuesDescription(),
)

flagset.Parse([]string{"-x=choice1,possibility3"})

for _, selected := range strings.Strings {
    fmt.Println(selected)
}

Output:

choice1
possibility3

func (*Strings) Get Uses

func (ssv *Strings) Get() interface{}

Get retrieves the current value.

func (*Strings) ResetDefault Uses

func (ssv *Strings) ResetDefault(values ...string)

ResetDefault resets Strings for use and assigns the given values as the default value. Any call to Set (e.g., via flag.FlagSet) will replace these values. Default values are not checked against the AllowedValues.

func (*Strings) Set Uses

func (ssv *Strings) Set(value string) error

Set sets the current value. The first call (after initialization or a call to ResetDefault) will replace all current values. Subsequent calls append values. This allows multiple values to be set with a single command line flag, or the use of multiple instances of the flag to append multiple values.

func (*Strings) String Uses

func (ssv *Strings) String() string

Retrieves the values set on Strings joined by the delimiter.

func (*Strings) ValidValuesDescription Uses

func (ssv *Strings) ValidValuesDescription() string

ValidValuesDescription returns a string describing the allowed values for this Strings. For example: "a", "b", or "c". If this Strings is unconstrained, it returns an empty string.

type TestFlagSet Uses

type TestFlagSet interface {
    FlagSet

    // Parse invokes the Parse function of the underlying
    // flag.FlagSet as a convenience for tests.
    Parse(args []string) error
}

TestFlagSet represents an optionally scoped FlagSet for tests. It differs from FlagSet only in that methods not normally needed by consumers of FlagSet are directly available.

func NewTestFlagSet Uses

func NewTestFlagSet() TestFlagSet

NewTestFlagSet creates a new FlagSet suitable for tests. It has no prefix, contains no flags, and the unwrapped flag.FlagSet will panic on parse errors.

type Timestamp Uses

type Timestamp struct {
    Value time.Time
}

Timestamp conforms to the flag.Value and flag.Getter interfaces. It can be used to populate a timestamp from a command line argument. It accepts the following inputs:

- timestamps in time.RFC3339Nano format (fractional seconds

optional)

- integer seconds since the Unix epoch (see

TimestampConversionFencepost)

- integer milliseconds since the Unix epoch (see

TimestampConversionFencepost)

- "now" (case insensitive)

func NewTimestamp Uses

func NewTimestamp(defaultTime time.Time) Timestamp

NewTimestamp creates a new Timestamp with the given default time.

func (*Timestamp) Get Uses

func (t *Timestamp) Get() interface{}

Get retrieves the current value of the Timestamp.

func (*Timestamp) Set Uses

func (t *Timestamp) Set(value string) error

Set sets the current value of the Timestamp.

func (*Timestamp) String Uses

func (t *Timestamp) String() string

String returns the current value of the Timestamp as a string in RFC33339 Nano format.

Directories

PathSynopsis
usagePackage usages provides a mechanism to insert and recover richer usage information (eg whether a flag is required, whether it contains sensitive information) into and from a flag.Flag usage string, respectively.

Package flag imports 12 packages (graph) and is imported by 26 packages. Updated 2018-07-12. Refresh now. Tools for package owners.