Documentation ¶
Overview ¶
Package flagext implements extensions to the standard flag package in the form of types that implement flag.Value
Index ¶
- Constants
- func Callback(fl *flag.FlagSet, name, value, usage string, cb func(string) error)deprecated
- func Choice(selection *string, choices ...string) flag.Value
- func ChoiceVar(fl *flag.FlagSet, name, value, usage string, choices ...string) *string
- func Logger(l *log.Logger, mode logMode) flag.Value
- func LoggerVar(fl *flag.FlagSet, l *log.Logger, name string, mode logMode, usage string)
- func MustHave(fl *flag.FlagSet, names ...string) error
- func MustHaveArgs(fl *flag.FlagSet, min, max int) error
- func ParseEnv(fl *flag.FlagSet, prefix string) error
- func StringsVar(fl *flag.FlagSet, ss *[]string, name, usage string)
- type MissingFlagsError
- type Reader
- type Strings
- type Writer
Examples ¶
Constants ¶
const ( LogVerbose logMode = true LogSilent logMode = false )
const (
// StdIO can be passed to File to set Stdin as the default
StdIO = "-"
)
Variables ¶
This section is empty.
Functions ¶
func Callback
deprecated
added in
v0.0.8
Callback is a convenience function for defining a Set(string) error function on a flag.FlagSet without constructing a new type.
If nil, fl defaults to flag.CommandLine. Value is only used for showing the default in usage help.
Deprecated: Use flag.Func in Go 1.16+.
Example (BadFlag) ¶
package main import ( "flag" "fmt" "io" "strings" "github.com/carlmjohnson/flagext" ) func main() { fs := flag.NewFlagSet("ExampleCallback", flag.ContinueOnError) fs.SetOutput(io.Discard) const usage = `...` var mode string flagext.Callback(fs, "mode", mode, usage, func(s string) error { if s != strings.ToLower(s) { return fmt.Errorf("mode must be lower case") } mode = s return nil }) err := fs.Parse([]string{"-mode", "X"}) fmt.Println(mode, err) }
Output: invalid value "X" for flag -mode: mode must be lower case
Example (DefaultValue) ¶
package main import ( "flag" "fmt" "strings" "github.com/carlmjohnson/flagext" ) func main() { fs := flag.NewFlagSet("ExampleCallback", flag.PanicOnError) mode := "none" flagext.Callback(fs, "mode", mode, "what mode to use", func(s string) error { if s != strings.ToLower(s) { return fmt.Errorf("mode must be lower case") } mode = s return nil }) fs.Parse([]string{}) fmt.Println(mode) }
Output: none
Example (GoodFlag) ¶
package main import ( "flag" "fmt" "strings" "github.com/carlmjohnson/flagext" ) func main() { fs := flag.NewFlagSet("ExampleCallback", flag.PanicOnError) const usage = `...` var mode string flagext.Callback(fs, "mode", mode, usage, func(s string) error { if s != strings.ToLower(s) { return fmt.Errorf("mode must be lower case") } mode = s return nil }) fs.Parse([]string{"-mode", "x"}) fmt.Println(mode) }
Output: x
func Choice ¶
Choice implements flag.Value. Pass directly into flag.Var. flag.Var sets selection to the value of a command line flag if it is among the choices. If the flag value is not among the choices, it returns an error.
Example (BadFlag) ¶
package main import ( "flag" "fmt" "io" "github.com/carlmjohnson/flagext" ) func main() { fs := flag.NewFlagSet("ExampleChoice", flag.ContinueOnError) fs.SetOutput(io.Discard) var mode string fs.Var(flagext.Choice(&mode, "a", "b"), "mode", "mode to run") err := fs.Parse([]string{"-mode", "c"}) fmt.Println(err) }
Output: invalid value "c" for flag -mode: "c" not in a, b
Example (DefaultValue) ¶
package main import ( "flag" "fmt" "github.com/carlmjohnson/flagext" ) func main() { fs := flag.NewFlagSet("ExampleChoice", flag.ContinueOnError) mode := "none" fs.Var(flagext.Choice(&mode, "yes", "no"), "mode", "mode to run") fs.Parse([]string{}) fmt.Println(mode) }
Output: none
Example (GoodFlag) ¶
package main import ( "flag" "fmt" "github.com/carlmjohnson/flagext" ) func main() { fs := flag.NewFlagSet("ExampleChoice", flag.ContinueOnError) var mode string fs.Var(flagext.Choice(&mode, "x", "y"), "mode", "mode to run") fs.Parse([]string{"-mode", "x"}) fmt.Println(mode) }
Output: x
func ChoiceVar ¶ added in v0.0.11
ChoiceVar is a convenience wrapper for Choice. If nil, fl defaults to flag.CommandLine.
func Logger ¶ added in v0.0.5
Logger sets output for a *log.Logger to os.Stderr or io.Discard via the returned flag.Value. Uses log.Default() if l is nil.
Example ¶
package main import ( "flag" "log" "os" "github.com/carlmjohnson/flagext" ) func main() { // Redirect Stderr for test { stderr := os.Stderr os.Stderr = os.Stdout defer func() { os.Stderr = stderr }() } { fs := flag.NewFlagSet("ExampleLogger", flag.PanicOnError) l := log.New(nil, "myapp ", 00) fs.Var( flagext.Logger(l, flagext.LogVerbose), "verbose", `log output`, ) fs.Parse([]string{"-verbose"}) l.Print("hello log 1") } { fs := flag.NewFlagSet("ExampleLogger", flag.PanicOnError) l := log.New(nil, "myapp ", 00) fs.Var( flagext.Logger(l, flagext.LogSilent), "silent", `don't log output`, ) fs.Parse([]string{}) l.Print("hello log 2") } { fs := flag.NewFlagSet("ExampleLogger", flag.PanicOnError) l := log.New(nil, "myapp ", 00) fs.Var( flagext.Logger(l, flagext.LogVerbose), "verbose", `log output`, ) fs.Parse([]string{"-verbose=false"}) l.Print("silenced!") } { fs := flag.NewFlagSet("ExampleLogger", flag.PanicOnError) l := log.New(nil, "myapp ", 00) fs.Var( flagext.Logger(l, flagext.LogSilent), "silent", `don't log output`, ) fs.Parse([]string{"-silent=1"}) l.Print("silenced!") } }
Output: myapp hello log 1 myapp hello log 2
func LoggerVar ¶ added in v0.0.11
LoggerVar is a convenience wrapper for Logger. If nil, fl defaults to flag.CommandLine.
func MustHave ¶ added in v0.0.9
MustHave is a convenience function that checks that the named flags were set on fl. Missing flags are treated with the policy of fl.ErrorHandling(): ExitOnError, ContinueOnError, or PanicOnError. Returned errors will have type MissingFlagsError.
If nil, fl defaults to flag.CommandLine.
Example (MissingFlag) ¶
package main import ( "flag" "fmt" "strings" "github.com/carlmjohnson/flagext" ) func main() { var buf strings.Builder defer func() { recover() fmt.Println(buf.String()) }() fs := flag.NewFlagSet("ExampleMustHave", flag.PanicOnError) fs.SetOutput(&buf) fs.String("a", "", "this value must be set") fs.String("b", "", "this value must be set") fs.String("c", "", "this value is optional") fs.Parse([]string{"-a", "set"}) flagext.MustHave(fs, "a", "b") }
Output: missing required flag: b Usage of ExampleMustHave: -a string this value must be set -b string this value must be set -c string this value is optional
Example (NoMissingFlag) ¶
package main import ( "flag" "github.com/carlmjohnson/flagext" ) func main() { fs := flag.NewFlagSet("ExampleMustHave", flag.PanicOnError) fs.String("a", "", "this value must be set") fs.String("b", "", "this value must be set") fs.String("c", "", "this value is optional") fs.Parse([]string{"-a", "set", "-b", "set"}) flagext.MustHave(fs, "a", "b") }
Output:
func MustHaveArgs ¶ added in v0.0.10
MustHaveArgs is a convenience function that checks that fl.NArg() is within the bounds min and max (inclusive). Use max -1 to indicate no maximum value. MustHaveArgs uses the policy of fl.ErrorHandling(): ExitOnError, ContinueOnError, or PanicOnError.
If nil, fl defaults to flag.CommandLine.
Example (CorrectNumber) ¶
package main import ( "flag" "github.com/carlmjohnson/flagext" ) func main() { fs := flag.NewFlagSet("ExampleMustHave", flag.PanicOnError) fs.String("a", "", "an option") fs.Parse([]string{"--", "-a", "-b", "-c"}) flagext.MustHaveArgs(fs, 3, 3) }
Output:
Example (WrongNumber) ¶
package main import ( "flag" "fmt" "strings" "github.com/carlmjohnson/flagext" ) func main() { var buf strings.Builder defer func() { recover() fmt.Println(buf.String()) }() fs := flag.NewFlagSet("ExampleMustHaveArgs", flag.PanicOnError) fs.SetOutput(&buf) fs.Usage = func() { fmt.Fprintf(fs.Output(), "Usage:\n\tExampleMustHaveArgs [optional arg]") } fs.Parse([]string{"--", "one", "two"}) flagext.MustHaveArgs(fs, 0, 1) }
Output: must have between 0 and 1 args; got 2 Usage: ExampleMustHaveArgs [optional arg]
func ParseEnv ¶ added in v0.20.1
ParseEnv lists any unset flags, checks whether a corresponding environment variable exists, and if so calls Set with its value. Flag names are prefixed and converted to SCREAMING_SNAKE_CASE when looking up environment variables.
Example ¶
package main import ( "flag" "fmt" "os" "github.com/carlmjohnson/flagext" ) func main() { fs := flag.NewFlagSet("ExampleParseEnv", flag.PanicOnError) a := fs.Int("a", 0, "") b := fs.Int("b", 0, "") fs.Parse([]string{"-a", "1"}) os.Setenv("TEST_ENV_A", "2") os.Setenv("TEST_ENV_B", "3") flagext.ParseEnv(fs, "test-env") // Does not override existing values fmt.Println("a", *a) // Does get new values from env fmt.Println("b", *b) }
Output: a 1 b 3
Types ¶
type MissingFlagsError ¶ added in v0.0.10
type MissingFlagsError []string
MissingFlagsError is the error type returned by MustHave.
func (MissingFlagsError) Error ¶ added in v0.0.10
func (missing MissingFlagsError) Error() string
type Reader ¶ added in v0.0.2
type Reader interface { io.ReadCloser flag.Getter }
Reader is an io.ReadCloser that can be set as a flag.Value
func File ¶ added in v0.0.2
File returns an io.Reader that lazily loads a file set as a flag.Value. Pass StdIO ("-") to read from standard input.
type Strings ¶ added in v0.0.4
type Strings []string
Strings is a slice of strings useful for accepting multiple option values
func (*Strings) Get ¶ added in v0.0.4
func (ss *Strings) Get() interface{}
Get implements flag.Getter
type Writer ¶ added in v0.0.3
type Writer interface { io.WriteCloser flag.Getter }
Writer is an io.WriteCloser that can be set as a flag.Value
func FileWriter ¶ added in v0.0.3
FileWriter returns an io.WriteCloser that lazily os.Creates a file set as a flag.Value. Pass StdIO ("-") to write to standard output.