flagga

package module
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Jul 23, 2018 License: MIT Imports: 9 Imported by: 2

README

flagga GoDoc Build Status codecov Go Report Card

flagga is an extensible Go library for handling program configuration using (but not limited to) command line arguments, environment variables and JSON.

This idea and API come from Peter Bourgon's Go for Industrial Programming talk at Gophercon Iceland 2018.

It should work as a drop-in replacement for the standard library flag package. The only difference is the fact that NewFlagSet and Init accept a second string for the description.

Goals

  • Be able to configure a program with different sources that have different priorities.
  • Be extensible so anyone can extend the API to provide different sources to get their configuration from (yaml, toml, database?, ...).
  • Be a drop-in replacement for the Go standard flag package with extra features.
  • Have no third-party dependencies.

Install

go get github.com/erizocosmico/flagga

Or use your preferred dependency manager such as dep or vgo.

Usage

var fs flagga.FlagSet

db := fs.String("db", defaultDBURI, "database connection string", flagga.Env("DBURI"))
users := fs.StringList("users", nil, "list of allowed users", flagga.JSON("users"))

err := fs.Parse(os.Args[1:], flagga.JSONVia("config.json"), flagga.EnvPrefix("MYAPP_"))
if err != nil {
    // handle err
}

fmt.Println(*db) // Outputs: "user@localhost:1234/foo"
fmt.Println(strings.Join(*users, ", ")) // Outputs: "jane, joe, alice"

To get the previous results we can invoke the program in the following ways:

echo '{"users":["jane", "joe", "alice"]}' > config.json
./myprogram -db=user@localhost:1234/foo -users=jane -users=joe -users=alice
MYAPP_DBURI=user@localhost:1234/foo ./myprogram
Priority of sources

CLI flags always have priority over environment variables or JSON keys. If a flag is provided using the command line flags, no other sources will be checked for that variable.

The rest of the priorities depend of the order in which the sources are passed to the Parse method. For example, fs.Parse(os.Args, flagga.EnvPrefix("FOO_"), flagga.JSONVia("cfg")) gives more priority to environment variables than to the JSON configuration.

Available Extractors
  • Env: from environment variable sources.
  • JSON: from JSON sources.

YAML and TOML extractors are available in the flaggax repository.

Available Sources
  • EnvPrefix: provides all environment variables matching the given prefix.
  • JSONVia: provides the content of the JSON in the given file.

YAML and TOML sources are available in the flaggax repository.

Custom Sources and Extractors

You can implement your own Sources and Extractors in case your configuration is in a different format. Check out the Source and Extractor interfaces in the package documentation.

Reference

License

MIT, see LICENSE

Documentation

Index

Constants

This section is empty.

Variables

View Source
var ErrHelp = fmt.Errorf("flagga: help requested")

ErrHelp is returned when -h, --h, --help or -help are found.

Functions

This section is empty.

Types

type ErrorHandling

type ErrorHandling byte

ErrorHandling defines what happens if an error is encountered while parsing a flag set.

const (
	// ContinueOnError will not halt the program if an error is encountered.
	ContinueOnError ErrorHandling = iota
	// ExitOnError will call os.Exit(2) after encountering an error.
	ExitOnError
	// PanicOnError will panic after encountering an error.
	PanicOnError
)

type Extractor

type Extractor interface {
	// Get checks the sources and tries to assign the flag value.
	Get(sources []Source, dst Value) (bool, error)
}

Extractor extracts values from the sources to fill the flag value.

func Env

func Env(key string) Extractor

Env returns an Extractor that will match environment variables with the given key.

func JSON

func JSON(key string) Extractor

JSON returns an Extractor that will match the given key in a provided JSON file to set as value for the flag.

type FileSource

type FileSource struct {
	File   string
	Parser ParseFunc
	Value  map[string]interface{}
}

FileSource is a Source that reads a file and parses it using a parser function.

func (*FileSource) Close

func (s *FileSource) Close() error

Close implements the Source interface.

func (*FileSource) Get

