rig

package module
v1.0.6 Latest Latest
Warning

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

Go to latest
Published: Feb 6, 2021 License: MIT Imports: 14 Imported by: 4

README

Rig

CircleCI Go Report Card GoDoc Coverage Status

Documentation

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func DefaultFlagSet

func DefaultFlagSet() *flag.FlagSet

DefaultFlagSet returns the default FlagSet used by the Parse and ParseStruct functions.

func Parse

func Parse(flags ...*Flag) error

Parse uses a default Config to parse the flags provided using os.Args. This default Config uses a flag.FlagSet with its ErrorHandling set to flag.ExitOnError.

Example
var ss []string
var timeout time.Duration
var f float64

err := Parse(
	Repeatable(&ss, StringGenerator(), "strings", "STRINGS", "repeatable strings flag", validators.ToRepeatable(validators.StringLengthMin(2))),
	Duration(&timeout, "timeout", "TIMEOUT", "duration flag"),
	Float64(&f, "float64", "FLOAT64", "float64 flag", validators.Float64Max(1.4), validators.Float64Max(3.2)),
)
if err != nil {
	os.Exit(2)
}
Output:

func ParseStruct

func ParseStruct(v interface{}, additionalFlags ...*Flag) error

ParseStruct uses a default Config to parse the flages provided using os.Args. StructtoFlags is used to generate the flags. the additionalFlags are applied after the flags derived from the provided struct.

Example
type Configuration struct {
	URL      *url.URL `flag:",require" typehint:"website_url"`
	Strings  []string
	Bool     bool `flag:"boolean" env:"BOOLEAN" usage:"a boolean flag"`
	Timeouts struct {
		ReadTimeout  time.Duration
		WriteTimeout time.Duration
	} `flag:",inline" env:",inline"`

	IgnoreMe float64 `flag:"-"`
}

conf := Configuration{}

err := ParseStruct(&conf)
if err != nil {
	return
}
Output:

Types

type Config

type Config struct {
	FlagSet *flag.FlagSet

	Flags []*Flag
	// contains filtered or unexported fields
}

A Config represents a set of flags to be parsed. The flags are only set on the underlying flag.FlagSet when Config.Parse is called.

func (*Config) Arg

func (c *Config) Arg(i int) string

Arg proxies the .Arg method on the underlying flag.Flagset

func (*Config) Args

func (c *Config) Args() []string

Args proxies the .Args method on the underlying flag.Flagset

func (*Config) Parse

func (c *Config) Parse(arguments []string) error

Parse parses the arguments provided, along with the environment variables (using os.Getenv). Flags parsed from the `arguments` take precedence over the environment variables. The argument list provided should not include the command name.

Example
var ss []string
var timeout time.Duration
var f float64

c := &Config{
	FlagSet: flag.NewFlagSet(os.Args[0], flag.ContinueOnError),
	Flags: []*Flag{
		Repeatable(&ss, StringGenerator(), "strings", "STRINGS", "repeatable strings flag", validators.ToRepeatable(validators.StringLengthMin(2))),
		Duration(&timeout, "timeout", "TIMEOUT", "duration flag"),
		Float64(&f, "float64", "FLOAT64", "float64 flag", validators.Float64Min(1.4), validators.Float64Max(3.2)),
	},
}
err := c.Parse([]string{"-strings=foo,bar", "-timeout=1h20s", "-float64=2.1"})
if err != nil {
	os.Exit(2)
}

fmt.Printf("ss: %q\n", ss)
fmt.Printf("timeout: %v\n", timeout)
fmt.Printf("f: %.2f\n", f)
Output:

ss: ["foo" "bar"]
timeout: 1h0m20s
f: 2.10

func (*Config) Usage

func (c *Config) Usage()

Usage prints the usage for the flags to the output defined on the underlying flag.FlagSet.

type Flag

type Flag struct {
	flag.Value
	Name     string
	Env      string
	Usage    string
	TypeHint string
	Required bool
	// contains filtered or unexported fields
}

A Flag represents the state and definition of a flag.

func Bool

func Bool(v *bool, flag, env, usage string) *Flag

Bool creates a flag for a boolean variable.

func Duration

func Duration(v *time.Duration, flag, env, usage string, validators ...validators.Duration) *Flag

Duration creates a flag for a time.Duration variable.

func Float64

func Float64(v *float64, flag, env, usage string, validators ...validators.Float64) *Flag

