optargs

package module
v0.3.3 Latest Latest
Warning

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

Go to latest
Published: Apr 1, 2026 License: MIT Imports: 11 Imported by: 1

README

OptArgs

Build Coverage Go Reference

A Go implementation of POSIX getopt(3), GNU getopt_long(3), and getopt_long_only(3) with native subcommand support.

OptArgs Core is the foundation for higher-level wrapper interfaces (goarg, pflags).

Features

  • Full POSIX getopt(3) compliance: short options, compaction, -- termination, POSIXLY_CORRECT
  • GNU getopt_long(3): --option=value, --option value, partial matching, case-insensitive
  • GNU getopt_long_only(3): single-dash long options with short option fallback
  • Advanced handling: -W extension, option redefinition, negative arguments
  • Native subcommand dispatch via AddCmd() with option inheritance through the parent chain
  • Iterator-based processing (Options() returns iter.Seq2[Option, error])
  • Verbose and silent error modes, both working through subcommand chains
  • Zero dependencies

Install

go get github.com/major0/optargs

Requires Go 1.23+.

Usage

GetOpt (POSIX short options)
package main

import (
    "fmt"
    "github.com/major0/optargs"
)

func main() {
    p, _ := optargs.GetOpt(os.Args[1:], "vf:o::")
    for opt, err := range p.Options() {
        if err != nil {
            fmt.Fprintf(os.Stderr, "%v\n", err)
            continue
        }
        switch opt.Name {
        case "v":
            fmt.Println("verbose")
        case "f":
            fmt.Println("file:", opt.Arg)
        case "o":
            fmt.Println("output:", opt.Arg)
        }
    }
}
GetOptLong (GNU long options)
p, _ := optargs.GetOptLong(os.Args[1:], "vf:", []optargs.Flag{
    {Name: "verbose", HasArg: optargs.NoArgument},
    {Name: "file",    HasArg: optargs.RequiredArgument},
    {Name: "output",  HasArg: optargs.OptionalArgument},
})
for opt, err := range p.Options() {
    // ...
}
GetOptLongOnly (single-dash long options)
p, _ := optargs.GetOptLongOnly(os.Args[1:], "vf:", []optargs.Flag{
    {Name: "verbose", HasArg: optargs.NoArgument},
    {Name: "file",    HasArg: optargs.RequiredArgument},
})
// -verbose tries long match first, falls back to short options via optstring
Subcommands
root, _ := optargs.GetOptLong(os.Args[1:], "v", []optargs.Flag{
    {Name: "verbose", HasArg: optargs.NoArgument},
})

serve, _ := optargs.GetOptLong([]string{}, "p:", []optargs.Flag{
    {Name: "port", HasArg: optargs.RequiredArgument},
})
root.AddCmd("serve", serve)

// Root iteration dispatches to child when "serve" is encountered.
// Child inherits parent options via parent-chain walk.
for opt, err := range root.Options() { /* root options */ }
for opt, err := range serve.Options() { /* serve options + inherited */ }
Strict Subcommands

By default, child parsers inherit parent options — unknown options in a subcommand are resolved by walking the parent chain. To disable this (POSIX-strict behavior where each command owns its own options):

root.SetStrictSubcommands(true)
root.AddCmd("serve", serve) // serve will NOT inherit root's options

This is automatically enabled when POSIXLY_CORRECT is set or when the optstring starts with +.

Optstring Syntax

Prefix Behavior
: Silent error mode — suppress error logging
+ POSIXLY_CORRECT — stop at first non-option
- Treat non-options as argument to option \x01
Suffix Meaning
f No argument
f: Required argument
f:: Optional argument
W; GNU -W word extension

Examples

  • example/ — vanilla GetOpt, GetOptLong, GetOptLongOnly usage
  • posix/ — obscure POSIX/GNU patterns: subcommand dispatch, silent error mode, POSIXLY_CORRECT

Wrapper Modules

Module Description
goarg Struct-tag based argument parsing (alexflint/go-arg compatible)
pflags Flag-method based parsing (spf13/pflag compatible)

Contributing

See CONTRIBUTING.md.

License

MIT

Documentation

Overview

Package optargs provides a collection of CLI parsing utilities in order to aid in the development of command line applications.

POSIX/GNU GetOpt

At the heart of the optargs package is a Go implementation of the GNU glibc versions the getopt(3), getopt_long(3), and getopt_long_only(3) functions.

Leveraging GNU/POSIX conventions as the backend parser option means that the parser has a very large degree of flexibility without restricting application design choices.

For example, POSIX/GNU allows for the following:

  • short-only options.
  • long-only options.
  • long and short options that do not require a value. I.e. it should be possible to pass `--foo` and specify that it never takes a value, and any attempt to pass it a value should be ignored or or result in an error.
  • short-options of any character that is a valid `isgraph()` character; with the exception of `-`, `:` and `;`. This means that the following options are valid: -=, -+, -{, -}, -^, -!, -@, etc.
  • short-option compaction: `-abc` is the equivalent of `-a -b -c`
  • short-option compaction with optional args: `-abarg` is the equivalent of `-a -b arg`
  • arguments to short options that begin with `-`: `-a -1` should pass `-1` as an argument to `-a`
  • long-arguments that include any `isgraph()` character in the name, this includes allowing `=` in the name of the argument. For example, `--foo=bar=boo` should map `foo=bar` as the Flag, and `boo` as the value to the flag. This potentially also allows for curious long-arg syntax such as: `--command:arg=value`.
  • many-to-one flag mappings. For example, the GNU `ls` command supports `--format=<format>` where each possible `<format>` options is also supported by a unique short-option. For example: `--format=across` = `-x`, `--format=commas` = `-m`, `--format=horizontal` = `-x`, `--format=long` = `-l`, etc.
  • The GNU `-W` flag which allows short-options to behave like an undefined long-option. E.g. `-W foo` should be interpreted as if `--foo` was passed to the application.
  • long-options that may look similar, but behave differently, from short options. E.g. `-c` and `--c` are allowed to behave differently.
  • short-option toggles. Because any `isgraph()` character is a valid short option, `-a` and `-A` can be distinct options that toggle the same field via their respective [Flag.Handle] callbacks. The parser processes options left-to-right, so the last occurrence wins naturally. This is required for tools that pull options from the environment and allow CLI overrides — contradictory sequences like `-aAaAa` must be handled correctly, with the final `-a` or `-A` determining the result.
  • multiple short-options that perform the same action. Useful for deprecating a short option while still supporting it: both `-s` (deprecated) and `-S` (current) can map to the same [Flag.Handle] callback. The wrapper controls which options appear in `--help` output, so deprecated aliases can be hidden without removing functionality.
  • left-to-right, last-occurrence-wins processing. The iterator yields each option in the order it appears on the command line. When the same option or contradictory options appear multiple times, the handler or application overwrites the value on each encounter. The parser does not accumulate, deduplicate, or reject repeated options — that policy belongs to the handler layer.

It is always possible to implement a Flag handler which imposes opinionated rules atop a non-opinionated parser, but it is not possible to write a less opinionated Flag handler atop an opinionated parser. To that end, the [optarg] parsers do not make any judgements outside of strictly adhering to the POSIX/GNU conventions. Applications are free to implement their own argument handler to best-fit their application's needs.

Flags()

Optargs supports traditional Go style flags which act as convenience methods around GetOpt, GetOptLong, and GetOptLongOnly with the aim of fully supporting drop-in replacements commonly used CLI tooling, such as:

While these packages are quite useful, they have some fundamental limitations and quirks that come from their design choices which aim to be overcome by optargs and in the case of spf13/pflag, those quirks ultimately percolate up to the user, such as spf13/pflag's boolean flags. Or putting arbitrary restrictions on applications, such as supporting long-only options, but not allowing short-only options. Or not supporting true non-option flags. I.e. many (all?) of the existing Go flag packages only allow an argument to a flag to be optional or required and are not capable of handling flags that never require an argument.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Convert added in v0.3.0

func Convert(value string, targetType reflect.Type) (interface{}, error)

