flag

package
v0.0.0-...-a7186bf Latest Latest
Warning

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

Go to latest
Published: Jul 14, 2026 License: Apache-2.0, MIT Imports: 15 Imported by: 0

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

Constants

This section is empty.

Variables

View Source
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")
)
View Source
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.

View Source
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

func Add[T any](registry *Registry, name string, v *T, options ...Option) *pflag.Flag

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

func AddToGroup(name string, flags ...*pflag.Flag)

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

func MarkMutuallyExclusive(flags ...*pflag.Flag)

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

func MarkOneRequired(flags ...*pflag.Flag)

MarkOneRequired marks that at least one of the specified flags is required when parsing command lines.

func MarkRequired

func MarkRequired(flags ...*pflag.Flag)

MarkRequired marks that all of the specified flags must be required when parsing command lines.

func MarkRequiredTogether

func MarkRequiredTogether(flags ...*pflag.Flag)

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

func Register(registry *Registry, v any)

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

func Unmarshal(out any, data []byte) error

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

type DefaultFunc func(ctx context.Context) (string, error)

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

func Groups

func Groups(fs *pflag.FlagSet) []*Group

Groups returns a slice containing all flag [Group]s in the flagset, sorted by group name and subsorted by flag name. Flags that are not part of a named group get added to the group "General Flags" -- which is always sorted last.

func (*Group) Hidden

func (g *Group) Hidden() bool

Hidden returns true if all flags in the group are marked as Hidden.

type Option

type Option interface {
	// contains filtered or unexported methods
}

Option configures an optional property of a flag registered by Add.

func Callback

func Callback(fn any) Option

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

func CompleteFilesMatching(exts ...string) Option

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

func CompleteFrom(options ...string) Option

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

func CompleterFunc(fn func(toComplete string) []string) Option

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

func DefaultFromEnv(name string) Option

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

func RepeatableUpTo(n int) Option

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 Shorthand

func Shorthand(short string) Option

Shorthand sets the single-character shorthand alias for the flag.

func Type

func Type(name string) Option

Type overrides the reported flag type name, bypassing the default kebab-case name derived from the Go type.

func UnmarshalWith

func UnmarshalWith[T any](unmarshal func(data []byte) (T, error)) Option

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.

func Usage

func Usage(usage string) Option

Usage sets the help string displayed for the flag.

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

type Registry flagreg.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.

Directories

Path Synopsis
Package flagtest provides testing utilities for the cli/flag package and the spf13/pflag packages.
Package flagtest provides testing utilities for the cli/flag package and the spf13/pflag packages.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL