Categorygithub.com/spf13/pflag
modulepackage
1.0.6
Repository: https://github.com/spf13/pflag.git
Documentation: pkg.go.dev

# README

Build Status Go Report Card GoDoc

Description

pflag is a drop-in replacement for Go's flag package, implementing POSIX/GNU-style --flags.

pflag is compatible with the GNU extensions to the POSIX recommendations for command-line options. For a more precise description, see the "Command-line flag syntax" section below.

pflag is available under the same style of BSD license as the Go language, which can be found in the LICENSE file.

Installation

pflag is available using the standard go get command.

Install by running:

go get github.com/spf13/pflag

Run tests by running:

go test github.com/spf13/pflag

Usage

pflag is a drop-in replacement of Go's native flag package. If you import pflag under the name "flag" then all code should continue to function with no changes.

import flag "github.com/spf13/pflag"

There is one exception to this: if you directly instantiate the Flag struct there is one more field "Shorthand" that you will need to set. Most code never instantiates this struct directly, and instead uses functions such as String(), BoolVar(), and Var(), and is therefore unaffected.

Define flags using flag.String(), Bool(), Int(), etc.

This declares an integer flag, -flagname, stored in the pointer ip, with type *int.

var ip *int = flag.Int("flagname", 1234, "help message for flagname")

If you like, you can bind the flag to a variable using the Var() functions.

var flagvar int
func init() {
    flag.IntVar(&flagvar, "flagname", 1234, "help message for flagname")
}

Or you can create custom flags that satisfy the Value interface (with pointer receivers) and couple them to flag parsing by

flag.Var(&flagVal, "name", "help message for flagname")

For such flags, the default value is just the initial value of the variable.

After all flags are defined, call

flag.Parse()

to parse the command line into the defined flags.

Flags may then be used directly. If you're using the flags themselves, they are all pointers; if you bind to variables, they're values.

fmt.Println("ip has value ", *ip)
fmt.Println("flagvar has value ", flagvar)

There are helper functions available to get the value stored in a Flag if you have a FlagSet but find it difficult to keep up with all of the pointers in your code. If you have a pflag.FlagSet with a flag called 'flagname' of type int you can use GetInt() to get the int value. But notice that 'flagname' must exist and it must be an int. GetString("flagname") will fail.

i, err := flagset.GetInt("flagname")

After parsing, the arguments after the flag are available as the slice flag.Args() or individually as flag.Arg(i). The arguments are indexed from 0 through flag.NArg()-1.

The pflag package also defines some new functions that are not in flag, that give one-letter shorthands for flags. You can use these by appending 'P' to the name of any function that defines a flag.

var ip = flag.IntP("flagname", "f", 1234, "help message")
var flagvar bool
func init() {
	flag.BoolVarP(&flagvar, "boolname", "b", true, "help message")
}
flag.VarP(&flagVal, "varname", "v", "help message")

Shorthand letters can be used with single dashes on the command line. Boolean shorthand flags can be combined with other shorthand flags.

The default set of command-line flags is controlled by top-level functions. The FlagSet type allows one to define independent sets of flags, such as to implement subcommands in a command-line interface. The methods of FlagSet are analogous to the top-level functions for the command-line flag set.

Setting no option default values for flags

After you create a flag it is possible to set the pflag.NoOptDefVal for the given flag. Doing this changes the meaning of the flag slightly. If a flag has a NoOptDefVal and the flag is set on the command line without an option the flag will be set to the NoOptDefVal. For example given:

var ip = flag.IntP("flagname", "f", 1234, "help message")
flag.Lookup("flagname").NoOptDefVal = "4321"

Would result in something like

Parsed ArgumentsResulting Value
--flagname=1357ip=1357
--flagnameip=4321
[nothing]ip=1234

Command line flag syntax

--flag    // boolean flags, or flags with no option default values
--flag x  // only on flags without a default value
--flag=x

Unlike the flag package, a single dash before an option means something different than a double dash. Single dashes signify a series of shorthand letters for flags. All but the last shorthand letter must be boolean flags or a flag with a default value

// boolean or flags where the 'no option default value' is set
-f
-f=true
-abc
but
-b true is INVALID

// non-boolean and flags without a 'no option default value'
-n 1234
-n=1234
-n1234

// mixed
-abcs "hello"
-absd="hello"
-abcs1234

Flag parsing stops after the terminator "--". Unlike the flag package, flags can be interspersed with arguments anywhere on the command line before this terminator.

