goflag

package module
v0.7.1 Latest Latest
Warning

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

Go to latest
Published: May 28, 2026 License: MIT Imports: 15 Imported by: 2

README

goflag

A simple, type-safe command-line flag parsing library for Go with support for subcommands, custom flag validation, persistent flags, and mutually exclusive flags.

Features

  • Type-Safe Flags: Dedicated registration methods for strings, slices, numbers, networks, emails, UUIDs, files, and more.
  • Nested Subcommands: Arbitrarily deep nested subcommand trees.
  • Improved Handler Signature: Handlers match the func(userdata any) error signature, enabling robust error propagation and context passing.
  • Direct Dispatching: ParseAndInvoke automatically executes matched subcommand handlers, allowing arbitrary configurations or services to be threaded through as user data.
  • Persistent (Inherited) Flags: Declare persistent flags on subcommands that are automatically parsed and made available to all downstream subcommands.
  • Mutually Exclusive Groups: Define sets of flags where at most one can be provided.
  • Rich Flag Validators: Chain built-in validators or apply custom validation logic to any parsed flag value.
  • Shell Completions: Automated generation of Bash and Zsh completion scripts that fully support persistent flags and subcommand hierarchies.

Installation

go get github.com/abiiranathan/goflag

Quick Start

package main

import (
	"fmt"
	"log"
	"os"
	"time"

	"github.com/abiiranathan/goflag"
)

type AppConfig struct {
	Verbose bool
}

func main() {
	var (
		config  string
		verbose bool
		timeout time.Duration
		port    int
	)

	// Create CLI with application name and description
	cli := goflag.New("myapp", "A simple command-line utility")

	// Define global flags
	cli.String("config", "c", &config, "Path to config file").Required()
	cli.Bool("verbose", "v", &verbose, "Enable verbose output")
	cli.Duration("timeout", "t", &timeout, "Request timeout")
	cli.Int("port", "p", &port, "Port to listen on")

	// Option A: Traditional manual execution
	subcmd, err := cli.Parse(os.Args)
	if err != nil {
		log.Fatal(err)
	}

	fmt.Printf("Config: %s\n", config)
	fmt.Printf("Verbose: %v\n", verbose)

	if subcmd != nil && subcmd.Handler != nil {
		if err := subcmd.Handler(nil); err != nil {
			log.Fatal(err)
		}
	}

	// Option B: Automated dispatching using ParseAndInvoke with threaded userdata
	appConfig := &AppConfig{Verbose: verbose}
	err = cli.ParseAndInvoke(os.Args, appConfig, func(cmd *goflag.SubCMD, userdata any) {
		// Optional pre-invoke callback
		if cmd != nil {
			fmt.Printf("Dispatched subcommand: %s\n", cmd.Name())
		}
	})
	if err != nil {
		log.Fatal(err)
	}
}

Subcommands

Create arbitrarily nested subcommands with their own custom handler execution and argument configurations.

package main

import (
	"fmt"
	"log"
	"os"
	"strings"

	"github.com/abiiranathan/goflag"
)

var (
	name     string = "World"
	greeting string = "Hello"
	upper    bool
)

func greetUser(userdata any) error {
	message := fmt.Sprintf("%s, %s!", greeting, name)
	if upper {
		message = strings.ToUpper(message)
	}
	fmt.Println(message)
	return nil
}

func main() {
	cli := goflag.New("greeter", "A CLI to greet people")

	// Register a subcommand
	cli.SubCommand("greet", "Greet a person", greetUser).
		String("name", "n", &name, "Name of the person to greet").Required().
		String("greeting", "g", &greeting, "Greeting to use").
		Bool("upper", "u", &upper, "Print in upper case")

	_, err := cli.Parse(os.Args)
	if err != nil {
		log.Fatal(err)
	}
}
$ greeter greet --name John --upper
HELLO, JOHN!

$ greeter greet -n Alice -g "Good morning"
Good morning, Alice!

Persistent Flags

Persistent flags are defined on a subcommand and are automatically visible to, and parseable by, all descendants (children, grandchildren, etc.).

var deployEnv string

deployCmd := cli.SubCommand("deploy", "Deploy the application", func(userdata any) error {
	fmt.Println("Please specify a target environment: staging or prod")
	return nil
})

// Registered once on deploy command, inherited by both staging and prod subcommands.
deployCmd.PersistentString("env", "e", &deployEnv, "Deployment target environment (e.g. staging, prod)").Required()

deployCmd.SubCommand("staging", "Deploy to staging", func(userdata any) error {
	fmt.Printf("Deploying staging with target environment configuration: %s\n", deployEnv)
	return nil
})