func (s *FileSource) Get(key string, dst Value) (bool, error)

Get implements the Source interface.

func (*FileSource) Open

func (s *FileSource) Open() error

Open implements the Source interface.

type Flag

type Flag struct {
	Name       string
	Usage      string
	Value      Value
	Default    interface{}
	Extractors []Extractor
}

Flag is a single flag in the program.

type FlagSet

type FlagSet struct {

	// Usage prints the usage instructions of the flag set.
	Usage func()
	// contains filtered or unexported fields
}

FlagSet is a collection of unique flags.

func NewFlagSet

func NewFlagSet(name, description string, errorHandling ErrorHandling) *FlagSet

NewFlagSet creates a new flag set with the given name, description and error handling policy.

func (*FlagSet) Arg

func (fs *FlagSet) Arg(i int) string

Arg returns the nth argument that has been found.

func (*FlagSet) Args

func (fs *FlagSet) Args() []string

Args returns the arguments that have been found.

func (*FlagSet) Bool

func (fs *FlagSet) Bool(
	name string,
	usage string,
	extractors ...Extractor,
) *bool

Bool adds a new bool flag and returns a pointer to the value that will be filled once the flag set is parsed.

func (*FlagSet) BoolVar

func (fs *FlagSet) BoolVar(
	v *bool,
	name string,
	usage string,
	extractors ...Extractor,
)

BoolVar adds a new bool flag. When the flag set is parsed it will fill the given pointer.

func (*FlagSet) Description

func (fs *FlagSet) Description() string

Description returns the given description to this flag set.

func (*FlagSet) Duration

func (fs *FlagSet) Duration(
	name string,
	defaultValue time.Duration,
	usage string,
	extractors ...Extractor,
) *time.Duration

Duration adds a new time.Duration flag and returns a pointer to the value that will be filled once the flag set is parsed.

func (*FlagSet) DurationList

func (fs *FlagSet) DurationList(
	name string,
	defaultValue []time.Duration,
	usage string,
	extractors ...Extractor,
) *[]time.Duration

DurationList adds a new []time.Duration flag and returns a pointer to the value that will be filled once the flag set is parsed.

func (*FlagSet) DurationListVar

func (fs *FlagSet) DurationListVar(
	v *[]time.Duration,
	name string,
	defaultValue []time.Duration,
	usage string,
	extractors ...Extractor,
)

DurationListVar adds a new []time.Duration flag. When the flag set is parsed it will fill the given pointer.

func (*FlagSet) DurationVar

func (fs *FlagSet) DurationVar(
	v *time.Duration,
	name string,
	defaultValue time.Duration,
	usage string,
	extractors ...Extractor,
)

DurationVar adds a new time.Duration flag. When the flag set is parsed it will fill the given pointer.

func (*FlagSet) Float

func (fs *FlagSet) Float(
	name string,
	defaultValue float64,
	usage string,
	extractors ...Extractor,
) *float64

Float adds a new float64 flag and returns a pointer to the value that will be filled once the flag set is parsed.

func (*FlagSet) FloatList

func (fs *FlagSet) FloatList(
	name string,
	defaultValue []float64,
	usage string,
	extractors ...Extractor,
) *[]float64

FloatList adds a new []float64 flag and returns a pointer to the value that will be filled once the flag set is parsed.

func (*FlagSet) FloatListVar

func (fs *FlagSet) FloatListVar(
	v *[]float64,
	name string,
	defaultValue []float64,
	usage string,
	extractors ...Extractor,
)

FloatListVar adds a new []float64 flag. When the flag set is parsed it will fill the given pointer.

func (*FlagSet) FloatVar

func (fs *FlagSet) FloatVar(
	v *float64,
	name string,
	defaultValue float64,
	usage string,
	extractors ...Extractor,
)

FloatVar adds a new float64 flag. When the flag set is parsed it will fill the given pointer.

func (*FlagSet) Init

func (fs *FlagSet) Init(name, description string, errorHandling ErrorHandling)

Init initializes the flag set with the given name, description and error handling policy.