Convert converts a string value to the specified Go type. Supports: string, bool, all int/uint/float sizes, pointer types, slice types, and types implementing encoding.TextUnmarshaler. Bool parsing accepts: true/t/1/yes/y/on and false/f/0/no/n/off (case-insensitive), matching alexflint/go-arg behavior.

func ConvertSlice added in v0.3.0

func ConvertSlice(csv string, sliceType reflect.Type) (interface{}, error)

ConvertSlice converts a comma-separated string to a slice of the specified element type. Used for default value processing. Splits by comma, trims whitespace on each element, skips empty elements after trimming. Returns empty slice for empty input.

func SetDebug added in v0.3.0

func SetDebug(enabled bool)

SetDebug enables or disables verbose debug logging in the parser.

Types

type ArgType

type ArgType int

ArgType specifies whether a flag takes no argument, a required argument, or an optional argument.

const (
	// NoArgument indicates the flag takes no argument.
	NoArgument ArgType = iota
	// RequiredArgument indicates the flag requires an argument.
	RequiredArgument
	// OptionalArgument indicates the flag accepts an optional argument.
	OptionalArgument
)

type BoolArgValuer added in v0.3.3

type BoolArgValuer interface {
	BoolTakesArg() bool
}

BoolArgValuer optionally declares whether a bool-like flag accepts an optional =value argument (e.g., --flag=true). When not implemented, wrappers default to accepting an optional argument for backward compatibility. Types that are strictly no-argument (like Count) return false.

type BoolValuer added in v0.3.2

type BoolValuer interface {
	IsBoolFlag() bool
}

BoolValuer marks a TypedValue as boolean — no argument required. Wrappers check this to determine NoArgument vs OptionalArgument for the parser.

type CommandRegistry

type CommandRegistry map[string]*Parser

CommandRegistry manages subcommands for a parser using a simple map

func NewCommandRegistry

func NewCommandRegistry() CommandRegistry

NewCommandRegistry creates a new command registry

func (CommandRegistry) AddAlias

func (cr CommandRegistry) AddAlias(alias, existingCommand string) error

AddAlias creates an alias for an existing command

func (CommandRegistry) AddCmd

func (cr CommandRegistry) AddCmd(name string, parser *Parser) *Parser

AddCmd registers a new subcommand with the parser Returns the registered parser for chaining

func (CommandRegistry) ExecuteCommand

func (cr CommandRegistry) ExecuteCommand(name string, args []string) (*Parser, error)

ExecuteCommand finds and prepares a command for execution.

func (CommandRegistry) GetAliases

func (cr CommandRegistry) GetAliases(targetParser *Parser) []string

GetAliases returns all aliases for a given parser

func (CommandRegistry) GetCommand

func (cr CommandRegistry) GetCommand(name string) (*Parser, bool)

GetCommand retrieves a parser by command name (exact match).

func (CommandRegistry) ListCommands

func (cr CommandRegistry) ListCommands() map[string]*Parser

ListCommands returns all command mappings

type Flag

type Flag struct {
	Name   string
	HasArg ArgType
	Handle func(name string, arg string) error

	// Metadata for help generation — set at registration time
	Help         string // human-readable help text
	ArgName      string // placeholder name (e.g., "FILE", "COUNT")
	DefaultValue string // display representation of default
	Peer         *Flag  // bidirectional short↔long link
}

Flag describes a single option definition for long option parsing. Name is the option name (without leading dashes) and HasArg specifies the argument requirement. Handle, when non-nil, is invoked instead of yielding an Option through the iterator.

type Option

type Option struct {
	Name   string
	HasArg bool
	Arg    string
}

Option represents a parsed option yielded by the iterator. Name is the option name, HasArg indicates whether an argument was consumed, and Arg holds the argument value if present.

type ParseMode

type ParseMode int

ParseMode controls how non-option arguments are handled during parsing.

const (
	// ParseDefault permutes arguments so that non-options are moved to the end.
	ParseDefault ParseMode = iota
	// ParseNonOpts treats each non-option argument as an argument to a
	// synthetic option with character code 1.
	ParseNonOpts
	// ParsePosixlyCorrect stops option processing at the first non-option argument.
	ParsePosixlyCorrect
)