deployCmd.SubCommand("prod", "Deploy to production", func(userdata any) error {
	fmt.Printf("Deploying production with target environment configuration: %s\n", deployEnv)
	return nil
})

Mutually Exclusive Flags

Declare constraints to ensure that at most one flag from a specific group is provided.

var (
	exportJSON bool
	exportYAML bool
)

cli.SubCommand("export", "Export dataset", handleExport).
	Bool("json", "j", &exportJSON, "Output as JSON").
	Bool("yaml", "y", &exportYAML, "Output as YAML").
	ExclusiveFlags("json", "yaml") // Parser errors if both flags are supplied

Custom Flag Validation

Attach custom criteria or use built-in helpers to validate any flag's deserialized value.

cli.Int("port", "p", &port, "Target server port").
	Required().
	Validate(goflag.Range(1024, 65535))

cli.String("shell", "s", &shell, "Target generation shell").
	Validate(goflag.Choices([]string{"bash", "zsh"}))

Available built-in validation helpers:

  • Choices([]T)
  • MinStringLen(length)
  • MaxStringLen(length)
  • Min(minValue)
  • Max(maxValue)
  • Range(minValue, maxValue)
  • NotEmpty

Supported Flag Types

Basic Types
cli.String("name", "n", &str, "String value")
cli.Int("count", "c", &num, "Integer value")
cli.Int64("big", "b", &big, "64-bit integer")
cli.Float32("ratio", "r", &f32, "32-bit float")
cli.Float64("pi", "p", &f64, "64-bit float")
cli.Bool("verbose", "v", &verbose, "Boolean flag")
cli.Rune("char", "c", &char, "Single character")
Slices
cli.StringSlice("origins", "o", &origins, "Allowed origins")
cli.IntSlice("ports", "p", &ports, "Port numbers")
Time & Network
cli.Duration("timeout", "t", &duration, "Duration (e.g. 5s, 2m)")
cli.Time("start", "s", &start, "Timestamp")
cli.IP("address", "a", &ip, "IP address")
cli.MAC("mac", "m", &mac, "MAC address")
cli.URL("endpoint", "e", &url, "URL")
cli.HostPortPair("listen", "l", &hostport, "Host:Port pair")
System & Filesystem
cli.Email("contact", "c", &email, "Email address")
cli.UUID("id", "i", &uuid, "UUID")
cli.FilePath("input", "f", &file, "Input file path (must exist)")
cli.DirPath("output", "d", &dir, "Output directory path (must exist)")

API Reference

CLI Struct Methods
  • New(name, description string) *CLI Initializes a new CLI instance. Registers a default completion subcommand for auto-generating bash and zsh scripts.
  • Parse(argv []string) (*SubCMD, error) Tokenizes arguments, processes validation/constraints, and returns the deepest matching subcommand leaf.
  • ParseAndInvoke(argv []string, userdata any, preInvokeCallback func(cmd *SubCMD, userdata any)) error Parses command arguments and immediately runs the matched handler, forwarding the user data pointer and invoking the optional pre-execute callback.
  • SubCommand(name, description string, handler func(any) error) *SubCMD Registers a top-level subcommand.
  • ExclusiveFlags(names ...string) *CLI Defines mutually exclusive flag sets at the global/root level.
  • PrintUsage(w io.Writer) Outputs the usage layout including global flags and all top-level subcommands.
  • Args() []string Retrieves root positional arguments.
SubCMD Struct Methods
  • SubCommand(name, description string, handler func(any) error) *SubCMD Registers a nested subcommand under this node.
  • Flag(ft flagType, name, shortName string, valuePtr any, usage string) *SubCMD Attaches a typed subcommand flag.
  • PersistentFlag(ft flagType, name, shortName string, valuePtr any, usage string) *SubCMD Attaches an inherited typed subcommand flag.
  • Required() *SubCMD Marks the most recently appended flag as required.
  • Validate(validators ...FlagValidator) *SubCMD Attaches validation logic to the last added flag.
  • ExclusiveFlags(names ...string) *SubCMD Declares mutually exclusive flags on this subcommand.
  • Args() []string Retrieves positional arguments gathered at this subcommand's scope.
  • Name() string Returns the subcommand name.
  • PrintUsage(w io.Writer) Outputs subcommand details, flags, persistent flags, and inherited options.

License

MIT License

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

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

func Max[T cmp.Ordered](maxValue T) func(v any) error

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

func MaxStringLen(length int) func(v any) error

MaxStringLen returns a validator function that checks if the provided string value has a maximum length.

func Min added in v0.1.5

func Min[T cmp.Ordered](minValue T) func(v any) error

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

