ff

package module
v1.7.1 Latest Latest
Warning

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

Go to latest
Published: Sep 27, 2021 License: Apache-2.0 Imports: 8 Imported by: 76

README

ff Latest Release GoDoc builds.sr.ht status

ff stands for flags-first, and provides an opinionated way to populate a flag.FlagSet with configuration data from the environment. By default, it parses only from the command line, but you can enable parsing from a configuration file and/or environmental variables.

With everything enabled, the priority order is:

  1. Command line flags (highest priority)
  2. Configuration file
  3. Environment variables (lowest priority)

Usage

Define a flag.FlagSet in your func main.

func main() {
	fs := flag.NewFlagSet("my-program", flag.ExitOnError)
	var (
		listenAddr = fs.String("listen-addr", "localhost:8080", "listen address")
		refresh    = fs.Duration("refresh", 15*time.Second, "refresh interval")
		debug      = fs.Bool("debug", false, "log debug information")
		_          = fs.String("config", "", "config file (optional)")
	)

Then, call ff.Parse instead of fs.Parse.

	ff.Parse(fs, os.Args[1:],
		ff.WithConfigFileFlag("config"),
		ff.WithConfigFileParser(ff.PlainParser),
		ff.WithEnvVarPrefix("MY_PROGRAM"),
	)

This example will parse flags from the commandline args, just like regular package flag, with the highest priority. If a -config file is specified, it will try to parse it using the PlainParser, which expects files in this format.

listen-addr localhost:8080
refresh 30s
debug true

You could also use the JSONParser, which expects a JSON object.

{
	"listen-addr": "localhost:8080",
	"refresh": "30s",
	"debug": true
}

Or, you could write your own config file parser.

// ConfigFileParser interprets the config file represented by the reader
// and calls the set function for each parsed flag pair.
type ConfigFileParser func(r io.Reader, set func(name, value string) error) error

Finally, it will look in the environment for variables with a MY_PROGRAM prefix. Flag names are capitalized, and separator characters are converted to underscores. In this case, for example, MY_PROGRAM_LISTEN_ADDR would match to listen-addr.

ffcli

Building a commandline application in the style of kubectl or docker? Consider package ffcli.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func JSONParser

func JSONParser(r io.Reader, set func(name, value string) error) error

JSONParser is a parser for config files in JSON format. Input should be an object. The object's keys are treated as flag names, and the object's values as flag values. If the value is an array, the flag will be set multiple times.

func Parse

func Parse(fs *flag.FlagSet, args []string, options ...Option) error

Parse the flags in the flag set from the provided (presumably commandline) args. Additional options may be provided to parse from a config file and/or environment variables in that priority order.

func PlainParser

func PlainParser(r io.Reader, set func(name, value string) error) error

PlainParser is a parser for config files in an extremely simple format. Each line is tokenized as a single key/value pair. The first whitespace-delimited token in the line is interpreted as the flag name, and all remaining tokens are interpreted as the value. Any leading hyphens on the flag name are ignored.

Types

type ConfigFileParser

type ConfigFileParser func(r io.Reader, set func(name, value string) error) error

ConfigFileParser interprets the config file represented by the reader and calls the set function for each parsed flag pair.

type Context

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

Context contains private fields used during parsing.

type JSONParseError

type JSONParseError struct {
	Inner error
}

JSONParseError wraps all errors originating from the JSONParser.

func (JSONParseError) Error

func (e JSONParseError) Error() string

Error implenents the error interface.

func (JSONParseError) Unwrap

func (e JSONParseError) Unwrap() error

Unwrap implements the xerrors.Wrapper interface, allowing xerrors.Is and xerrors.As to work with JSONParseErrors.

type Option

type Option func(*Context)

Option controls some aspect of parse behavior.

func WithAllowMissingConfigFile

func WithAllowMissingConfigFile(allow bool) Option

WithAllowMissingConfigFile will permit parse to succeed, even if a provided config file doesn't exist.

func WithConfigFile

func WithConfigFile(filename string) Option

WithConfigFile tells parse to read the provided filename as a config file. Requires WithConfigFileParser, and overrides WithConfigFileFlag.

func WithConfigFileFlag

func WithConfigFileFlag(flagname string) Option

WithConfigFileFlag tells parse to treat the flag with the given name as a config file. Requires WithConfigFileParser, and is overridden by WithConfigFile.

func WithConfigFileParser

func WithConfigFileParser(p ConfigFileParser) Option

WithConfigFileParser tells parse how to interpret the config file provided via WithConfigFile or WithConfigFileFlag.

func WithEnvVarIgnoreCommas added in v1.7.0

func WithEnvVarIgnoreCommas(ignore bool) Option

WithEnvVarIgnoreCommas tells parse to ignore commas in environment variable values, treating the complete value as a single string passed to the associated flag. By default, if an environment variable's value contains commas, each comma-delimited token is treated as a separate instance of the associated flag.

func WithEnvVarNoPrefix

func WithEnvVarNoPrefix() Option

WithEnvVarNoPrefix tells parse to look in the environment for variables with no prefix. See WithEnvVarPrefix for an explanation of how flag names are converted to environment variables names.

func WithEnvVarPrefix

func WithEnvVarPrefix(prefix string) Option

WithEnvVarPrefix tells parse to look in the environment for variables with the given prefix. Flag names are converted to environment variables by capitalizing them, and replacing separator characters like periods or hyphens with underscores.

func WithIgnoreUndefined

func WithIgnoreUndefined(ignore bool) Option

WithIgnoreUndefined tells parse to ignore undefined flags that it encounters, which would normally throw an error.

type StringConversionError

type StringConversionError struct {
	Value interface{}
}

StringConversionError is returned when a value in a config file can't be converted to a string, to be provided to a flag.

func (StringConversionError) Error

func (e StringConversionError) Error() string

Error implements the error interface.

Directories

Path Synopsis
Package ffcli is for building declarative commandline applications.
Package ffcli is for building declarative commandline applications.
Package fftest provides helpers for parser testing.
Package fftest provides helpers for parser testing.
Package fftoml provides a TOML config file paser.
Package fftoml provides a TOML config file paser.
Package ffyaml provides a YAML config file paser.
Package ffyaml provides a YAML config file paser.

Jump to

Keyboard shortcuts

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