flag

package
v0.0.0-...-c8a214a Latest Latest
Warning

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

Go to latest
Published: Oct 25, 2018 License: Apache-2.0 Imports: 12 Imported by: 29

Documentation

Overview

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

Index

Examples

Constants

View Source
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.

Variables

This section is empty.

Functions

func Enumerate

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

Enumerate returns a slice containing all Flags in the Flagset

func EnvKey

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

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.

Types

type Choice

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

func NewChoice(allowedValues ...string) Choice

NewChoice produces a Choice with a set of allowed values.

Example
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

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

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

func (*Choice) Set

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

func (cv *Choice) String() string

String returns the current value of the Choice.

func (*Choice) ValidValuesDescription

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

func (cv Choice) WithDefault(value string) Choice

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

type ConstrainedValue

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

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

func Wrap(fs *flag.FlagSet) FlagSet

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

type FromEnv

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

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

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

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

func NewHostPort

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

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

func (hp *HostPort) Addr() string

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

func (*HostPort) Get

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

Get implements flag.Getter.

func (*HostPort) ParsedHostPort

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

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

Set implements flag.Value.

func (*HostPort) String

func (hp *HostPort) String() string

type MockFromEnv

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

MockFromEnv is a mock of FromEnv interface

func NewMockFromEnv

func NewMockFromEnv(ctrl *gomock.Controller) *MockFromEnv

NewMockFromEnv creates a new mock instance

func (*MockFromEnv) AllFlags

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

AllFlags mocks base method

func (*MockFromEnv) EXPECT

func (m *MockFromEnv) EXPECT() *MockFromEnvMockRecorder

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

func (*MockFromEnv) Fill

func (m *MockFromEnv) Fill() error

Fill mocks base method

func (*MockFromEnv) Filled

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

Filled mocks base method

func (*MockFromEnv) Prefix

func (m *MockFromEnv) Prefix() string

Prefix mocks base method

type MockFromEnvMockRecorder

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

MockFromEnvMockRecorder is the mock recorder for MockFromEnv

func (*MockFromEnvMockRecorder) AllFlags

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

AllFlags indicates an expected call of AllFlags

func (*MockFromEnvMockRecorder) Fill

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

Fill indicates an expected call of Fill

func (*MockFromEnvMockRecorder) Filled

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

Filled indicates an expected call of Filled

func (*MockFromEnvMockRecorder) Prefix

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

Prefix indicates an expected call of Prefix

type Strings

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.

Example (WithDelimiter)
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

func NewStrings() Strings

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

Example
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

func NewStringsWithConstraint(allowedValues ...string) Strings

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

Example
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

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

Get retrieves the current value.

func (*Strings) ResetDefault

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

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

func (ssv *Strings) String() string

Retrieves the values set on Strings joined by the delimiter.

func (*Strings) ValidValuesDescription

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

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

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

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

func NewTimestamp(defaultTime time.Time) Timestamp

NewTimestamp creates a new Timestamp with the given default time.

func (*Timestamp) Get

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

Get retrieves the current value of the Timestamp.

func (*Timestamp) Set

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

Set sets the current value of the Timestamp.

func (*Timestamp) String

func (t *Timestamp) String() string

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

Directories

Path Synopsis
Package 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 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.

Jump to

Keyboard shortcuts

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