func MinStringLen(length int) func(v any) error

MinStringLen returns a validator function that checks if the provided string value has a minimum length.

func NotEmpty added in v0.4.0

func NotEmpty(v any) error

NotEmpty returns a validator function that checks if the provided string value is not empty.

func ParseBool

func ParseBool(value string) (bool, error)

ParseBool parses a string to a bool.

func ParseDirPath

func ParseDirPath(value string) (string, error)

ParseDirPath resolves absolute directory path and checks that it exists.

func ParseDuration

func ParseDuration(value string) (time.Duration, error)

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

func ParseEmail(value string) (string, error)

ParseEmail parses a string to an email address using mail.ParseAddress.

func ParseFilePath

func ParseFilePath(value string) (string, error)

ParseFilePath resolves absolute file path and checks that it exists.

func ParseFloat32

func ParseFloat32(value string) (float32, error)

ParseFloat32 parses a string to a float32.

func ParseFloat64

func ParseFloat64(value string) (float64, error)

ParseFloat64 parses a string to a float64.

func ParseHostPort

func ParseHostPort(value string) (string, error)

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 ParseIP

func ParseIP(value string) (net.IP, error)

ParseIP parses a string to a net.IP using net.ParseIP.

func ParseInt

func ParseInt(value string) (int, error)

ParseInt parses a string to an int.

func ParseInt64

func ParseInt64(value string) (int64, error)

ParseInt64 parses a string to an int64.

func ParseIntSlice

func ParseIntSlice(value string) ([]int, error)

ParseIntSlice parses a comma-separated string into a slice of ints.

func ParseMAC

func ParseMAC(value string) (net.HardwareAddr, error)

func ParseRune

func ParseRune(value string) (rune, error)

ParseRune parses a string to a rune.

func ParseStringSlice

func ParseStringSlice(value string) ([]string, error)

ParseStringSlice parses a comma-separated string into a slice of strings.

func ParseTime

func ParseTime(value string) (time.Time, error)

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"

func ParseUUID

func ParseUUID(value string) (uuid.UUID, error)

ParseUUID parses a string to a uuid.UUID using the github.com/google/uuid package.

func ParseUrl

func ParseUrl(value string) (*url.URL, error)

ParseUrl parses a string to a url.URL using url.ParseRequestURI.

func Range added in v0.1.5

func Range[T cmp.Ordered](minValue, maxValue T) func(v any) error

Range returns a validator function that checks if the provided value is within the specified range (inclusive).

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

func New(name, description string) *CLI

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

func (c *CLI) Args() []string

Args returns the positional arguments collected at the root level during the most recent Parse call.

func (*CLI) Bool added in v0.2.0

func (c *CLI) Bool(name, shortName string, valuePtr *bool, usage string) *Flag

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

func (c *CLI) DirPath(name, shortName string, valuePtr *string, usage string) *Flag

DirPath adds a directory path flag to the CLI. The directory must exist at parse time.

func (*CLI) Duration added in v0.2.0

func (c *CLI) Duration(name, shortName string, valuePtr *time.Duration, usage string) *Flag

Duration adds a time.Duration flag to the CLI. Accepts duration strings such as "5s", "2m30s", "1h".

func (*CLI) Email added in v0.2.0

func (c *CLI) Email(name, shortName string, valuePtr *string, usage string) *Flag

Email adds an email address flag to the CLI.

func (*CLI) ExclusiveFlags added in v0.6.0

func (c *CLI) ExclusiveFlags(names ...string) *CLI

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

func (c *CLI) FilePath(name, shortName string, valuePtr *string, usage string) *Flag

FilePath adds a file path flag to the CLI. The file must exist at parse time.

func (*CLI) Float32 added in v0.2.0

func (c *CLI) Float32(name, shortName string, valuePtr *float32, usage string) *Flag

Float32 adds a 32-bit floating-point flag to the CLI.

func (*CLI) Float64 added in v0.2.0

func (c *CLI) Float64(name, shortName string, valuePtr *float64, usage string) *Flag

Float64 adds a 64-bit floating-point flag to the CLI.

func (*CLI) GenBashCompletion added in v0.2.0

func (c *CLI) GenBashCompletion(w io.Writer)

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

func (c *CLI) GenZshCompletion(w io.Writer)

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

func (c *CLI) HostPortPair(name, shortName string, valuePtr *string, usage string) *Flag

HostPortPair adds a host:port flag to the CLI (e.g. "localhost:8080").

func (*CLI) IP added in v0.2.0

func (c *CLI) IP(name, shortName string, valuePtr *net.IP, usage string) *Flag

