Documentation
¶
Overview ¶
Package goflag provides a simple, type-safe command-line flag parsing library with support for arbitrarily nested subcommands, required-flag validation, per-flag validators, mutually exclusive flag groups, persistent (inherited) flags, and shell completion generation.
Quick start ¶
cli := goflag.New("myapp", "Does something useful")
cli.String("config", "c", &cfg, "Path to config file").Required()
cli.Bool("verbose", "v", &verbose, "Verbose output")
subcmd, err := cli.Parse(os.Args)
if err != nil { log.Fatal(err) }
if subcmd != nil {
if err := subcmd.Handler(nil); err != nil { log.Fatal(err) }
}
Author: Dr. Abiira Nathan. Date: Sept 25. 2023 License: MIT License
Index ¶
- func Choices[T comparable](choices []T) func(v any) error
- func Max[T cmp.Ordered](maxValue T) func(v any) error
- func MaxStringLen(length int) func(v any) error
- func Min[T cmp.Ordered](minValue T) func(v any) error
- func MinStringLen(length int) func(v any) error
- func NotEmpty(v any) error
- func ParseBool(value string) (bool, error)
- func ParseDirPath(value string) (string, error)
- func ParseDuration(value string) (time.Duration, error)
- func ParseEmail(value string) (string, error)
- func ParseFilePath(value string) (string, error)
- func ParseFloat32(value string) (float32, error)
- func ParseFloat64(value string) (float64, error)
- func ParseHostPort(value string) (string, error)
- func ParseIP(value string) (net.IP, error)
- func ParseInt(value string) (int, error)
- func ParseInt64(value string) (int64, error)
- func ParseIntSlice(value string) ([]int, error)
- func ParseMAC(value string) (net.HardwareAddr, error)
- func ParseRune(value string) (rune, error)
- func ParseStringSlice(value string) ([]string, error)
- func ParseTime(value string) (time.Time, error)
- func ParseUUID(value string) (uuid.UUID, error)
- func ParseUrl(value string) (*url.URL, error)
- func Range[T cmp.Ordered](minValue, maxValue T) func(v any) error
- type CLI
- func (c *CLI) Args() []string
- func (c *CLI) Bool(name, shortName string, valuePtr *bool, usage string) *Flag
- func (c *CLI) DirPath(name, shortName string, valuePtr *string, usage string) *Flag
- func (c *CLI) Duration(name, shortName string, valuePtr *time.Duration, usage string) *Flag
- func (c *CLI) Email(name, shortName string, valuePtr *string, usage string) *Flag
- func (c *CLI) ExclusiveFlags(names ...string) *CLI
- func (c *CLI) FilePath(name, shortName string, valuePtr *string, usage string) *Flag
- func (c *CLI) Float32(name, shortName string, valuePtr *float32, usage string) *Flag
- func (c *CLI) Float64(name, shortName string, valuePtr *float64, usage string) *Flag
- func (c *CLI) GenBashCompletion(w io.Writer)
- func (c *CLI) GenZshCompletion(w io.Writer)
- func (c *CLI) HostPortPair(name, shortName string, valuePtr *string, usage string) *Flag
- func (c *CLI) IP(name, shortName string, valuePtr *net.IP, usage string) *Flag
- func (c *CLI) InstallCompletion(shell string) error
- func (c *CLI) Int(name, shortName string, valuePtr *int, usage string) *Flag
- func (c *CLI) Int64(name, shortName string, valuePtr *int64, usage string) *Flag
- func (c *CLI) IntSlice(name, shortName string, valuePtr *[]int, usage string) *Flag
- func (c *CLI) MAC(name, shortName string, valuePtr *net.HardwareAddr, usage string) *Flag
- func (c *CLI) Parse(argv []string) (*SubCMD, error)
- func (c *CLI) ParseAndInvoke(argv []string, userdata any, preInvokeCallback func(cmd *SubCMD, userdata any)) error
- func (c *CLI) PrintUsage(w io.Writer)
- func (c *CLI) Rune(name, shortName string, valuePtr *rune, usage string) *Flag
- func (c *CLI) String(name, shortName string, valuePtr *string, usage string) *Flag
- func (c *CLI) StringSlice(name, shortName string, valuePtr *[]string, usage string) *Flag
- func (c *CLI) SubCommand(name, description string, handler func(userdata any) error) *SubCMD
- func (c *CLI) Time(name, shortName string, valuePtr *time.Time, usage string) *Flag
- func (c *CLI) URL(name, shortName string, valuePtr *url.URL, usage string) *Flag
- func (c *CLI) UUID(name, shortName string, valuePtr *uuid.UUID, usage string) *Flag
- func (c *CLI) UninstallCompletion(shell string) error
- type Flag
- type FlagValidator
- type SubCMD
- func (cmd *SubCMD) Args() []string
- func (cmd *SubCMD) Bool(name, shortName string, valuePtr *bool, usage string) *SubCMD
- func (cmd *SubCMD) DirPath(name, shortName string, valuePtr *string, usage string) *SubCMD
- func (cmd *SubCMD) Duration(name, shortName string, valuePtr *time.Duration, usage string) *SubCMD
- func (cmd *SubCMD) Email(name, shortName string, valuePtr *string, usage string) *SubCMD
- func (cmd *SubCMD) ExclusiveFlags(names ...string) *SubCMD
- func (cmd *SubCMD) FilePath(name, shortName string, valuePtr *string, usage string) *SubCMD
- func (cmd *SubCMD) Flag(ft flagType, name, shortName string, valuePtr any, usage string) *SubCMD
- func (cmd *SubCMD) Float32(name, shortName string, valuePtr *float32, usage string) *SubCMD
- func (cmd *SubCMD) Float64(name, shortName string, valuePtr *float64, usage string) *SubCMD
- func (cmd *SubCMD) HostPortPair(name, shortName string, valuePtr *string, usage string) *SubCMD
- func (cmd *SubCMD) IP(name, shortName string, valuePtr *net.IP, usage string) *SubCMD
- func (cmd *SubCMD) Int(name, shortName string, valuePtr *int, usage string) *SubCMD
- func (cmd *SubCMD) Int64(name, shortName string, valuePtr *int64, usage string) *SubCMD
- func (cmd *SubCMD) IntSlice(name, shortName string, valuePtr *[]int, usage string) *SubCMD
- func (cmd *SubCMD) MAC(name, shortName string, valuePtr *net.HardwareAddr, usage string) *SubCMD
- func (cmd *SubCMD) Name() string
- func (cmd *SubCMD) PersistentBool(name, shortName string, valuePtr *bool, usage string) *SubCMD
- func (cmd *SubCMD) PersistentDirPath(name, shortName string, valuePtr *string, usage string) *SubCMD
- func (cmd *SubCMD) PersistentDuration(name, shortName string, valuePtr *time.Duration, usage string) *SubCMD
- func (cmd *SubCMD) PersistentEmail(name, shortName string, valuePtr *string, usage string) *SubCMD
- func (cmd *SubCMD) PersistentFilePath(name, shortName string, valuePtr *string, usage string) *SubCMD
- func (cmd *SubCMD) PersistentFlag(ft flagType, name, shortName string, valuePtr any, usage string) *SubCMD
- func (cmd *SubCMD) PersistentFloat32(name, shortName string, valuePtr *float32, usage string) *SubCMD
- func (cmd *SubCMD) PersistentFloat64(name, shortName string, valuePtr *float64, usage string) *SubCMD
- func (cmd *SubCMD) PersistentHostPortPair(name, shortName string, valuePtr *string, usage string) *SubCMD
- func (cmd *SubCMD) PersistentIP(name, shortName string, valuePtr *net.IP, usage string) *SubCMD
- func (cmd *SubCMD) PersistentInt(name, shortName string, valuePtr *int, usage string) *SubCMD
- func (cmd *SubCMD) PersistentInt64(name, shortName string, valuePtr *int64, usage string) *SubCMD
- func (cmd *SubCMD) PersistentIntSlice(name, shortName string, valuePtr *[]int, usage string) *SubCMD
- func (cmd *SubCMD) PersistentMAC(name, shortName string, valuePtr *net.HardwareAddr, usage string) *SubCMD
- func (cmd *SubCMD) PersistentRune(name, shortName string, valuePtr *rune, usage string) *SubCMD
- func (cmd *SubCMD) PersistentString(name, shortName string, valuePtr *string, usage string) *SubCMD
- func (cmd *SubCMD) PersistentStringSlice(name, shortName string, valuePtr *[]string, usage string) *SubCMD
- func (cmd *SubCMD) PersistentTime(name, shortName string, valuePtr *time.Time, usage string) *SubCMD
- func (cmd *SubCMD) PersistentURL(name, shortName string, valuePtr *url.URL, usage string) *SubCMD
- func (cmd *SubCMD) PersistentUUID(name, shortName string, valuePtr *uuid.UUID, usage string) *SubCMD
- func (cmd *SubCMD) PrintUsage(w io.Writer)
- func (cmd *SubCMD) Required() *SubCMD
- func (cmd *SubCMD) Rune(name, shortName string, valuePtr *rune, usage string) *SubCMD
- func (cmd *SubCMD) String(name, shortName string, valuePtr *string, usage string) *SubCMD
- func (cmd *SubCMD) StringSlice(name, shortName string, valuePtr *[]string, usage string) *SubCMD
- func (cmd *SubCMD) SubCommand(name, description string, handler func(userdata any) error) *SubCMD
- func (cmd *SubCMD) Time(name, shortName string, valuePtr *time.Time, usage string) *SubCMD
- func (cmd *SubCMD) URL(name, shortName string, valuePtr *url.URL, usage string) *SubCMD
- func (cmd *SubCMD) UUID(name, shortName string, valuePtr *uuid.UUID, usage string) *SubCMD
- func (cmd *SubCMD) Validate(validators ...FlagValidator) *SubCMD
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func Choices ¶ added in v0.1.5
func Choices[T comparable](choices []T) func(v any) error
Choices returns a validator function that checks if the provided value is one of the allowed choices.
func Max ¶ added in v0.1.5
Max returns a validator function that checks if the provided value is less than or equal to the specified maximum value.
func MaxStringLen ¶ added in v0.1.5
MaxStringLen returns a validator function that checks if the provided string value has a maximum length.
func Min ¶ added in v0.1.5
Min returns a validator function that checks if the provided value is greater than or equal to the specified minimum value.
func MinStringLen ¶ added in v0.1.5
MinStringLen returns a validator function that checks if the provided string value has a minimum length.
func NotEmpty ¶ added in v0.4.0
NotEmpty returns a validator function that checks if the provided string value is not empty.
func ParseDirPath ¶
ParseDirPath resolves absolute directory path and checks that it exists.
func ParseDuration ¶
ParseDuration parses a string to a duration. Uses time.ParseDuration. Supported units are "ns", "us" (or "µs"), "ms", "s", "m", "h". e.g 1h30m, 1h, 1m30s, 1m, 1m30s, 1ms, 1us, 1ns
func ParseEmail ¶
ParseEmail parses a string to an email address using mail.ParseAddress.
func ParseFilePath ¶
ParseFilePath resolves absolute file path and checks that it exists.
func ParseFloat32 ¶
ParseFloat32 parses a string to a float32.
func ParseFloat64 ¶
ParseFloat64 parses a string to a float64.
func ParseHostPort ¶
ParseHostPort parses a host:port pair from a string. An empty string is considered a valid host. :) e.g ":8000" is a valid host-port pair.
func ParseInt64 ¶
ParseInt64 parses a string to an int64.
func ParseIntSlice ¶
ParseIntSlice parses a comma-separated string into a slice of ints.
func ParseStringSlice ¶
ParseStringSlice parses a comma-separated string into a slice of strings.
func ParseTime ¶
ParseTime parses a string to a time.Time. Tries multiple formats in order until one succeeds. Supported formats are: "2006-01-02T15:04:05Z07:00", "2006-01-02T15:04:05Z0700", "2006-01-02T15:04:05Z07", "2006-01-02T15:04:05", "2006-01-02T15:04 MST"
Types ¶
type CLI ¶ added in v0.2.0
type CLI struct {
// contains filtered or unexported fields
}
CLI is the root command-line context. It owns global flags, top-level subcommands, mutually exclusive flag groups, and the positional arguments that remain after parsing.
Not safe for concurrent use.
func New ¶ added in v0.2.0
New creates a new CLI with the given program name and description. A "completion" subcommand is automatically registered that can generate and install bash/zsh completion scripts.
func (*CLI) Args ¶ added in v0.6.0
Args returns the positional arguments collected at the root level during the most recent Parse call.
func (*CLI) Bool ¶ added in v0.2.0
Bool adds a boolean flag to the CLI. Boolean flags are set to true by their presence alone; no explicit value is required.
func (*CLI) DirPath ¶ added in v0.2.0
DirPath adds a directory path flag to the CLI. The directory must exist at parse time.
func (*CLI) Duration ¶ added in v0.2.0
Duration adds a time.Duration flag to the CLI. Accepts duration strings such as "5s", "2m30s", "1h".
func (*CLI) ExclusiveFlags ¶ added in v0.6.0
ExclusiveFlags declares that at most one flag from names may be set in a single invocation. Returns c for chaining.
Example:
cli.ExclusiveFlags("install", "uninstall")
func (*CLI) FilePath ¶ added in v0.2.0
FilePath adds a file path flag to the CLI. The file must exist at parse time.
func (*CLI) GenBashCompletion ¶ added in v0.2.0
GenBashCompletion generates a bash completion script and writes it to w. The script provides tab completion for global flags, subcommands (including nested ones), and per-subcommand flags. Only long-form flags (--flag) are surfaced in completions to reduce clutter; short forms remain usable.
func (*CLI) GenZshCompletion ¶ added in v0.2.0
GenZshCompletion generates a zsh completion script and writes it to w. The script uses the _arguments / state-machine approach and supports arbitrarily nested subcommands.
func (*CLI) HostPortPair ¶ added in v0.2.0
HostPortPair adds a host:port flag to the CLI (e.g. "localhost:8080").
func (*CLI) InstallCompletion ¶ added in v0.2.0
InstallCompletion generates and installs the completion script for the named shell ("bash" or "zsh") to the user's home directory, and updates the relevant rc file if the source line is not already present.
Returns an error if the shell is not supported or if any file operation fails.
func (*CLI) IntSlice ¶ added in v0.2.0
IntSlice adds a comma-separated integer slice flag to the CLI.
func (*CLI) Parse ¶ added in v0.2.0
Parse tokenises argv (pass os.Args), populates flag variables, and returns the deepest matching SubCMD in the subcommand tree. Positional arguments are stored on the matched SubCMD (or on the CLI itself when no subcommand matched). Returns nil, nil when no subcommand was found and no error occurred.
The first element of argv is assumed to be the program name and is skipped.
func (*CLI) ParseAndInvoke ¶ added in v0.4.0
func (c *CLI) ParseAndInvoke(argv []string, userdata any, preInvokeCallback func(cmd *SubCMD, userdata any)) error
ParseAndInvoke is a convenience wrapper around Parse that immediately calls the matched subcommand's Handler, passing userdata through to it. If a preInvokeCallback is provided it is called with the matched subcommand (which may be nil) and userdata before the handler runs.
Returns any error from Parse or from the handler itself.
func (*CLI) PrintUsage ¶ added in v0.2.0
PrintUsage writes the full usage message (global flags + subcommand list) to w.
func (*CLI) StringSlice ¶ added in v0.2.0
StringSlice adds a comma-separated string slice flag to the CLI.
func (*CLI) SubCommand ¶ added in v0.2.0
SubCommand registers a top-level subcommand and returns it for flag configuration via method chaining.
Panics if name or description is empty, or if handler is nil.
func (*CLI) URL ¶ added in v0.2.0
URL adds a URL flag to the CLI, validated via url.ParseRequestURI.
func (*CLI) UninstallCompletion ¶ added in v0.2.0
UninstallCompletion removes the completion script for the named shell and cleans up any source/fpath lines added by InstallCompletion.
Returns an error if the shell is not supported or if removal fails.
type Flag ¶ added in v0.1.0
type Flag struct {
// contains filtered or unexported fields
}
Flag represents a single command-line flag with its type, names, default value pointer, usage string, and optional validators.
func (*Flag) Required ¶ added in v0.1.0
Required marks the flag as mandatory and returns it for chaining.
func (*Flag) Validate ¶ added in v0.1.0
func (flag *Flag) Validate(validators ...FlagValidator) *Flag
Validate appends validators to the flag and returns the flag for chaining.
type FlagValidator ¶ added in v0.3.0
FlagValidator is a user-supplied validation function called after a flag's value has been parsed. It receives the concrete (dereferenced) value and must return nil on success or error on failure.
type SubCMD ¶ added in v0.4.0
type SubCMD struct {
Handler func(userdata any) error // Invoked by ParseAndInvoke when this subcommand is matched.
// contains filtered or unexported fields
}
SubCMD represents a subcommand in the CLI application. Subcommands may be nested arbitrarily deep; each SubCMD holds a pointer to its parent so that help output, persistent-flag inheritance, and completion generation can walk the full ancestry chain.
Not safe for concurrent use during registration; safe for concurrent reads after Parse has returned.
func (*SubCMD) Args ¶ added in v0.6.0
Args returns the positional arguments captured for this subcommand during the most recent Parse call. Positional arguments are any tokens that are not flag names, flag values, or recognised nested subcommand names.
func (*SubCMD) ExclusiveFlags ¶ added in v0.6.0
ExclusiveFlags declares that at most one flag from names may be provided in a single invocation of this subcommand. Returns cmd for chaining.
func (*SubCMD) Flag ¶ added in v0.4.0
Flag adds a typed flag to the subcommand and returns the subcommand for continued method chaining. The final flag added is the one affected by subsequent Required() and Validate() calls.
func (*SubCMD) Float32 ¶ added in v0.4.0
Float32 adds a 32-bit floating-point flag to the subcommand.
func (*SubCMD) Float64 ¶ added in v0.4.0
Float64 adds a 64-bit floating-point flag to the subcommand.
func (*SubCMD) HostPortPair ¶ added in v0.4.0
HostPortPair adds a host:port flag to the subcommand.
func (*SubCMD) IP ¶ added in v0.4.0
IP adds an IP address flag to the subcommand. Previously registered with flagFloat32 by mistake — fixed.
func (*SubCMD) IntSlice ¶ added in v0.4.0
IntSlice adds a comma-separated integer slice flag to the subcommand.
func (*SubCMD) PersistentBool ¶ added in v0.6.0
PersistentBool adds a persistent boolean flag to the subcommand.
func (*SubCMD) PersistentDirPath ¶ added in v0.6.0
func (cmd *SubCMD) PersistentDirPath(name, shortName string, valuePtr *string, usage string) *SubCMD
PersistentDirPath adds a persistent directory path flag to the subcommand.
func (*SubCMD) PersistentDuration ¶ added in v0.6.0
func (cmd *SubCMD) PersistentDuration(name, shortName string, valuePtr *time.Duration, usage string) *SubCMD
PersistentDuration adds a persistent time.Duration flag to the subcommand.
func (*SubCMD) PersistentEmail ¶ added in v0.6.0
PersistentEmail adds a persistent email address flag to the subcommand.
func (*SubCMD) PersistentFilePath ¶ added in v0.6.0
func (cmd *SubCMD) PersistentFilePath(name, shortName string, valuePtr *string, usage string) *SubCMD
PersistentFilePath adds a persistent file path flag to the subcommand.
func (*SubCMD) PersistentFlag ¶ added in v0.6.0
func (cmd *SubCMD) PersistentFlag(ft flagType, name, shortName string, valuePtr any, usage string) *SubCMD
PersistentFlag adds a typed flag that is automatically visible to all nested subcommands (children, grandchildren, etc.) registered under cmd. It returns cmd for method chaining; Required() and Validate() target the last added persistent flag.
func (*SubCMD) PersistentFloat32 ¶ added in v0.6.0
func (cmd *SubCMD) PersistentFloat32(name, shortName string, valuePtr *float32, usage string) *SubCMD
PersistentFloat32 adds a persistent 32-bit float flag to the subcommand.
func (*SubCMD) PersistentFloat64 ¶ added in v0.6.0
func (cmd *SubCMD) PersistentFloat64(name, shortName string, valuePtr *float64, usage string) *SubCMD
PersistentFloat64 adds a persistent 64-bit float flag to the subcommand.
func (*SubCMD) PersistentHostPortPair ¶ added in v0.6.0
func (cmd *SubCMD) PersistentHostPortPair(name, shortName string, valuePtr *string, usage string) *SubCMD
PersistentHostPortPair adds a persistent host:port flag to the subcommand.
func (*SubCMD) PersistentIP ¶ added in v0.6.0
PersistentIP adds a persistent IP address flag to the subcommand.
func (*SubCMD) PersistentInt ¶ added in v0.6.0
PersistentInt adds a persistent integer flag to the subcommand.
func (*SubCMD) PersistentInt64 ¶ added in v0.6.0
PersistentInt64 adds a persistent 64-bit integer flag to the subcommand.
func (*SubCMD) PersistentIntSlice ¶ added in v0.6.0
func (cmd *SubCMD) PersistentIntSlice(name, shortName string, valuePtr *[]int, usage string) *SubCMD
PersistentIntSlice adds a persistent comma-separated integer slice flag to the subcommand.
func (*SubCMD) PersistentMAC ¶ added in v0.6.0
func (cmd *SubCMD) PersistentMAC(name, shortName string, valuePtr *net.HardwareAddr, usage string) *SubCMD
PersistentMAC adds a persistent hardware (MAC) address flag to the subcommand.
func (*SubCMD) PersistentRune ¶ added in v0.6.0
PersistentRune adds a persistent rune flag to the subcommand.
func (*SubCMD) PersistentString ¶ added in v0.6.0
PersistentString adds a persistent string flag to the subcommand.
func (*SubCMD) PersistentStringSlice ¶ added in v0.6.0
func (cmd *SubCMD) PersistentStringSlice(name, shortName string, valuePtr *[]string, usage string) *SubCMD
PersistentStringSlice adds a persistent comma-separated string slice flag to the subcommand.
func (*SubCMD) PersistentTime ¶ added in v0.6.0
func (cmd *SubCMD) PersistentTime(name, shortName string, valuePtr *time.Time, usage string) *SubCMD
PersistentTime adds a persistent time.Time flag to the subcommand.
func (*SubCMD) PersistentURL ¶ added in v0.6.0
PersistentURL adds a persistent URL flag to the subcommand.
func (*SubCMD) PersistentUUID ¶ added in v0.6.0
func (cmd *SubCMD) PersistentUUID(name, shortName string, valuePtr *uuid.UUID, usage string) *SubCMD
PersistentUUID adds a persistent UUID flag to the subcommand.
func (*SubCMD) PrintUsage ¶ added in v0.4.0
PrintUsage writes usage information for this subcommand to w.
func (*SubCMD) Required ¶ added in v0.4.0
Required marks the most recently added flag (own or persistent) as required.
func (*SubCMD) StringSlice ¶ added in v0.4.0
StringSlice adds a comma-separated string slice flag to the subcommand.
func (*SubCMD) SubCommand ¶ added in v0.6.0
SubCommand registers a nested subcommand under cmd and returns the new child SubCMD so that its flags can be configured via method chaining.
Panics if name or description is empty, or if handler is nil.
func (*SubCMD) Validate ¶ added in v0.4.0
func (cmd *SubCMD) Validate(validators ...FlagValidator) *SubCMD
Validate appends validators to the most recently added flag (own or persistent).