flagx

package
v0.1.75 Latest Latest
Warning

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

Go to latest
Published: Sep 27, 2024 License: Apache-2.0 Imports: 11 Imported by: 64

README

Functions which extend the capabilities of the flag package.

This package includes:

  • flagx.ArgsFromEnv allows flags to be passed from the command-line or as an environment variable.

  • flagx.FileBytes is a new flag type. It automatically reads the content of the given file as a []byte, handling any error during flag parsing and simplifying application logic.

  • flagx.StringArray is a new flag type that handles appending to []string

Usage of any of the above is like:

package main

import (
	"flag"
	"fmt"

	"github.com/m-lab/go/flagx"
)

var (
	flagArray flagx.StringArray
)

func main() {
	flag.Var(&flagArray, "array", "append to string array")
	flag.Parse()
	fmt.Printf("%+v\n", flagArray)
	// your code here
}

Documentation

Overview

Package flagx extends to capabilities of flags to also be able to read from environment variables. This comes in handy when dockerizing applications.

Example
package main

import (
	"flag"
	"log"

	"github.com/m-lab/go/flagx"
)

func main() {
	metadata := flagx.KeyValue{}
	flag.Var(&metadata, "metadata", "Key-value pairs to be added to the metadata (flag may be repeated)")
	// Commandline flags should look like: -metadata key1=val1 -metadata key2=val2
	flag.Parse()

	log.Println(metadata.Get())
}
Output:

Index

Examples

Constants

This section is empty.

Variables

View Source
var (
	// Advanced is a *flag.FlagSet for advanced flags. Packages should add flags
	// to Advanced when those flags should NOT be included in the default
	// flag.CommandLine flag set. Advanced flags may be enabled by calling
	// EnableAdvancedFlags _before_ calling flag.Parse().
	Advanced = flag.NewFlagSet("advanced", flag.ExitOnError)
)
View Source
var ErrBadTimeFormat = fmt.Errorf("ErrBadTimeFormat: unsupported time format")

ErrBadTimeFormat is returned when failing to parse a Time value.

Functions

func ArgsFromEnv

func ArgsFromEnv(flagSet *flag.FlagSet) error

ArgsFromEnv will expand command-line argument parsing to include setting the values of flags from their corresponding environment variables. The environment variable for an argument is the upper-case version of the command-line flag.

If you have two flags that map to the same environment variable string (like "-a" and "-A"), then the behavior of this function is unspecified and should not be relied upon. Also, your flags should have more descriptive names.

func ArgsFromEnvWithLog added in v0.1.40

func ArgsFromEnvWithLog(flagSet *flag.FlagSet, logArgs bool) error

ArgsFromEnvWithLog operates as ArgsFromEnv with an additional option to disable logging of all flag values. This is helpful for command line applications that wish to disable extra argument logging.

func AssignedFlags added in v0.1.21

func AssignedFlags(flagSet *flag.FlagSet) map[string]struct{}

AssignedFlags returns a map[string]struct{} where every key in the map is the name of a flag in the passed-in FlagSet that was explicitly set on the command-line.

func EnableAdvancedFlags added in v0.1.42

func EnableAdvancedFlags()

EnableAdvancedFlags adds all flags registered with the Advanced flag set to the default flag.CommandLine flag set. EnableAdvancedFlags should be called before flag.Parse().

func MakeShellVariableName added in v0.1.21

func MakeShellVariableName(flagName string) string