IP adds an IP address flag to the CLI. Accepts both IPv4 and IPv6.

func (*CLI) InstallCompletion added in v0.2.0

func (c *CLI) InstallCompletion(shell string) error

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) Int added in v0.2.0

func (c *CLI) Int(name, shortName string, valuePtr *int, usage string) *Flag

Int adds an integer flag to the CLI.

func (*CLI) Int64 added in v0.2.0

func (c *CLI) Int64(name, shortName string, valuePtr *int64, usage string) *Flag

Int64 adds a 64-bit integer flag to the CLI.

func (*CLI) IntSlice added in v0.2.0

func (c *CLI) IntSlice(name, shortName string, valuePtr *[]int, usage string) *Flag

IntSlice adds a comma-separated integer slice flag to the CLI.

func (*CLI) MAC added in v0.2.0

func (c *CLI) MAC(name, shortName string, valuePtr *net.HardwareAddr, usage string) *Flag

MAC adds a hardware (MAC) address flag to the CLI.

func (*CLI) Parse added in v0.2.0

func (c *CLI) Parse(argv []string) (*SubCMD, error)

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

func (c *CLI) PrintUsage(w io.Writer)

PrintUsage writes the full usage message (global flags + subcommand list) to w.

func (*CLI) Rune added in v0.2.0

func (c *CLI) Rune(name, shortName string, valuePtr *rune, usage string) *Flag

Rune adds a single Unicode character flag to the CLI.

func (*CLI) String added in v0.2.0

func (c *CLI) String(name, shortName string, valuePtr *string, usage string) *Flag

String adds a string flag to the CLI.

func (*CLI) StringSlice added in v0.2.0

func (c *CLI) StringSlice(name, shortName string, valuePtr *[]string, usage string) *Flag

StringSlice adds a comma-separated string slice flag to the CLI.

func (*CLI) SubCommand added in v0.2.0

func (c *CLI) SubCommand(name, description string, handler func(userdata any) error) *SubCMD

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) Time added in v0.2.0

func (c *CLI) Time(name, shortName string, valuePtr *time.Time, usage string) *Flag

Time adds a time.Time flag to the CLI.

func (*CLI) URL added in v0.2.0

func (c *CLI) URL(name, shortName string, valuePtr *url.URL, usage string) *Flag

URL adds a URL flag to the CLI, validated via url.ParseRequestURI.

func (*CLI) UUID added in v0.2.0

func (c *CLI) UUID(name, shortName string, valuePtr *uuid.UUID, usage string) *Flag

UUID adds a UUID flag to the CLI.

func (*CLI) UninstallCompletion added in v0.2.0

func (c *CLI) UninstallCompletion(shell string) error

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

func (flag *Flag) Required() *Flag

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

type FlagValidator func(value any) error

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

func (cmd *SubCMD) Args() []string

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) Bool added in v0.4.0

func (cmd *SubCMD) Bool(name, shortName string, valuePtr *bool, usage string) *SubCMD

Bool adds a boolean flag to the subcommand.

func (*SubCMD) DirPath added in v0.4.0

func (cmd *SubCMD) DirPath(name, shortName string, valuePtr *string, usage string) *SubCMD

DirPath adds a directory path flag to the subcommand.

func (*SubCMD) Duration added in v0.4.0

func (cmd *SubCMD) Duration(name, shortName string, valuePtr *time.Duration, usage string) *SubCMD

Duration adds a time.Duration flag to the subcommand.

func (*SubCMD) Email added in v0.4.0

func (cmd *SubCMD) Email(name, shortName string, valuePtr *string, usage string) *SubCMD

Email adds an email address flag to the subcommand.

func (*SubCMD) ExclusiveFlags added in v0.6.0

func (cmd *SubCMD) ExclusiveFlags(names ...string) *SubCMD

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) FilePath added in v0.4.0

func (cmd *SubCMD) FilePath(name, shortName string, valuePtr *string, usage string) *SubCMD

FilePath adds a file path flag to the subcommand.

func (*SubCMD) Flag added in v0.4.0

func (cmd *SubCMD) Flag(ft flagType, name, shortName string, valuePtr any, usage string) *SubCMD

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

func (cmd *SubCMD) Float32(name, shortName string, valuePtr *float32, usage string) *SubCMD

Float32 adds a 32-bit floating-point flag to the subcommand.

func (*SubCMD) Float64 added in v0.4.0

func (cmd *SubCMD) Float64(name, shortName string, valuePtr *float64, usage string) *SubCMD

Float64 adds a 64-bit floating-point flag to the subcommand.

func (*SubCMD) HostPortPair added in v0.4.0

