README

flagext GoDoc Go Report Card

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

Expand ▾ Collapse ▴

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

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.

Example (BadFlag)

Code:

package main

import (
	"flag"
	"fmt"
	"github.com/carlmjohnson/flagext"
	"io/ioutil"
	"strings"
)

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)
}
invalid value "X" for flag -mode: mode must be lower case
Example (DefaultValue)

Code:

package main

import (
	"flag"
	"fmt"
	"github.com/carlmjohnson/flagext"
	"strings"
)

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)
}
none
Example (GoodFlag)

Code:

package main

import (
	"flag"
	"fmt"
	"github.com/carlmjohnson/flagext"
	"strings"
)

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)
}
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)

Code:

package main

import (
	"flag"
	"fmt"
	"github.com/carlmjohnson/flagext"
	"io/ioutil"
)

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)
}
invalid value "c" for flag -mode: "c" not in a, b
Example (DefaultValue)

Code:

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)
}
none
Example (GoodFlag)

Code:

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)
}
x

func ChoiceVar

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

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

Code:

package main

import (
	"flag"
	"github.com/carlmjohnson/flagext"
	"log"
	"os"
)

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!")
	}
}
myapp hello log 1
myapp hello log 2

func LoggerVar

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

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)

Code:

package main

import (
	"flag"
	"fmt"
	"github.com/carlmjohnson/flagext"
	"strings"
)

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")
}
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)

Code:

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")
}

func MustHaveArgs

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)

Code:

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)
}

Example (WrongNumber)

Code:

package main

import (
	"flag"
	"fmt"
	"github.com/carlmjohnson/flagext"
	"strings"
)

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)
}
must have between 0 and 1 args; got 2
Usage:
	ExampleMustHaveArgs [optional arg]

func ParseEnv

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

Code:

package main

import (
	"flag"
	"fmt"
	"github.com/carlmjohnson/flagext"
	"os"
)

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)
}
a 1
b 3

func StringsVar

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

type MissingFlagsError []string

MissingFlagsError is the error type returned by MustHave.

func (MissingFlagsError) Error

func (missing MissingFlagsError) Error() string

type Reader

type Reader interface {
	io.ReadCloser
	flag.Getter
}

Reader is an io.ReadCloser that can be set as a flag.Value

func File

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

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

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

type Strings []string

Strings is a slice of strings useful for accepting multiple option values

func (*Strings) Get

func (ss *Strings) Get() interface{}

Get implements flag.Getter

func (*Strings) Set

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

Set implements flag.Value

func (*Strings) String

func (ss *Strings) String() string

String implements flag.Value

type Writer

type Writer interface {
	io.WriteCloser
	flag.Getter
}

Writer is an io.WriteCloser that can be set as a flag.Value

func FileWriter

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.