flagext

package module
Version: v0.21.0 Latest Latest
Warning

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

Go to latest
Published: Feb 25, 2021 License: MIT Imports: 11 Imported by: 36

README

flagext GoDoc Go Report Card

Implementations of the flag.Value interface to extend the flag package

Documentation

Overview

Package flagext implements extensions to the standard flag package in the form of types that implement flag.Value

Index

Examples

Constants

View Source
const (
	LogVerbose logMode = true
	LogSilent  logMode = false
)
View Source
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

This function has been deprecated.
func Callback(fl *flag.FlagSet, name, value, usage string, cb func(string) error)

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/ioutil"
	"strings"

	"github.com/carlmjohnson/flagext"
)

func main() {
	fs := flag.NewFlagSet("ExampleCallback", flag.ContinueOnError)
	fs.SetOutput(ioutil.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)
	const usage = `...`
	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

func Choice(selection *string, choices ...string) flag.Value

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/ioutil"

	"github.com/carlmjohnson/flagext"
)

func main() {
	fs := flag.NewFlagSet("ExampleChoice", flag.ContinueOnError)
	fs.SetOutput(ioutil.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

func ChoiceVar(fl *flag.FlagSet, name, value, usage string, choices ...string) *string

ChoiceVar is a convenience wrapper for Choice. If nil, fl defaults to flag.CommandLine.

func Logger added in v0.0.5

func Logger(l *log.Logger, mode logMode) flag.Value

Logger sets output for a *log.Logger to os.Stderr or ioutil.Discard via the returned flag.Value

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

func LoggerVar(fl *flag.FlagSet, l *log.Logger, name string, mode logMode, usage string)

LoggerVar is a convenience wrapper for Logger. If nil, fl defaults to flag.CommandLine.

func MustHave added in v0.0.9

func MustHave(fl *flag.FlagSet, names ...string) error

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

func MustHaveArgs(fl *flag.FlagSet, min, max int) error

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

func ParseEnv(fl *flag.FlagSet, prefix string) error

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

func StringsVar added in v0.0.7

func StringsVar(fl *flag.FlagSet, ss *[]string, name, usage string)

StringsVar is a convenience function for adding a slice of strings to a FlagSet. If nil, fl defaults to flag.CommandLine.

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

func File(defaultPath string) Reader

File returns an io.Reader that lazily loads a file set as a flag.Value. Pass StdIO ("-") to read from standard input.

func FileOrURL added in v0.0.2

func FileOrURL(defaultPath string, client *http.Client) Reader

FileOrURL is an io.Reader that lazily opens a URL or file path set as a flag.Value.

func URL added in v0.0.2

func URL(defaultPath string, client *http.Client) Reader

URL returns an io.Reader that lazily loads an HTTP(S) URL set as a flag.Value.

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

func (*Strings) Set added in v0.0.4

func (ss *Strings) Set(val string) error

Set implements flag.Value

func (*Strings) String added in v0.0.4

func (ss *Strings) String() string

String implements flag.Value

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

func FileWriter(defaultPath string) Writer

FileWriter returns an io.WriteCloser that lazily os.Creates a file set as a flag.Value. Pass StdIO ("-") to write to standard output.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
t or T : Toggle theme light dark auto
y or Y : Canonical URL