type Parser

type Parser struct {
	Args []string

	// Command support - simple map of command name to parser
	Commands CommandRegistry

	// Metadata for help generation
	Name        string // command/subcommand name
	Description string // command/subcommand description
	// contains filtered or unexported fields
}

Parser is the core argument parser. It processes command-line arguments according to POSIX getopt(3) and GNU getopt_long(3) conventions.

Args holds the remaining unprocessed arguments. After iteration completes, Args contains non-option arguments (and any arguments after "--").

Commands holds registered subcommands. Use Parser.AddCmd to register subcommands; do not manipulate Commands directly.

func GetOpt

func GetOpt(args []string, optstring string) (*Parser, error)

GetOpt creates a parser implementing POSIX getopt(3) behavior. It parses args according to the optstring specification.

func GetOptLong

func GetOptLong(args []string, optstring string, longopts []Flag) (*Parser, error)

GetOptLong creates a parser implementing GNU getopt_long(3) behavior. It supports both short options via optstring and long options via longopts.

func GetOptLongOnly

func GetOptLongOnly(args []string, optstring string, longopts []Flag) (*Parser, error)

GetOptLongOnly creates a parser implementing GNU getopt_long_only(3) behavior. Single-dash options are first tried as long options; on failure, the parser falls back to short option parsing via the optstring.

func NewParser

func NewParser(config ParserConfig, shortOpts map[byte]*Flag, longOpts map[string]*Flag, args []string) (*Parser, error)

NewParser creates a Parser from pre-built configuration, short option map, long option map, and argument list. Most callers should use GetOpt, GetOptLong, or GetOptLongOnly instead.

Flag structs in shortOpts and longOpts may include a non-nil Handle field for per-option handler dispatch. When a flag with a non-nil Handle is resolved during parsing, the handler is invoked instead of yielding an Option through the iterator. This is the construction-time path for attaching handlers:

verbose := &optargs.Flag{Name: "verbose", HasArg: optargs.NoArgument}
debug := &optargs.Flag{
	Name:   "debug",
	HasArg: optargs.NoArgument,
	Handle: func(name, arg string) error {
		log.Println("debug mode enabled")
		return nil
	},
}
p, err := optargs.NewParser(config,
	map[byte]*optargs.Flag{'v': verbose, 'd': debug},
	map[string]*optargs.Flag{"verbose": verbose, "debug": debug},
	os.Args[1:],
)

For parsers created via GetOpt, GetOptLong, or GetOptLongOnly, handlers can be attached after construction using Parser.SetHandler, Parser.SetShortHandler, or Parser.SetLongHandler. The two paths are complementary: NewParser for construction-time setup, SetHandler variants for post-construction attachment.

func NewParserWithCaseInsensitiveCommands

func NewParserWithCaseInsensitiveCommands(shortOpts map[byte]*Flag, longOpts map[string]*Flag, args []string) (*Parser, error)

NewParserWithCaseInsensitiveCommands creates a new parser with case insensitive command matching enabled

func (*Parser) ActiveCommand added in v0.3.0

func (p *Parser) ActiveCommand() (name string, parser *Parser)

ActiveCommand returns the name and parser of the subcommand that was dispatched during parsing. If no subcommand was dispatched, name is empty and parser is nil. For nested subcommands, returns the immediate child — callers walk the chain by calling ActiveCommand on the returned parser.

func (*Parser) AddAlias

func (p *Parser) AddAlias(alias, existingCommand string) error

AddAlias creates an alias for an existing command

func (*Parser) AddCmd

func (p *Parser) AddCmd(name string, parser *Parser) *Parser

AddCmd registers a new subcommand with this parser.

func (*Parser) ExecuteCommand

func (p *Parser) ExecuteCommand(name string, args []string) (*Parser, error)

ExecuteCommand finds and executes a command

func (*Parser) GetAliases

func (p *Parser) GetAliases(targetParser *Parser) []string

GetAliases returns all aliases for a given parser

func (*Parser) GetCommand

func (p *Parser) GetCommand(name string) (*Parser, bool)

GetCommand retrieves a parser by command name

