Documentation
¶
Overview ¶
Package flag simplifies command-line flag registration by wrapping github.com/spf13/pflag behind a small, type-driven surface.
Rather than exposing a distinct registration call per value type, the package decodes flag values through Unmarshal so that any supported type -- and any type that decodes itself -- can be bound to a flag with a single entrypoint. It additionally layers on grouping, requirement constraints, shell completion, and recursive registration of flag-bearing values.
Index ¶
- Variables
- func Add[T any](registry *Registry, name string, v *T, options ...Option) *pflag.Flag
- func AddToGroup(name string, flags ...*pflag.Flag)
- func MarkMutuallyExclusive(flags ...*pflag.Flag)
- func MarkOneRequired(flags ...*pflag.Flag)
- func MarkRequired(flags ...*pflag.Flag)
- func MarkRequiredTogether(flags ...*pflag.Flag)
- func Register(registry *Registry, v any)
- func Unmarshal(out any, data []byte) error
- type DefaultFunc
- type Group
- type Option
- func Callback(fn any) Option
- func CompleteDirs() Option
- func CompleteFiles() Option
- func CompleteFilesMatching(exts ...string) Option
- func CompleteFrom(options ...string) Option
- func CompleterFunc(fn func(toComplete string) []string) Option
- func DefaultFromEnv(name string) Option
- func DefaultFromFunc(fn DefaultFunc) Option
- func Hidden() Option
- func Repeatable() Option
- func RepeatableUpTo(n int) Option
- func Required() Option
- func Shorthand(short string) Option
- func Type(name string) Option
- func UnmarshalWith[T any](unmarshal func(data []byte) (T, error)) Option
- func Usage(usage string) Option
- type Registrar
- type Registry
- type Unmarshaler
Constants ¶
This section is empty.
Variables ¶
var ( // ErrInvalidTarget indicates the value passed to [Unmarshal] was not a // non-nil pointer that can be written to. ErrInvalidTarget = errors.New("target must be a non-nil pointer") // ErrUnsupportedType indicates the element type addressed by the target is // not one that [Unmarshal] knows how to decode. ErrUnsupportedType = errors.New("unsupported type") )
var ErrAlreadySet = errors.New("flag already specified")
ErrAlreadySet indicates a non-accumulating flag was specified more than once. Only unnamed slice flags (such as []string) accumulate across occurrences by default; any other flag reports this error on its second occurrence unless it was made repeatable with Repeatable or RepeatableUpTo.
var ErrTooManyOccurrences = errors.New("flag specified too many times")
ErrTooManyOccurrences indicates a flag was specified more times than its RepeatableUpTo cap allows.
Functions ¶
func Add ¶
Add registers a flag named name whose value is decoded into v, returning the created pflag.Flag.
By default the flag is decoded with Unmarshal and reports a kebab-case type name derived from T; both may be adjusted with Option values. A bool-kinded T is registered so that a bare --name implies true.
An unnamed slice T accumulates across repeated occurrences, so --name a --name b is equivalent to --name a,b; any other T reports ErrAlreadySet if specified more than once. Repeatable lifts that limit, and RepeatableUpTo caps it, reporting ErrTooManyOccurrences beyond the cap; a repeated non-slice flag keeps the last value. Callback options are invoked with the decoded value on each occurrence.
func AddToGroup ¶
AddToGroup assigns each of the given flags to the named display group. Flags that share a group name are reported together by Groups, and rendered under that heading in help output. A flag that is not added to any group is reported under the default "General Flags" heading.
func MarkMutuallyExclusive ¶
MarkMutuallyExclusive marks that all flags must be mutually exclusive with each other, and will generate an error when parsing flags that have both set.
func MarkOneRequired ¶
MarkOneRequired marks that at least one of the specified flags is required when parsing command lines.
func MarkRequired ¶
MarkRequired marks that all of the specified flags must be required when parsing command lines.
func MarkRequiredTogether ¶
MarkRequiredTogether marks that all flags must be specified together when any one flag is specified. Note that this does not mean that all flags are always required; it's all or none. If all flags are always required, then MarkRequired should be used.
func Register ¶
Register adds all flags associated to v into fs.
If v implements Registrar directly, it will be registered immediately.
If v does not implement Registrar, but is an iterable type like a slice, map, or structured object -- each visible field will recursively be inspected for whether it implements Registrar, and any discovered fields will be registered.
Note: If an object implements Registrar and contains fields of other types that may be Registrar types, the object is responsible for manually registering those fields.
func Unmarshal ¶
Unmarshal decodes data into out.
The element addressed by out is decoded by the first of these that applies: an Unmarshaler implementation, an encoding.TextUnmarshaler implementation, or -- for a string, boolean, integer, floating-point, or time.Duration element -- built-in parsing:
- Integers are parsed with the base inferred from the input (e.g. "0x" for hexadecimal, "0b" for binary, "0o" for octal, otherwise decimal).
- Floating-point values are parsed as strconv.ParseFloat does.
- time.Duration is parsed with time.ParseDuration.
- Strings are taken verbatim.
- Booleans accept only "true" or "false".
- Slices parse the input as comma-separated values, decoding each field by the rules above for the element type.
This function will return ErrInvalidTarget if out is not a writable pointer (nor a self-decoding value), ErrUnsupportedType if the element type is not supported, or any errors from the underlying API otherwise.
Types ¶
type DefaultFunc ¶
DefaultFunc is a function that can provide a flag default, only executed if a flag was not set during the CLI invocation.
type Group ¶
type Group struct {
// Name is the name of the flag group.
Name string
// Flags is a list of all the flags that are part of this group.
Flags []*pflag.Flag
}
Group represents a grouping of flags denoted by the name of a given group
type Option ¶
type Option interface {
// contains filtered or unexported methods
}
Option configures an optional property of a flag registered by Add.
func Callback ¶
Callback registers fn to be invoked with the flag's decoded value each time the flag is set. fn must be a function of one of these shapes:
func() func(value) func() error func(value) error
where value is any type the decoded flag value is assignable or convertible to (for example func(any) on a string flag). A function returning a non-nil error fails parsing with that error.
Callback panics if fn is not a function of a supported shape. If the decoded value cannot be converted to fn's parameter type, setting the flag reports an error wrapping [errCallbackType].
func CompleteDirs ¶
func CompleteDirs() Option
CompleteDirs completes the flag with directory names only.
func CompleteFiles ¶
func CompleteFiles() Option
CompleteFiles completes the flag with file names, deferring to the shell's default file completion.
func CompleteFilesMatching ¶
CompleteFilesMatching completes the flag with file names whose extension is one of exts. A leading dot on an extension is optional, so ".json" and "json" are equivalent.
func CompleteFrom ¶
CompleteFrom completes the flag with the members of options that are prefixed by the word being completed. File completion is suppressed so only the given options are offered.
func CompleterFunc ¶
CompleterFunc completes the flag with the candidates returned by fn for the word being completed. File completion is suppressed so only fn's candidates are offered.
func DefaultFromEnv ¶
DefaultFromEnv adds an environment variable that will be sourced for a default value for this flag.
func DefaultFromFunc ¶
func DefaultFromFunc(fn DefaultFunc) Option
DefaultFromFunc adds an DefaultFunc that will be executed for computing a default flag value if this was not specified.
func Hidden ¶
func Hidden() Option
Hidden marks the flag as hidden, omitting it from generated help and usage output while leaving it functional when specified.
func Repeatable ¶
func Repeatable() Option
Repeatable allows the flag to be specified any number of times. A repeated non-slice flag keeps the last value; a slice flag accumulates across occurrences.
func RepeatableUpTo ¶
RepeatableUpTo allows the flag to be specified up to n times, reporting ErrTooManyOccurrences on any further occurrence. It panics if n is less than one.
func Required ¶
func Required() Option
Required marks the flag as required, so parsing fails when it is omitted. It is shorthand for MarkRequired on the registered flag.
func Type ¶
Type overrides the reported flag type name, bypassing the default kebab-case name derived from the Go type.
func UnmarshalWith ¶
UnmarshalWith overrides how the raw flag bytes are decoded into the flag's value, replacing the default of Unmarshal. The type parameter is inferred from unmarshal, so callers supply a fully typed decoder.
type Registrar ¶
type Registrar interface {
RegisterFlags(fs *Registry)
}
Registrar abstracts objects that have flags that need to be registered to a Registry.
Registrars are queried as part of the Register operation, which allows for recursive and conditional registration of custom flag types.
type Registry ¶
Registry is the opaque flag destination threaded through registration. It wraps a pflag.Registry and records which Registrar instances have already been registered so that a shared instance registers its flags only once. Add is its only mutator.
type Unmarshaler ¶
type Unmarshaler interface {
// UnmarshalFlag decodes data into the receiver, returning an error if the
// input is not valid for the type.
UnmarshalFlag(data []byte) error
}
Unmarshaler is implemented by types that decode themselves from the raw bytes of a flag value.