Float64 creates a flag for a float64 variable.

func Int

func Int(v *int, flag, env, usage string, validators ...validators.Int) *Flag

Int creates a flag for a int variable.

func Int64

func Int64(v *int64, flag, env, usage string, validators ...validators.Int64) *Flag

Int64 creates a flag for a int64 variable.

func Pointer added in v1.0.6

func Pointer(f *Flag, v interface{}) *Flag

func Regexp

func Regexp(v **regexp.Regexp, flag, env, usage string, validators ...validators.Regexp) *Flag

Regexp creates a flag for a *regexp.Regexp variable.

func Repeatable

func Repeatable(v interface{}, generator Generator, flag, env, usage string, validators ...validators.Repeatable) *Flag

Repeatable creates a flag that is repeatable. The variable `v` provided should be a pointer to a slice. The Generator should generates values that are assignable to the slice's emlements type.

Example
var bb []bool
var ss []string
var dd []time.Duration

c := &Config{
	FlagSet: testingFlagset(),
	Flags: []*Flag{
		Repeatable(&bb, BoolGenerator(), "bool", "BOOL", "repeatable boolean flag"),
		Repeatable(&ss, StringGenerator(), "string", "STRING", "repeatable string flag"),
		Repeatable(&dd, DurationGenerator(), "duration", "DURATION", "repeatable duration flag"),
	},
}

err := c.Parse([]string{"-bool=t,f,t", "-string=foo", "-string=bar", "-duration=5m2s,3m44s"})
if err != nil {
	return
}

fmt.Printf("booleans: %v\nstrings: %q\ndurations: %v\n", bb, ss, dd)
Output:

booleans: [true false true]
strings: ["foo" "bar"]
durations: [5m2s 3m44s]

func Required

func Required(f *Flag) *Flag

Required marks a flag as required, updating the typehint with "required". Noop if Flag.Required is true.

func String

func String(v *string, flag, env, usage string, validators ...validators.String) *Flag

String creates a flag for a string variable.

func StructToFlags

func StructToFlags(v interface{}) ([]*Flag, error)

StructToFlags generates a set of Flag based on the provided struct.

StructToFlags recognizes four struct flags: "flag", "env", "typehint" and "usage". The flag and env names are inferred based on the field name unless values are provided in the struct tags. The field names are transformed from CamelCase to snake_case (using "-" as a separator for the flag).

Additional options "inline" and "require" can be specified in the struct tags ("require" should be specified on the "flag" tag).

A flag or env can be marked as ignored by using `flag:"-"` and `env:"-"` respectively

Example
type Configuration struct {
	URL      *url.URL `flag:",require" typehint:"website_url"`
	Strings  []string
	Bool     bool `flag:"boolean" env:"BOOLEAN" usage:"a boolean flag"`
	Timeouts struct {
		ReadTimeout     time.Duration `env:"-"`
		WriteTimeout    time.Duration
		unexportedField int
	} `flag:",inline" env:",inline"`
	CustomType TestFlagValue

	IgnoreMe float64 `flag:"-"`
}

conf := Configuration{
	CustomType: TestFlagValue{
		Foo: "TestFlagValue",
	},
}

flags, err := StructToFlags(&conf)
if err != nil {
	fmt.Printf("Error: %v\n", err)
	return
}

c := &Config{
	FlagSet: flag.NewFlagSet("test-rig", flag.ContinueOnError),
	Flags:   flags,
}
c.FlagSet.SetOutput(os.Stdout)

c.Usage()
Output:

Usage of test-rig:
  -url website_url           URL=website_url           (required)
  -read-timeout duration                               (default "0s")
  -write-timeout duration    WRITE_TIMEOUT=duration    (default "0s")
  -boolean                   BOOLEAN=bool              a boolean flag (default "false")
  -custom-type value         CUSTOM_TYPE=value         (default "TestFlagValue")
  -strings []string          STRINGS=[]string          (default "[]")

func TypeHint

func TypeHint(f *Flag, typeHint string) *Flag

TypeHint overwrites a Flag's typehint.

Example
var s string

c := &Config{
	FlagSet: testingFlagset(),
	Flags: []*Flag{
		// This will overwrite the default "string" typehint in the usage
		TypeHint(String(&s, "contact", "CONTACT", "Administrative contact"), "email address"),
	},
}

c.Usage()
Output:

Usage of rig-test:
  -contact "email address"    CONTACT="email address"    Administrative contact

func URL