func (*Parser) ListCommands

func (p *Parser) ListCommands() map[string]*Parser

ListCommands returns all command mappings

func (*Parser) Options

func (p *Parser) Options() iter.Seq2[Option, error]

Options returns an iterator over parsed options. Each iteration yields an Option and an error. When a subcommand is encountered, the iterator dispatches to the child parser automatically.

func (*Parser) SetHandler added in v0.2.0

func (p *Parser) SetHandler(name string, handler func(string, string) error) error

SetHandler is a convenience method that attaches a handler to a matching option using command-line prefix syntax. Pass "--name" for long options or "-c" for short options. Returns an error if the prefix is missing or no matching option is found.

Examples:

parser.SetHandler("--verbose", handler)  // calls SetLongHandler("verbose", handler)
parser.SetHandler("-v", handler)          // calls SetShortHandler('v', handler)
parser.SetHandler("--v", handler)         // calls SetLongHandler("v", handler)

SetHandler only modifies options on this parser — it does not walk the parent chain.

func (*Parser) SetLongHandler added in v0.2.0

func (p *Parser) SetLongHandler(name string, handler func(string, string) error) error

SetLongHandler attaches a handler to a long option registered on this parser. Returns an error if no matching long option is found.

Long option names may be single characters (e.g., "v" for --v). Use SetLongHandler for long options and SetShortHandler for short options — the two namespaces are independent.

SetLongHandler only modifies options on this parser — it does not walk the parent chain.

func (*Parser) SetShortHandler added in v0.2.0

func (p *Parser) SetShortHandler(c byte, handler func(string, string) error) error

SetShortHandler attaches a handler to a short option registered on this parser. Returns an error if no matching short option is found.

SetShortHandler only modifies options on this parser — it does not walk the parent chain.

func (*Parser) SetStrictSubcommands added in v0.3.0

func (p *Parser) SetStrictSubcommands(strict bool)

SetStrictSubcommands enables or disables strict subcommand mode. When enabled, child parsers registered via AddCmd do not inherit parent options — unknown options in a subcommand produce an error instead of walking the parent chain.

func (*Parser) StrictSubcommands added in v0.3.0

func (p *Parser) StrictSubcommands() bool

StrictSubcommands reports whether strict subcommand mode is enabled.

type ParserConfig

type ParserConfig struct {
	// contains filtered or unexported fields
}

ParserConfig holds configuration for a Parser instance. All fields are unexported; configuration is set via optstring prefix flags and constructor parameters, or via setter methods.

func (*ParserConfig) Interspersed added in v0.3.2

func (c *ParserConfig) Interspersed() bool

Interspersed returns whether interspersed option/non-option args are allowed.

func (*ParserConfig) LongOnly added in v0.3.1

func (c *ParserConfig) LongOnly() bool

LongOnly returns whether getopt_long_only(3) mode is enabled.

func (*ParserConfig) SetInterspersed added in v0.3.2

func (c *ParserConfig) SetInterspersed(interspersed bool)

SetInterspersed controls whether non-option arguments can appear between options. When false, option processing stops at the first non-option argument (POSIX behavior). Default is true (GNU behavior).

func (*ParserConfig) SetLongOnly added in v0.3.1

func (c *ParserConfig) SetLongOnly(enabled bool)

SetLongOnly enables or disables getopt_long_only(3) behavior. When enabled, single-dash arguments (e.g., -verbose) are first tried as long options; on failure, the parser falls back to short option parsing.

type TypedValue added in v0.3.2

type TypedValue interface {
	// Set parses the string into the typed value.
	Set(string) error

	// String formats the current value as a string.
	String() string

	// Type returns the type name for help text (e.g., "int", "bool", "duration").
	Type() string
}

TypedValue is the core interface for typed flag values. It is a superset of pflags' Value interface — any TypedValue can be used where a pflags Value is expected.

func NewBoolFuncValue added in v0.3.2

func NewBoolFuncValue(fn func(string) error) TypedValue

NewBoolFuncValue returns a TypedValue that calls fn on each Set() and implements BoolValuer so it works as a no-argument flag.