Integer flags accept 1234, 0664, 0x1234 and may be negative. Boolean flags (in their long form) accept 1, 0, t, f, true, false, TRUE, FALSE, True, False. Duration flags accept any input valid for time.ParseDuration.

Mutating or "Normalizing" Flag names

It is possible to set a custom flag name 'normalization function.' It allows flag names to be mutated both when created in the code and when used on the command line to some 'normalized' form. The 'normalized' form is used for comparison. Two examples of using the custom normalization func follow.

Example #1: You want -, _, and . in flags to compare the same. aka --my-flag == --my_flag == --my.flag

func wordSepNormalizeFunc(f *pflag.FlagSet, name string) pflag.NormalizedName {
	from := []string{"-", "_"}
	to := "."
	for _, sep := range from {
		name = strings.Replace(name, sep, to, -1)
	}
	return pflag.NormalizedName(name)
}

myFlagSet.SetNormalizeFunc(wordSepNormalizeFunc)

Example #2: You want to alias two flags. aka --old-flag-name == --new-flag-name

func aliasNormalizeFunc(f *pflag.FlagSet, name string) pflag.NormalizedName {
	switch name {
	case "old-flag-name":
		name = "new-flag-name"
		break
	}
	return pflag.NormalizedName(name)
}

myFlagSet.SetNormalizeFunc(aliasNormalizeFunc)

Deprecating a flag or its shorthand

It is possible to deprecate a flag, or just its shorthand. Deprecating a flag/shorthand hides it from help text and prints a usage message when the deprecated flag/shorthand is used.

Example #1: You want to deprecate a flag named "badflag" as well as inform the users what flag they should use instead.

// deprecate a flag by specifying its name and a usage message
flags.MarkDeprecated("badflag", "please use --good-flag instead")

This hides "badflag" from help text, and prints Flag --badflag has been deprecated, please use --good-flag instead when "badflag" is used.

Example #2: You want to keep a flag name "noshorthandflag" but deprecate its shortname "n".

// deprecate a flag shorthand by specifying its flag name and a usage message
flags.MarkShorthandDeprecated("noshorthandflag", "please use --noshorthandflag only")

This hides the shortname "n" from help text, and prints Flag shorthand -n has been deprecated, please use --noshorthandflag only when the shorthand "n" is used.

Note that usage message is essential here, and it should not be empty.

Hidden flags

It is possible to mark a flag as hidden, meaning it will still function as normal, however will not show up in usage/help text.

Example: You have a flag named "secretFlag" that you need for internal use only and don't want it showing up in help text, or for its usage text to be available.

// hide a flag by specifying its name
flags.MarkHidden("secretFlag")

Disable sorting of flags

pflag allows you to disable sorting of flags for help and usage message.

Example:

flags.BoolP("verbose", "v", false, "verbose output")
flags.String("coolflag", "yeaah", "it's really cool flag")
flags.Int("usefulflag", 777, "sometimes it's very useful")
flags.SortFlags = false
flags.PrintDefaults()

Output:

  -v, --verbose           verbose output
      --coolflag string   it's really cool flag (default "yeaah")
      --usefulflag int    sometimes it's very useful (default 777)

Supporting Go flags when using pflag

In order to support flags defined using Go's flag package, they must be added to the pflag flagset. This is usually necessary to support flags defined by third-party dependencies (e.g. golang/glog).

Example: You want to add the Go flags to the CommandLine flagset

import (
	goflag "flag"
	flag "github.com/spf13/pflag"
)

var ip *int = flag.Int("flagname", 1234, "help message for flagname")

func main() {
	flag.CommandLine.AddGoFlagSet(goflag.CommandLine)
	flag.Parse()
}

More info

You can see the full reference documentation of the pflag package at godoc.org, or through go's standard documentation system by running godoc -http=:6060 and browsing to http://localhost:6060/pkg/github.com/spf13/pflag after installation.

# Functions