func URL(v **url.URL, flag, env, usage string, validators ...validators.URL) *Flag

URL creates a flag for a *url.URL variable.

func Uint

func Uint(v *uint, flag, env, usage string, validators ...validators.Uint) *Flag

Uint creates a flag for a uint variable.

func Uint64

func Uint64(v *uint64, flag, env, usage string, validators ...validators.Uint64) *Flag

Uint64 creates a flag for a uint64 variable.

func Var

func Var(v flag.Value, flag, env, usage string, validators ...validators.Var) *Flag

Var creates a flag for a flag.Value variable.

func (*Flag) IsBoolFlag

func (f *Flag) IsBoolFlag() bool

IsBoolFlag proxies the .IsBoolFlag method on the underlying flag.Value, if defined.

func (Flag) IsSet added in v1.0.2

func (f Flag) IsSet() bool

IsSet returns true if the flag was set via the command line or the environment

func (*Flag) Set

func (f *Flag) Set(v string) error

Set proxies the .Set method on the underlying flag.Value. It is used to keep track of wether a flag has been set or not.

type Generator

type Generator func() flag.Value

A Generator is a function that returns new values of a type implementing flag.Value. Generators are used with Repeatable to create a new value to be appended to the target slice.

func BoolGenerator

func BoolGenerator() Generator

BoolGenerator is the default boolean generator, to be used with Repeatable for boolean slices.

func DurationGenerator

func DurationGenerator() Generator

DurationGenerator is the default time.Duration generator, to be used with Repeatable for time.Duration slices.

func Float64Generator

func Float64Generator() Generator

Float64Generator is the default float64 generator, to be used with Repeatable for float64 slices.

func Int64Generator

func Int64Generator() Generator

Int64Generator is the default int64 generator, to be used with Repeatable for int64 slices.

func IntGenerator

func IntGenerator() Generator

IntGenerator is the default int generator, to be used with Repeatable for int slices.

func MakeGenerator

func MakeGenerator(v flag.Value) Generator

MakeGenerator creates a Generator that will create values of the underlying type of `v`.

Example
var cc []CustomType // implements the "flag".Value interface

c := &Config{
	FlagSet: testingFlagset(),
	Flags: []*Flag{
		Repeatable(&cc, MakeGenerator(new(CustomType)), "custom", "CUSTOM", "Repeatable flag with a custom type"),
	},
}

err := c.Parse([]string{"-custom=foo,bar"})
if err != nil {
	return
}

fmt.Printf("%v\n", cc)
Output:

[foo bar]

func RegexpGenerator

func RegexpGenerator() Generator

RegexpGenerator is the default *regexp.Regexp generator, to be used with Repeatable for regexp slices.

Example
var rr []*regexp.Regexp

c := &Config{
	FlagSet: testingFlagset(),
	Flags: []*Flag{
		Repeatable(&rr, RegexpGenerator(), "regexp", "REGEXP", "Repeatable regexp flag"),
	},
}

err := c.Parse([]string{"-regexp=^foo.*", "-regexp=[0-9]bar{1,5}"})
if err != nil {
	return
}

fmt.Printf("%v\n", rr)
Output:

[^foo.* [0-9]bar{1 5}]

func StringGenerator

func StringGenerator() Generator

StringGenerator is the default string generator, to be used with Repeatable for string slices.

func URLGenerator

func URLGenerator() Generator

URLGenerator is the default *url.URL generator, to be used with Repeatable for url slices. the slices type must be []urlValue for the generator to work

Example
var uu []*url.URL

c := &Config{
	FlagSet: testingFlagset(),
	Flags: []*Flag{
		Repeatable(&uu, URLGenerator(), "url", "URL", "Repeatable url flag"),
	},
}

err := c.Parse([]string{"-url=https://example.com", "-url=https://cally.com"})
if err != nil {
	return
}

fmt.Printf("%v\n", uu)
Output:

[https://example.com https://cally.com]

func Uint64Generator

func Uint64Generator() Generator

Uint64Generator is the default uint64 generator, to be used with Repeatable for uint64 slices.

func UintGenerator

func UintGenerator() Generator

UintGenerator is the default uint generator, to be used with Repeatable for uint slices.

type PointerValue added in v1.0.6

type PointerValue interface {
	flag.Value

	New(interface{}) flag.Value
	IsNil() bool
}

Directories

Path Synopsis
examples

Jump to

Keyboard shortcuts

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