func (cmd *SubCMD) HostPortPair(name, shortName string, valuePtr *string, usage string) *SubCMD

HostPortPair adds a host:port flag to the subcommand.

func (*SubCMD) IP added in v0.4.0

func (cmd *SubCMD) IP(name, shortName string, valuePtr *net.IP, usage string) *SubCMD

IP adds an IP address flag to the subcommand. Previously registered with flagFloat32 by mistake — fixed.

func (*SubCMD) Int added in v0.4.0

func (cmd *SubCMD) Int(name, shortName string, valuePtr *int, usage string) *SubCMD

Int adds an integer flag to the subcommand.

func (*SubCMD) Int64 added in v0.4.0

func (cmd *SubCMD) Int64(name, shortName string, valuePtr *int64, usage string) *SubCMD

Int64 adds a 64-bit integer flag to the subcommand.

func (*SubCMD) IntSlice added in v0.4.0

func (cmd *SubCMD) IntSlice(name, shortName string, valuePtr *[]int, usage string) *SubCMD

IntSlice adds a comma-separated integer slice flag to the subcommand.

func (*SubCMD) MAC added in v0.4.0

func (cmd *SubCMD) MAC(name, shortName string, valuePtr *net.HardwareAddr, usage string) *SubCMD

MAC adds a hardware (MAC) address flag to the subcommand.

func (*SubCMD) Name added in v0.4.0

func (cmd *SubCMD) Name() string

Name returns the name of the subcommand.

func (*SubCMD) PersistentBool added in v0.6.0

func (cmd *SubCMD) PersistentBool(name, shortName string, valuePtr *bool, usage string) *SubCMD

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

func (cmd *SubCMD) PersistentEmail(name, shortName string, valuePtr *string, usage string) *SubCMD

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

func (cmd *SubCMD) PersistentIP(name, shortName string, valuePtr *net.IP, usage string) *SubCMD

PersistentIP adds a persistent IP address flag to the subcommand.

func (*SubCMD) PersistentInt added in v0.6.0

func (cmd *SubCMD) PersistentInt(name, shortName string, valuePtr *int, usage string) *SubCMD

PersistentInt adds a persistent integer flag to the subcommand.

func (*SubCMD) PersistentInt64 added in v0.6.0

func (cmd *SubCMD) PersistentInt64(name, shortName string, valuePtr *int64, usage string) *SubCMD

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

func (cmd *SubCMD) PersistentRune(name, shortName string, valuePtr *rune, usage string) *SubCMD

PersistentRune adds a persistent rune flag to the subcommand.

func (*SubCMD) PersistentString added in v0.6.0

func (cmd *SubCMD) PersistentString(name, shortName string, valuePtr *string, usage string) *SubCMD

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

func (cmd *SubCMD) PersistentURL(name, shortName string, valuePtr *url.URL, usage string) *SubCMD

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

func (cmd *SubCMD) PrintUsage(w io.Writer)

PrintUsage writes usage information for this subcommand to w.

func (*SubCMD) Required added in v0.4.0

func (cmd *SubCMD) Required() *SubCMD

Required marks the most recently added flag (own or persistent) as required.

func (*SubCMD) Rune added in v0.4.0

func (cmd *SubCMD) Rune(name, shortName string, valuePtr *rune, usage string) *SubCMD

Rune adds a single Unicode character flag to the subcommand.

func (*SubCMD) String added in v0.4.0

func (cmd *SubCMD) String(name, shortName string, valuePtr *string, usage string) *SubCMD

String adds a string flag to the subcommand.

func (*SubCMD) StringSlice added in v0.4.0

func (cmd *SubCMD) StringSlice(name, shortName string, valuePtr *[]string, usage string) *SubCMD

StringSlice adds a comma-separated string slice flag to the subcommand.

func (*SubCMD) SubCommand added in v0.6.0

func (cmd *SubCMD) SubCommand(name, description string, handler func(userdata any) error) *SubCMD

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) Time added in v0.4.0

func (cmd *SubCMD) Time(name, shortName string, valuePtr *time.Time, usage string) *SubCMD

Time adds a time.Time flag to the subcommand.

func (*SubCMD) URL added in v0.4.0

func (cmd *SubCMD) URL(name, shortName string, valuePtr *url.URL, usage string) *SubCMD

URL adds a URL flag to the subcommand.

func (*SubCMD) UUID added in v0.4.0

func (cmd *SubCMD) UUID(name, shortName string, valuePtr *uuid.UUID, usage string) *SubCMD

UUID adds a UUID flag to the subcommand.

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

Directories

Path Synopsis
cmd
example command

Jump to

Keyboard shortcuts

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