func (*FlagSet) Int

func (fs *FlagSet) Int(
	name string,
	defaultValue int,
	usage string,
	extractors ...Extractor,
) *int

Int adds a new int flag and returns a pointer to the value that will be filled once the flag set is parsed.

func (*FlagSet) Int64

func (fs *FlagSet) Int64(
	name string,
	defaultValue int64,
	usage string,
	extractors ...Extractor,
) *int64

Int64 adds a new int64 flag and returns a pointer to the value that will be filled once the flag set is parsed.

func (*FlagSet) Int64List

func (fs *FlagSet) Int64List(
	name string,
	defaultValue []int64,
	usage string,
	extractors ...Extractor,
) *[]int64

Int64List adds a new []int64 flag and returns a pointer to the value that will be filled once the flag set is parsed.

func (*FlagSet) Int64ListVar

func (fs *FlagSet) Int64ListVar(
	v *[]int64,
	name string,
	defaultValue []int64,
	usage string,
	extractors ...Extractor,
)

Int64ListVar adds a new []int64 flag. When the flag set is parsed it will fill the given pointer.

func (*FlagSet) Int64Var

func (fs *FlagSet) Int64Var(
	v *int64,
	name string,
	defaultValue int64,
	usage string,
	extractors ...Extractor,
)

Int64Var adds a new int64 flag. When the flag set is parsed it will fill the given pointer.

func (*FlagSet) IntList

func (fs *FlagSet) IntList(
	name string,
	defaultValue []int,
	usage string,
	extractors ...Extractor,
) *[]int

IntList adds a new []int flag and returns a pointer to the value that will be filled once the flag set is parsed.

func (*FlagSet) IntListVar

func (fs *FlagSet) IntListVar(
	v *[]int,
	name string,
	defaultValue []int,
	usage string,
	extractors ...Extractor,
)

IntListVar adds a new []int flag. When the flag set is parsed it will fill the given pointer.

func (*FlagSet) IntVar

func (fs *FlagSet) IntVar(
	v *int,
	name string,
	defaultValue int,
	usage string,
	extractors ...Extractor,
)

IntVar adds a new int flag. When the flag set is parsed it will fill the given pointer.

func (*FlagSet) Lookup

func (fs *FlagSet) Lookup(name string) *Flag

Lookup returns the defined flag with the given name. It will return nil if it's not found.

func (*FlagSet) NArg

func (fs *FlagSet) NArg() int

NArg returns the number of arguments that have been found.

func (*FlagSet) NFlags

func (fs *FlagSet) NFlags() int

NFlags returns the number of flags that have been filled.

func (*FlagSet) Name

func (fs *FlagSet) Name() string

Name returns the given name to this flag set.

func (*FlagSet) Output

func (fs *FlagSet) Output() io.Writer

Output returns the destination writer for the usage and error messages. If no output was set, the default is os.Stderr.

func (*FlagSet) Parse

func (fs *FlagSet) Parse(args []string, sources ...Source) error

Parse fills the flags with values from the given arguments and sources.

func (*FlagSet) Parsed

func (fs *FlagSet) Parsed() bool

Parsed returns whether the flag set has already been parsed.

func (*FlagSet) PrintDefaults

func (fs *FlagSet) PrintDefaults()

PrintDefaults prints all flags with their description and default value.

func (*FlagSet) SetOutput

func (fs *FlagSet) SetOutput(w io.Writer)

SetOutput sets the destination writer for the usage and error messages.

func (*FlagSet) String

func (fs *FlagSet) String(
	name, defaultValue, usage string,
	extractors ...Extractor,
) *string

String adds a new string flag and returns a pointer to the value that will be filled once the flag set is parsed.

func (*FlagSet) StringList

func (fs *FlagSet) StringList(
	name string,
	defaultValue []string,
	usage string,
	extractors ...Extractor,
) *[]string

StringList adds a new []string flag and returns a pointer to the value that will be filled once the flag set is parsed.

func (*FlagSet) StringListVar