Arg returns the i'th command-line argument.
Args returns the non-flag command-line arguments.
Bool defines a bool flag with specified name, default value, and usage string.
BoolP is like Bool, but accepts a shorthand letter that can be used after a single dash.
BoolSlice defines a []bool flag with specified name, default value, and usage string.
BoolSliceP is like BoolSlice, but accepts a shorthand letter that can be used after a single dash.
BoolSliceVar defines a []bool flag with specified name, default value, and usage string.
BoolSliceVarP is like BoolSliceVar, but accepts a shorthand letter that can be used after a single dash.
BoolVar defines a bool flag with specified name, default value, and usage string.
BoolVarP is like BoolVar, but accepts a shorthand letter that can be used after a single dash.
BytesBase64 defines an []byte flag with specified name, default value, and usage string.
BytesBase64P is like BytesBase64, but accepts a shorthand letter that can be used after a single dash.
BytesBase64Var defines an []byte flag with specified name, default value, and usage string.
BytesBase64VarP is like BytesBase64Var, but accepts a shorthand letter that can be used after a single dash.
BytesHex defines an []byte flag with specified name, default value, and usage string.
BytesHexP is like BytesHex, but accepts a shorthand letter that can be used after a single dash.
BytesHexVar defines an []byte flag with specified name, default value, and usage string.
BytesHexVarP is like BytesHexVar, but accepts a shorthand letter that can be used after a single dash.
Count defines a count flag with specified name, default value, and usage string.
CountP is like Count only takes a shorthand for the flag name.
CountVar like CountVar only the flag is placed on the CommandLine instead of a given flag set.
CountVarP is like CountVar only take a shorthand for the flag name.
Duration defines a time.Duration flag with specified name, default value, and usage string.
DurationP is like Duration, but accepts a shorthand letter that can be used after a single dash.
DurationSlice defines a []time.Duration flag with specified name, default value, and usage string.
DurationSliceP is like DurationSlice, but accepts a shorthand letter that can be used after a single dash.
DurationSliceVar defines a duration[] flag with specified name, default value, and usage string.
DurationSliceVarP is like DurationSliceVar, but accepts a shorthand letter that can be used after a single dash.
DurationVar defines a time.Duration flag with specified name, default value, and usage string.
DurationVarP is like DurationVar, but accepts a shorthand letter that can be used after a single dash.
Float32 defines a float32 flag with specified name, default value, and usage string.
Float32P is like Float32, but accepts a shorthand letter that can be used after a single dash.
Float32Slice defines a []float32 flag with specified name, default value, and usage string.
Float32SliceP is like Float32Slice, but accepts a shorthand letter that can be used after a single dash.
Float32SliceVar defines a float32[] flag with specified name, default value, and usage string.
Float32SliceVarP is like Float32SliceVar, but accepts a shorthand letter that can be used after a single dash.
Float32Var defines a float32 flag with specified name, default value, and usage string.
Float32VarP is like Float32Var, but accepts a shorthand letter that can be used after a single dash.
Float64 defines a float64 flag with specified name, default value, and usage string.
Float64P is like Float64, but accepts a shorthand letter that can be used after a single dash.
Float64Slice defines a []float64 flag with specified name, default value, and usage string.
Float64SliceP is like Float64Slice, but accepts a shorthand letter that can be used after a single dash.
Float64SliceVar defines a float64[] flag with specified name, default value, and usage string.
Float64SliceVarP is like Float64SliceVar, but accepts a shorthand letter that can be used after a single dash.
Float64Var defines a float64 flag with specified name, default value, and usage string.
Float64VarP is like Float64Var, but accepts a shorthand letter that can be used after a single dash.
Int defines an int flag with specified name, default value, and usage string.
Int16 defines an int16 flag with specified name, default value, and usage string.
Int16P is like Int16, but accepts a shorthand letter that can be used after a single dash.
Int16Var defines an int16 flag with specified name, default value, and usage string.
Int16VarP is like Int16Var, but accepts a shorthand letter that can be used after a single dash.
Int32 defines an int32 flag with specified name, default value, and usage string.
Int32P is like Int32, but accepts a shorthand letter that can be used after a single dash.
Int32Slice defines a []int32 flag with specified name, default value, and usage string.
Int32SliceP is like Int32Slice, but accepts a shorthand letter that can be used after a single dash.
Int32SliceVar defines a int32[] flag with specified name, default value, and usage string.
Int32SliceVarP is like Int32SliceVar, but accepts a shorthand letter that can be used after a single dash.
Int32Var defines an int32 flag with specified name, default value, and usage string.
Int32VarP is like Int32Var, but accepts a shorthand letter that can be used after a single dash.
Int64 defines an int64 flag with specified name, default value, and usage string.
Int64P is like Int64, but accepts a shorthand letter that can be used after a single dash.
Int64Slice defines a []int64 flag with specified name, default value, and usage string.
Int64SliceP is like Int64Slice, but accepts a shorthand letter that can be used after a single dash.
Int64SliceVar defines a int64[] flag with specified name, default value, and usage string.
Int64SliceVarP is like Int64SliceVar, but accepts a shorthand letter that can be used after a single dash.
Int64Var defines an int64 flag with specified name, default value, and usage string.
Int64VarP is like Int64Var, but accepts a shorthand letter that can be used after a single dash.
Int8 defines an int8 flag with specified name, default value, and usage string.
Int8P is like Int8, but accepts a shorthand letter that can be used after a single dash.
Int8Var defines an int8 flag with specified name, default value, and usage string.
Int8VarP is like Int8Var, but accepts a shorthand letter that can be used after a single dash.
IntP is like Int, but accepts a shorthand letter that can be used after a single dash.
IntSlice defines a []int flag with specified name, default value, and usage string.
IntSliceP is like IntSlice, but accepts a shorthand letter that can be used after a single dash.
IntSliceVar defines a int[] flag with specified name, default value, and usage string.
IntSliceVarP is like IntSliceVar, but accepts a shorthand letter that can be used after a single dash.
IntVar defines an int flag with specified name, default value, and usage string.
IntVarP is like IntVar, but accepts a shorthand letter that can be used after a single dash.
IP defines an net.IP flag with specified name, default value, and usage string.
IPMask defines an net.IPMask flag with specified name, default value, and usage string.
IPMaskP is like IP, but accepts a shorthand letter that can be used after a single dash.
IPMaskVar defines an net.IPMask flag with specified name, default value, and usage string.
IPMaskVarP is like IPMaskVar, but accepts a shorthand letter that can be used after a single dash.
IPNet defines an net.IPNet flag with specified name, default value, and usage string.
IPNetP is like IPNet, but accepts a shorthand letter that can be used after a single dash.
IPNetSlice defines a []net.IPNet flag with specified name, default value, and usage string.
IPNetSliceP is like IPNetSlice, but accepts a shorthand letter that can be used after a single dash.
IPNetSliceVar defines a []net.IPNet flag with specified name, default value, and usage string.
IPNetSliceVarP is like IPNetSliceVar, but accepts a shorthand letter that can be used after a single dash.
IPNetVar defines an net.IPNet flag with specified name, default value, and usage string.
IPNetVarP is like IPNetVar, but accepts a shorthand letter that can be used after a single dash.
IPP is like IP, but accepts a shorthand letter that can be used after a single dash.
IPSlice defines a []net.IP flag with specified name, default value, and usage string.
IPSliceP is like IPSlice, but accepts a shorthand letter that can be used after a single dash.
IPSliceVar defines a []net.IP flag with specified name, default value, and usage string.
IPSliceVarP is like IPSliceVar, but accepts a shorthand letter that can be used after a single dash.
IPVar defines an net.IP flag with specified name, default value, and usage string.
IPVarP is like IPVar, but accepts a shorthand letter that can be used after a single dash.
Lookup returns the Flag structure of the named command-line flag, returning nil if none exists.
NArg is the number of arguments remaining after flags have been processed.
NewFlagSet returns a new, empty flag set with the specified name, error handling property and SortFlags set to true.
NFlag returns the number of command-line flags that have been set.
Parse parses the command-line flags from os.Args[1:].
ParseAll parses the command-line flags from os.Args[1:] and called fn for each.
Parsed returns true if the command-line flags have been parsed.
ParseIPv4Mask written in IP form (e.g.
PFlagFromGoFlag will return a *pflag.Flag given a *flag.Flag If the *flag.Flag.Name was a single character (ex: `v`) it will be accessiblei with both `-v` and `--v` in flags.
PrintDefaults prints to standard error the default values of all defined command-line flags.
Set sets the value of the named command-line flag.
SetInterspersed sets whether to support interspersed option/non-option arguments.
ShorthandLookup returns the Flag structure of the short handed flag, returning nil if none exists.
String defines a string flag with specified name, default value, and usage string.
StringArray defines a string flag with specified name, default value, and usage string.
StringArrayP is like StringArray, but accepts a shorthand letter that can be used after a single dash.
StringArrayVar defines a string flag with specified name, default value, and usage string.
StringArrayVarP is like StringArrayVar, but accepts a shorthand letter that can be used after a single dash.
StringP is like String, but accepts a shorthand letter that can be used after a single dash.
StringSlice defines a string flag with specified name, default value, and usage string.
StringSliceP is like StringSlice, but accepts a shorthand letter that can be used after a single dash.
StringSliceVar defines a string flag with specified name, default value, and usage string.
StringSliceVarP is like StringSliceVar, but accepts a shorthand letter that can be used after a single dash.
StringToInt defines a string flag with specified name, default value, and usage string.
StringToInt64 defines a string flag with specified name, default value, and usage string.
StringToInt64P is like StringToInt64, but accepts a shorthand letter that can be used after a single dash.
StringToInt64Var defines a string flag with specified name, default value, and usage string.
StringToInt64VarP is like StringToInt64Var, but accepts a shorthand letter that can be used after a single dash.
StringToIntP is like StringToInt, but accepts a shorthand letter that can be used after a single dash.
StringToIntVar defines a string flag with specified name, default value, and usage string.
StringToIntVarP is like StringToIntVar, but accepts a shorthand letter that can be used after a single dash.
StringToString defines a string flag with specified name, default value, and usage string.
StringToStringP is like StringToString, but accepts a shorthand letter that can be used after a single dash.
StringToStringVar defines a string flag with specified name, default value, and usage string.
StringToStringVarP is like StringToStringVar, but accepts a shorthand letter that can be used after a single dash.
StringVar defines a string flag with specified name, default value, and usage string.
StringVarP is like StringVar, but accepts a shorthand letter that can be used after a single dash.
Uint defines a uint flag with specified name, default value, and usage string.
Uint16 defines a uint flag with specified name, default value, and usage string.
Uint16P is like Uint16, but accepts a shorthand letter that can be used after a single dash.
Uint16Var defines a uint flag with specified name, default value, and usage string.
Uint16VarP is like Uint16Var, but accepts a shorthand letter that can be used after a single dash.
Uint32 defines a uint32 flag with specified name, default value, and usage string.
Uint32P is like Uint32, but accepts a shorthand letter that can be used after a single dash.
Uint32Var defines a uint32 flag with specified name, default value, and usage string.
Uint32VarP is like Uint32Var, but accepts a shorthand letter that can be used after a single dash.
Uint64 defines a uint64 flag with specified name, default value, and usage string.
Uint64P is like Uint64, but accepts a shorthand letter that can be used after a single dash.
Uint64Var defines a uint64 flag with specified name, default value, and usage string.
Uint64VarP is like Uint64Var, but accepts a shorthand letter that can be used after a single dash.
Uint8 defines a uint8 flag with specified name, default value, and usage string.
Uint8P is like Uint8, but accepts a shorthand letter that can be used after a single dash.
Uint8Var defines a uint8 flag with specified name, default value, and usage string.
Uint8VarP is like Uint8Var, but accepts a shorthand letter that can be used after a single dash.
UintP is like Uint, but accepts a shorthand letter that can be used after a single dash.
UintSlice defines a []uint flag with specified name, default value, and usage string.
UintSliceP is like UintSlice, but accepts a shorthand letter that can be used after a single dash.
UintSliceVar defines a uint[] flag with specified name, default value, and usage string.
UintSliceVarP is like the UintSliceVar, but accepts a shorthand letter that can be used after a single dash.
UintVar defines a uint flag with specified name, default value, and usage string.
UintVarP is like UintVar, but accepts a shorthand letter that can be used after a single dash.
UnquoteUsage extracts a back-quoted name from the usage string for a flag and returns it and the un-quoted usage.
Var defines a flag with the specified name and usage string.
VarP is like Var, but accepts a shorthand letter that can be used after a single dash.
Visit visits the command-line flags in lexicographical order or in primordial order if f.SortFlags is false, calling fn for each.
VisitAll visits the command-line flags in lexicographical order or in primordial order if f.SortFlags is false, calling fn for each.

# Constants

ContinueOnError will return an err from Parse() if an error is found.
ExitOnError will call os.Exit(2) if an error is found when parsing.
PanicOnError will panic() if an error is found when parsing flags.

# Variables

CommandLine is the default set of command-line flags, parsed from os.Args.
ErrHelp is the error returned if the flag -help is invoked but no such flag is defined.
Usage prints to standard error a usage message documenting all defined command-line flags.

# Structs

A Flag represents the state of a flag.
A FlagSet represents a set of defined flags.
ParseErrorsWhitelist defines the parsing errors that can be ignored.

# Interfaces

SliceValue is a secondary interface to all flags which hold a list of values.
Value is the interface to the dynamic value stored in a flag.

# Type aliases

ErrorHandling defines how to handle flag parsing errors.
NormalizedName is a flag name that has been normalized according to rules for the FlagSet (e.g.