func NewBoolSliceValue added in v0.3.2

func NewBoolSliceValue(val []bool, p *[]bool) TypedValue

func NewBoolValue added in v0.3.2

func NewBoolValue(val bool, p *bool) TypedValue

func NewCountValue added in v0.3.2

func NewCountValue(val int, p *int) TypedValue

NewCountValue returns a TypedValue backed by *int that increments on each Set() call. Implements BoolValuer so it works as a no-argument flag (e.g., -vvv for verbosity 3).

func NewDurationSliceValue added in v0.3.2

func NewDurationSliceValue(val []time.Duration, p *[]time.Duration) TypedValue

func NewDurationValue added in v0.3.2

func NewDurationValue(val time.Duration, p *time.Duration) TypedValue

func NewFloat32SliceValue added in v0.3.2

func NewFloat32SliceValue(val []float32, p *[]float32) TypedValue

func NewFloat32Value added in v0.3.2

func NewFloat32Value(val float32, p *float32) TypedValue

func NewFloat64SliceValue added in v0.3.2

func NewFloat64SliceValue(val []float64, p *[]float64) TypedValue

func NewFloat64Value added in v0.3.2

func NewFloat64Value(val float64, p *float64) TypedValue

func NewFuncValue added in v0.3.2

func NewFuncValue(fn func(string) error) TypedValue

NewFuncValue returns a TypedValue that calls fn on each Set().

func NewInt8Value added in v0.3.2

func NewInt8Value(val int8, p *int8) TypedValue

func NewInt16Value added in v0.3.2

func NewInt16Value(val int16, p *int16) TypedValue

func NewInt32SliceValue added in v0.3.2

func NewInt32SliceValue(val []int32, p *[]int32) TypedValue

func NewInt32Value added in v0.3.2

func NewInt32Value(val int32, p *int32) TypedValue

func NewInt64SliceValue added in v0.3.2

func NewInt64SliceValue(val []int64, p *[]int64) TypedValue

func NewInt64Value added in v0.3.2

func NewInt64Value(val int64, p *int64) TypedValue

func NewIntSliceValue added in v0.3.2

func NewIntSliceValue(val []int, p *[]int) TypedValue

func NewIntValue added in v0.3.2

func NewIntValue(val int, p *int) TypedValue

func NewStringArrayValue added in v0.3.2

func NewStringArrayValue(val []string, p *[]string) TypedValue

NewStringArrayValue returns a TypedValue that appends each Set() call's raw string without splitting on commas. Distinct from StringSlice.

func NewStringSliceValue added in v0.3.2

func NewStringSliceValue(val []string, p *[]string) TypedValue

func NewStringToInt64Value added in v0.3.2

func NewStringToInt64Value(val map[string]int64, p *map[string]int64) TypedValue

func NewStringToIntValue added in v0.3.2

func NewStringToIntValue(val map[string]int, p *map[string]int) TypedValue

func NewStringToStringValue added in v0.3.2

func NewStringToStringValue(val map[string]string, p *map[string]string) TypedValue

func NewStringValue added in v0.3.2

func NewStringValue(val string, p *string) TypedValue

func NewTextValue added in v0.3.2

NewTextValue returns a TypedValue wrapping any encoding.TextUnmarshaler. If dest also implements encoding.TextMarshaler, String() uses MarshalText(). The val parameter provides the initial/display value via TextMarshaler.

func NewUint8Value added in v0.3.2

func NewUint8Value(val uint8, p *uint8) TypedValue

func NewUint16Value added in v0.3.2

func NewUint16Value(val uint16, p *uint16) TypedValue

func NewUint32Value added in v0.3.2

func NewUint32Value(val uint32, p *uint32) TypedValue

func NewUint64Value added in v0.3.2

func NewUint64Value(val uint64, p *uint64) TypedValue

func NewUintSliceValue added in v0.3.2

func NewUintSliceValue(val []uint, p *[]uint) TypedValue

func NewUintValue added in v0.3.2

func NewUintValue(val uint, p *uint) TypedValue

Directories

Path Synopsis
pflags module

Jump to

Keyboard shortcuts

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