func (fs *FlagSet) StringListVar(
	v *[]string,
	name string,
	defaultValue []string,
	usage string,
	extractors ...Extractor,
)

StringListVar adds a new []string flag. When the flag set is parsed it will fill the given pointer.

func (*FlagSet) StringVar

func (fs *FlagSet) StringVar(
	v *string,
	name string,
	defaultValue string,
	usage string,
	extractors ...Extractor,
)

StringVar adds a new string flag. When the flag set is parsed it will fill the given pointer.

func (*FlagSet) Uint

func (fs *FlagSet) Uint(
	name string,
	defaultValue uint,
	usage string,
	extractors ...Extractor,
) *uint

Uint adds a new uint flag and returns a pointer to the value that will be filled once the flag set is parsed.

func (*FlagSet) Uint64

func (fs *FlagSet) Uint64(
	name string,
	defaultValue uint64,
	usage string,
	extractors ...Extractor,
) *uint64

Uint64 adds a new uint64 flag and returns a pointer to the value that will be filled once the flag set is parsed.

func (*FlagSet) Uint64List

func (fs *FlagSet) Uint64List(
	name string,
	defaultValue []uint64,
	usage string,
	extractors ...Extractor,
) *[]uint64

Uint64List adds a new []uint64 flag and returns a pointer to the value that will be filled once the flag set is parsed.

func (*FlagSet) Uint64ListVar

func (fs *FlagSet) Uint64ListVar(
	v *[]uint64,
	name string,
	defaultValue []uint64,
	usage string,
	extractors ...Extractor,
)

Uint64ListVar adds a new []uint64 flag. When the flag set is parsed it will fill the given pointer.

func (*FlagSet) Uint64Var

func (fs *FlagSet) Uint64Var(
	v *uint64,
	name string,
	defaultValue uint64,
	usage string,
	extractors ...Extractor,
)

Uint64Var adds a new uint64 flag. When the flag set is parsedit will fill the given pointer.

func (*FlagSet) UintList

func (fs *FlagSet) UintList(
	name string,
	defaultValue []uint,
	usage string,
	extractors ...Extractor,
) *[]uint

UintList adds a new []uint flag and returns a pointer to the value that will be filled once the flag set is parsed.

func (*FlagSet) UintListVar

func (fs *FlagSet) UintListVar(
	v *[]uint,
	name string,
	defaultValue []uint,
	usage string,
	extractors ...Extractor,
)

UintListVar adds a new []uint flag. When the flag set is parsed it will fill the given pointer.

func (*FlagSet) UintVar

func (fs *FlagSet) UintVar(
	v *uint,
	name string,
	defaultValue uint,
	usage string,
	extractors ...Extractor,
)

UintVar adds a new uint flag. When the flag set is parsed it will fill the given pointer.

type ParseFunc

type ParseFunc func(data []byte, dst interface{}) error

ParseFunc is a function that will parse the given data and put the result into the given destination.

type Source

type Source interface {
	// Open allows the Source to perform some initialization before parsing.
	Open() error
	// Get will try to get the given key from the source and fill the Value.
	Get(key string, dst Value) (bool, error)
	// Close is called after parsing to release all used resources by the
	// source. Close should be tolerant to multiple calls, even if it has
	// not been opened.
	Close() error
}

Source provides values for the flags.

func EnvPrefix

func EnvPrefix(prefix string) Source

EnvPrefix will provide as values the environment variables that match the given prefix.

func JSONVia

func JSONVia(file string) Source

JSONVia returns a Source that will use a JSON file as a provider of flag values.

func NewFileSource

func NewFileSource(file string, parser ParseFunc) Source

NewFileSource returns a Source that will read the given file and use the given parser to extract the contents of it.

type Value

type Value interface {
	// Set the given value as the new value. For slice types, this performs an
	// append if the value is not a slice.
	Set(val interface{}) error
}

Value is a flag value that can be set.

func NewValue

func NewValue(val interface{}) Value

NewValue wraps the pointer into a Value type.

Jump to

Keyboard shortcuts

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