MakeShellVariableName makes every passed-in string match the regexp [A-Z_][A-Z0-9_]* Characters in shell variable names should be part of the portable character set (defined to be [A-Z0-9_] in https://pubs.opengroup.org/onlinepubs/000095399/basedefs/xbd_chap08.html) and may not begin with a digit.

Types

type DateTime added in v0.1.21

type DateTime struct {
	time.Time
}

DateTime is a flag type for accepting date parameters.

func (DateTime) Get added in v0.1.21

func (t DateTime) Get() string

Get retrieves the current date value as a string.

func (*DateTime) Set added in v0.1.21

func (t *DateTime) Set(s string) error

Set parses and assigns the DateTime value. DateTime accepts all formats supported by the "github.com/araddon/dateparse" package.

func (DateTime) String added in v0.1.21

func (t DateTime) String() string

String reports the parsed time as a string using time.Time.String().

type DurationArray added in v0.1.30

type DurationArray []time.Duration

DurationArray collects time.Durations so a duration flag can be specified multiple times or using "," separated items. The default argument should almost always be the empty array, because there is no way to remove an element, only to add one.

func (DurationArray) Get added in v0.1.30

func (da DurationArray) Get() interface{}

Get retrieves the value contained in the flag.

func (*DurationArray) Set added in v0.1.30

func (da *DurationArray) Set(s string) error

Set appends the given time.Duration to the DurationArray. Set accepts multiple durations separated by commas "," and appends each element to the DurationArray.

func (DurationArray) String added in v0.1.30

func (da DurationArray) String() string

String reports the DurationArray as a Go value.

type Enum added in v0.1.20

type Enum struct {
	Options []string
	Value   string
}

Enum is a new flag type. An Enum contains an array of Options and a selected Value.

func (Enum) Get added in v0.1.20

func (e Enum) Get() string

Get retrieves the value contained in the flag.

func (*Enum) Set added in v0.1.20

func (e *Enum) Set(s string) error

Set selects the Enum.Value if s equals one of the values in Enum.Options.

func (Enum) String added in v0.1.20

func (e Enum) String() string

String reports the set Enum value.

type File added in v0.1.42

type File struct {
	Bytes []byte
	Name  string
}

File is a new flag type. For a given filename, File reads and saves the file content to Bytes and the original filename to Name. Errors opening or reading the file are handled during flag parsing.

func (*File) Content added in v0.1.42

func (fb *File) Content() string

Content retrieves the bytes read from the file as a string.

func (*File) Get added in v0.1.42

func (fb *File) Get() []byte

Get retrieves the bytes read from the file.

func (*File) Set added in v0.1.42

func (fb *File) Set(s string) error

Set accepts a file name. On success, the file content is saved to Bytes, and the original file name to Name.

func (*File) String added in v0.1.42

func (fb *File) String() string

String reports the original file Name. NOTE: String is typically used by the flag help text and to report flag values. To return the file content as a string, see File.Content().

type FileBytes

type FileBytes []byte

FileBytes is a new flag type. It automatically reads the content of the given filename as a `[]byte`, handling errors during flag parsing.

func (FileBytes) Get

func (fb FileBytes) Get() interface{}

Get retrieves the bytes read from the file (or the default bytes).

func (*FileBytes) Set

func (fb *FileBytes) Set(s string) error

Set accepts a filename and reads the bytes associated with that file into the FileBytes storage.

func (FileBytes) String

func (fb FileBytes) String() string

String reports the FileBytes content as a string.

FileBytes are awkward to represent in help text, and such help text is the main use of the Stringer interface for this flag. Help text like:

"Sets the file containing the prefix string. The default file contents are: " + fb.String()

is recommended.

type FileBytesArray added in v0.1.41

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

FileBytesArray is a new flag type that combines the semantics of StringArray for multiple filenames and FileBytes for reading the content of each file. Every filename is read as a `[]byte` and the contents appended to an FileBytesArray of type `[][]byte`.

Like StringArray, the flag parameter may be specified multiple times or using "," separated items. Unlike other Flag types, the default argument should almost always be the empty array, because there is no way to remove an element, only to add one.

func (*FileBytesArray) Get added in v0.1.41

func (fb *FileBytesArray) Get() [][]byte

Get retrieves the bytes read from the file (or the default bytes).

func (*FileBytesArray) Set added in v0.1.41

func (fb *FileBytesArray) Set(s string) error

Set accepts a filename (or filenames separated by comma) and reads the bytes associated with the file and appends the bytes the FileBytesArray.

func (FileBytesArray) String added in v0.1.41

func (fb FileBytesArray) String() string

String reports the original FileBytesArray filenames a string.

type KeyValue added in v0.1.20

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

KeyValue parses "key=value" pairs from a given argument. The KeyValue flag is designed to be used for repeatable arguments. Each use of the flag will add another key value pair (or overwrite a previous one if the same key is used).

func (*KeyValue) Get added in v0.1.20

func (kv *KeyValue) Get() map[string]string

Get returns all of the KeyValue pairs as a map[string]string. The returned value is a copy.

func (*KeyValue) Set added in v0.1.20

func (kv *KeyValue) Set(kvs string) error

Set parses key=value argument. Multiple pairs may be separated with a comma, i.e. "key1=value1,key2=value2". When the first character of the value is prefixed by with "@", i.e. "key1=@file1", Set reads the file content for the key value.

func (*KeyValue) String added in v0.1.20

func (kv *KeyValue) String() string

String serializes parsed arguments into a form similiar to how they were added from the command line. Order is not preserved.

type KeyValueArray added in v0.1.48

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

KeyValueArray maps a key to one or multiple values. It parses "key=value1,value2,..." pairs from a given argument and is designed to be used for repeatable arguments. Each use of the flag will add a new key-[]value pair (or append to a previous one if the same key is used).

func (*KeyValueArray) Get added in v0.1.48

func (kva *KeyValueArray) Get() map[string][]string

Get returns all of the KeyValueArray pairs as a map[string][]string. The returned value is a copy.

func (*KeyValueArray) Set added in v0.1.48

func (kva *KeyValueArray) Set(pair string) error

Set parses key=value1,value2,... arguments. Only one key-[]value pair can be specified per call.

func (*KeyValueArray) String added in v0.1.48

func (kva *KeyValueArray) String() string

String returns the key-[]value pairs as a string.

type KeyValueEscaped added in v0.1.69

type KeyValueEscaped struct {
	KeyValue
}

KeyValueEscaped parses "key=value" pairs from a given argument. Unlike the KeyValue flag, which is designed for repeatable arguments separated by any ',', KeyValueEscaped allows for key/value with escaped commas (i.e. `\,`), with key/value pairs separated by an unescaped comma (i.e., ','). Each use of the flag will add another key value pair (or overwrite a previous one if the same key is used).

func (*KeyValueEscaped) Get added in v0.1.69

func (kve *KeyValueEscaped) Get() map[string]string

Get returns all of the KeyValueEscaped pairs as a map[string]string. The returned value is a copy.

func (*KeyValueEscaped) Set added in v0.1.69

func (kve *KeyValueEscaped) Set(kvs string) error

Set parses key=value argument. Multiple pairs may be separated with an unescaped comma, i.e. "key1=value1,key2=value2". When the first character of the value is prefixed by with "@", i.e. "key1=@file1", Set reads the file content for the key value.

func (*KeyValueEscaped) String added in v0.1.69

func (kve *KeyValueEscaped) String() string

String serializes parsed arguments into a form similiar to how they were added from the command line. Order is not preserved.

type StringArray

type StringArray []string

StringArray is a new flag type. It appends the flag parameter to an `[]string` allowing the parameter to be specified multiple times or using "," separated items. Unlike other Flag types, the default argument should almost always be the empty array, because there is no way to remove an element, only to add one.

func (StringArray) Contains added in v0.1.21

func (sa StringArray) Contains(value string) bool

Contains returns true when the given value equals one of the StringArray values.

func (StringArray) Get

func (sa StringArray) Get() interface{}

Get retrieves the value contained in the flag.

func (*StringArray) Set

func (sa *StringArray) Set(s string) error

Set accepts a string parameter and appends it to the associated StringArray. Set attempts to split the given string on commas "," and appends each element to the StringArray.

func (StringArray) String

func (sa StringArray) String() string

String reports the StringArray as a Go value.

type StringFile added in v0.1.75

type StringFile struct {
	Value string
	// contains filtered or unexported fields
}

StringFile acts like the native flag.String by storing a string from the given argument. Additionally, StringFile may specify a file to read the string value from when prefixed with an '@', e.g. -flag=@value.txt

func (*StringFile) Get added in v0.1.75

func (fs *StringFile) Get() string

Get returns the flag value.

func (*StringFile) Set added in v0.1.75

func (fs *StringFile) Set(v string) error

Set records the string in Value. When the first character of the parameter is prefixed with "@", i.e. "@file1", Set reads the file content for the value.

func (*StringFile) String added in v0.1.75

func (fs *StringFile) String() string

String returns the flags in a form similiar to how they were added from the command line.

type Time added in v0.1.21

type Time struct {
	Hour   int
	Minute int
	Second int
}

Time is a flag type for accepting time parameters formatted as HH:MM:SS. If you need sub-second resolution, consider using one of the unix timestamp formats (ms, usec, or ns) supported by DateTime.

func (Time) Get added in v0.1.21

func (t Time) Get() string

Get retrieves the value contained in the flag.

func (*Time) Set added in v0.1.21

func (t *Time) Set(s string) error

Set parses and assigns the Time Hour, Minute, and Second values.

func (Time) String added in v0.1.21

func (t Time) String() string

String reports the set Time value.

type URL added in v0.1.30

type URL struct {
	*url.URL
}

URL is a flag type for parsing URL strings and handling errors during flag parsing. Use MustNewURL() to specify a default value.

func MustNewURL added in v0.1.30

func MustNewURL(s string) URL

MustNewURL creates a new flagx.URL initialized with the given value. Failure to parse is fatal. For example:

f := flagx.MustNewURL("http://example.com")

func (*URL) Get added in v0.1.30

func (u *URL) Get() *url.URL

Get returns the inner *url.URL type.

func (*URL) Set added in v0.1.30

func (u *URL) Set(s string) error

Set parses a URL string and stores the result.

func (*URL) String added in v0.1.30

func (u *URL) String() string

String formats the underlying URL as a string.

Jump to

Keyboard shortcuts

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