flags

package module
v0.6.1 Latest Latest
Warning

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

Go to latest
Published: May 11, 2026 License: BSD-3-Clause Imports: 30 Imported by: 0

README

flags

flags

flags is a reflection-powered command-line parser for Go. It lets you describe a CLI with ordinary Go structs and tags, then handles parsing, help, completion, configuration, validation, localization, and generated documentation around that model.

It keeps the familiar struct-tag workflow, while adding stricter validation, better generated output, modern completion/docs tooling, and practical integration APIs.


Documentation Site · Go Reference

Why Use It

Use flags when you want a CLI that is defined close to the Go data it fills. The struct remains the public contract, and the parser can derive help, completion, config examples, and documentation from the same source.

Useful strengths:

  • short and long options with POSIX-style parsing;
  • commands, subcommands, option groups, and positional arguments;
  • typed values, defaults, slices, maps, counters, and custom parsers;
  • environment variables and INI configuration;
  • value validators for common string, path, and numeric constraints;
  • shell completion for bash, zsh, and PowerShell;
  • generated help, markdown, HTML, and manpage output;
  • opt-in localization for parser text and user-facing metadata;
  • runtime setters for generated or application-owned metadata.

Installation

go get github.com/woozymasta/flags

Minimal Example

package main

import (
  "errors"
  "fmt"
  "os"

  "github.com/woozymasta/flags"
)

type Options struct {
  Verbose bool   `short:"v" long:"verbose" description:"Show verbose output"`
  Name    string `short:"n" long:"name" required:"true" description:"User name"`
}

func main() {
  var opts Options

  parser := flags.NewParser(&opts, flags.Default)
  _, err := parser.Parse()
  if err != nil {
    var ferr *flags.Error
    if errors.As(err, &ferr) && ferr.Type == flags.ErrHelp {
      os.Exit(0)
    }
    os.Exit(1)
  }

  if opts.Verbose {
    fmt.Println("verbose mode enabled")
  }
  fmt.Printf("hello, %s\n", opts.Name)
}

Run it:

app --name Alice
app -v --name Alice
app --help

flags.Default enables the built-in help flag, parser error printing, and -- pass-through handling. For libraries and tests, use flags.Default &^ flags.PrintErrors so callers control output.

Commands

Commands are struct fields tagged with command. A command can own options, positional arguments, subcommands, and an Execute(args []string) error method.

type AddCommand struct {
  Name string `long:"name" required:"true"`
}

func (c *AddCommand) Execute(args []string) error {
  fmt.Println("add", c.Name)
  return nil
}

type Options struct {
  Add AddCommand `command:"add" description:"Add item"`
}

This gives a command shape like:

app add --name task

Configuration

Small tools often use tag defaults and environment variables:

type Options struct {
  Port  int    `long:"port" default:"8080" env:"APP_PORT"`
  Token string `long:"token" env:"APP_TOKEN" required:"true" secret:"true"`
}

Applications that load a config file before parsing CLI arguments can use flags.ConfiguredValues so prefilled struct values are kept and can satisfy required checks.

INI support is available when a simple generated or user-editable config file is useful:

ini := flags.NewIniParser(parser)
_ = ini.ParseFile("app.ini")

Help, Completion

The same parser model can render user-facing output:

parser.WriteHelp(os.Stdout)
_ = parser.WriteNamedCompletion(os.Stdout, flags.CompletionShellBash, "app")
_ = parser.WriteDoc(os.Stdout, flags.DocFormatMarkdown)

Documentation

Use the source documentation when working in the repository: docs/.
Use the published site for rendered guides and navigation: Documentation Site.
Use Go Reference for API documentation generated from Go symbols: Go Reference.

Documentation

Overview

Package flags provides a reflection-based command-line parser.

It is similar to Go's standard `flag` package, but adds richer modeling: long and short options, nested groups, subcommands, map and slice values, environment-variable defaults, INI integration, and shell completion.

Features

Core features:

  • Short options (for example, `-v`)
  • Long options (for example, `--verbose`)
  • Options with required, optional, or no arguments
  • Optional argument values (`--flag=value`) with fallback `optional-value`
  • Defaults from tags and environment variables (including slices and maps)
  • Grouped options and nested namespaces
  • Subcommands and command aliases
  • Help and man-page generation
  • `--` passthrough support (`PassDoubleDash`)
  • Optional unknown-flag ignoring
  • Combined short flags (for example, `-aux`)
  • Option argument forms such as `-I/usr/include`, `-I=/usr/include`, `-I /usr/include`
  • Repeated options (store in slices or use counter semantics)
  • Primitive scalar types, maps, and callback/function options

Windows-specific behavior:

  • Slash-prefixed options (`/v`, `/verbose`)
  • `:` delimiter for option arguments in Windows mode
  • Windows-style help rendering
  • `forceposix` build tag to disable Windows-style parsing

Quick Start

Minimal parse flow:

type Options struct {
	Verbose bool   `short:"v" long:"verbose" description:"Show verbose output"`
	Region  string `long:"region" default:"eu-west-1" description:"Cloud region"`
}

var opts Options
parser := NewParser(&opts, Default|HelpCommands)

_, err := parser.Parse()
if err != nil {
	var ferr *Error
	if errors.As(err, &ferr) && ferr.Type == ErrHelp {
		os.Exit(0)
	}
	os.Exit(1)
}

`HelpCommands` opt-in enables built-in commands: `help`, `version`, `completion`, `docs`, `config`.

For custom value conversion, implement Marshaler and Unmarshaler.

Struct Tags

An option field must define at least one of `short` or `long`.

General option tags:

  • `short`: single-character short option name
  • `long`: long option name
  • `required`: marks option as required; repeatable options support count ranges
  • `xor`: delimiter-separated exclusive option relation groups
  • `and`: delimiter-separated all-or-none option relation groups
  • `counter`: integer counter mode; each occurrence increments by 1
  • `validate-*`: post-parse value validators for strings, paths, and numbers
  • `description`: short help text
  • `long-description`: extended text (currently used in generated man pages)
  • `no-flag`: ignore field as command-line option
  • `hidden`: hide from help and man pages
  • `secret`: redact value in help, docs, completion, and error output
  • `deprecated`: mark option as deprecated with a replacement hint

Value and default tags:

  • `optional`: marks option argument as optional; must be passed as `--opt=value`
  • `optional-value`: value used when optional option appears without explicit argument
  • `order`: display/completion priority in group block sorting
  • `default`: default value (repeat for slice/map entries)
  • `defaults`: delimiter-separated default list (non-repeatable)
  • `default-mask`: display replacement for default in help; `-` hides default entirely
  • `env`: environment variable that overrides default value
  • `auto-env`: derive environment variable from `long` name when enabled
  • `env-delim`: split `env` value by delimiter for slice/map fields
  • `value-name`: placeholder name shown in help
  • `choice`: allowed value constraint (repeatable), for example `long:"animal" choices:"cat;dog"`
  • `choices`: delimiter-separated allowed values (non-repeatable)
  • `completion`: completion hint (`file`, `dir`, `none`) used when no custom completer or choices are defined
  • `base`: radix for integer parsing, default `10`
  • `key-value-delimiter`: delimiter used when parsing map values, default `:`
  • `unquote`: when set to `false`, disables automatic unquoting of argument values
  • `short-alias`: extra short option name (repeatable)
  • `short-aliases`: delimiter-separated short aliases (non-repeatable)
  • `long-alias`: extra long option name (repeatable)
  • `long-aliases`: delimiter-separated long aliases (non-repeatable)

INI tags:

  • `ini-name`: explicit INI key name
  • `no-ini`: ignore field for INI parsing/writing

Group and command tags:

  • `group`: treat struct field as a named option group
  • `namespace`: prefix long option names inside group hierarchy
  • `env-namespace`: prefix environment variable names inside group hierarchy
  • `command`: treat struct field as a command
  • `command-group`: display group for command help/docs
  • `subcommands-optional`: make subcommands under this command optional
  • `default-command`: activate this subcommand when no explicit command token is provided; only one subcommand per parent may carry this tag
  • `pass-after-non-option`: for this command, stop option parsing after the first non-option argument
  • `deprecated`: mark command as deprecated with a replacement hint
  • `alias`: extra command name (repeatable)
  • `aliases`: delimiter-separated command aliases (non-repeatable)
  • `positional-args`: map trailing positional arguments into struct fields
  • `io`: string I/O role (`in`, `out`) for options/positionals
  • `io-kind`: string I/O kind (`auto`, `stream`, `file`, `string`)
  • `io-stream`: stream token (`stdin`, `stdout`, `stderr`)
  • `io-open`: output file mode metadata (`truncate`, `append`)
  • `positional-arg-name`: placeholder label for positional help
  • `completion`: positional completion hint (`file`, `dir`, `none`)

Validation tags apply to option fields and positional argument fields:

  • `validate-existing-file`: path must exist and be a regular file
  • `validate-existing-dir`: path must exist and be a directory
  • `validate-readable`: path must be readable by the current process
  • `validate-writable`: path or parent directory must be writable
  • `validate-non-empty`: string must be non-empty after trimming
  • `validate-regex`: string must fully match the regular expression
  • `validate-min-len` / `validate-max-len`: string rune length bounds
  • `validate-min` / `validate-max`: numeric value bounds
  • `validate-path-abs`: path must be absolute

For `positional-args`, arguments are optional by default. Use `required` either on the positional struct field or on individual fields. Numeric `required` forms are supported for trailing positional slices and repeatable option fields. `required:"N"` means at least `N` values, and `required:"N-M"` means from `N` to `M` values. For positional args, `io:"in"`/`io:"out"` with `io-kind:"auto"` or `io-kind:"stream"` defaults omitted values to `stdin`/`stdout`. For options, no implicit fallback is applied when the flag is omitted. When `completion` is not set, `io-kind:"file"` and `io-kind:"auto"` imply file completion hints.

Error Handling

With Default parser options, PrintErrors is enabled and parse errors are printed by the parser. A typical pattern is:

_, err := parser.Parse()
if err != nil {
	var ferr *Error
	if errors.As(err, &ferr) && ferr.Type == ErrHelp {
		os.Exit(0)
	}
	os.Exit(1)
}

If you need full control over output formatting/routing, disable PrintErrors and print returned errors yourself.

Option Groups

Groups organize related options in help output and in parser structure. You can define groups in three ways:

  1. Create a parser with NewNamedParser.
  2. Add groups programmatically with [Parser.AddGroup].
  3. Add nested struct fields tagged with `group:"name"`.

For post-scan programmatic adjustments, implement Configurer on your options/group/command data type and mutate option metadata via parser APIs. Common runtime setters are available on Option (for example names, aliases, defaults, env bindings, choices, required/hidden flags, and order). Command/group/arg metadata can also be tuned at runtime via setters on Command, Group, and Arg.

Commands

Commands split CLI behavior into explicit actions (similar to `git add`, `git commit`, and so on). You can define commands in two ways:

  1. Add commands programmatically with [Parser.AddCommand].
  2. Add struct fields tagged with `command:"name"`.

If the selected command implements Commander, its `Execute` method runs after parsing with the remaining arguments.

By default only the selected leaf command executes. Enable CommandChain to execute every active command implementing Commander from parent to leaf. If a command returns an error, the chain stops and Parser.Parse returns that error.

Built-in command entry points are opt-in through parser option bits: HelpCommand, VersionCommand, CompletionCommand, DocsCommand, and ConfigCommand. HelpCommands enables the full set. Built-in commands are grouped as `Help Commands` in help/docs by default; use Parser.SetBuiltinCommandGroup to rename that display group or set it to an empty string. Built-in `completion` auto-detects shell format when `--shell` is omitted (`zsh`/`pwsh`) and falls back to `bash`. The `docs` command supports Markdown, HTML, man page, and JSON output formats; `docs json` serializes the full parser model as a machine-readable manifest. Use [SetDefaultCommand] or the `default-command` struct tag to activate a subcommand automatically when no explicit command token is given.

Command-local options become valid after the command token is parsed. With a global `-v` option and an `add` command, these are equivalent:

./app -v add
./app add -v

If `-v` exists only on `add`, then `./app -v add` fails, while `./app add -v` works.

Completion

Completion mode is enabled by setting `GO_FLAGS_COMPLETION`:

GO_FLAGS_COMPLETION=1 ./completion-example arg1 arg2 arg3

The last argument (`arg3`) is treated as the value to complete. When `GO_FLAGS_COMPLETION=verbose`, completion descriptions are emitted when multiple candidates exist.

Because completion executes your program, avoid side effects during startup (for example, in `init` routines).

Bash integration example:

_completion_example() {
	local args=("${COMP_WORDS[@]:1:$COMP_CWORD}")
	mapfile -t COMPREPLY < <(GO_FLAGS_COMPLETION=1 "${COMP_WORDS[0]}" "${args[@]}")
	return 0
}
complete -F _completion_example completion-example

Completion requires PassDoubleDash, and the parser enforces it automatically when `GO_FLAGS_COMPLETION` is set.

For custom value completion, implement Completer. Filename is a built-in example. Slices and arrays are also completable when their element type implements Completer. When no custom completer is available, completion source priority is: `choices` -> `completion` hint (`file`/`dir`/`none`) -> built-in bool values.

Example
var opts struct {
	// Slice of bool will append 'true' each time the option
	// is encountered (can be set multiple times, like -vvv)
	Verbose []bool `short:"v" long:"verbose" description:"Show verbose debug information"`

	// Example of automatic marshalling to desired type (uint)
	Offset uint `long:"offset" description:"Offset"`

	// Example of a callback, called each time the option is found.
	Call func(string) `short:"c" description:"Call phone number"`

	// Example of a required flag
	Name string `short:"n" long:"name" description:"A name" required:"true"`

	// Example of a value name
	File string `short:"f" long:"file" description:"A file" value-name:"FILE"`

	// Example of a pointer
	Ptr *int `short:"p" description:"A pointer to an integer"`

	// Example of a slice of strings
	StringSlice []string `short:"s" description:"A slice of strings"`

	// Example of a slice of pointers
	PtrSlice []*string `long:"ptrslice" description:"A slice of pointers to string"`

	// Example of a map
	IntMap map[string]int `long:"intmap" description:"A map from string to int"`

	// Example of a filename (useful for completion)
	Filename Filename `long:"filename" description:"A filename"`

	// Example of positional arguments
	Args struct {
		ID   string
		Num  int
		Rest []string
	} `positional-args:"yes" required:"yes"`
}

// Callback which will invoke callto:<argument> to call a number.
// Note that this works just on OS X (and probably only with
// Skype) but it shows the idea.
opts.Call = func(num string) {
	cmd := exec.Command("open", "callto:"+num)
	cmd.Start()
	cmd.Process.Release()
}

// Make some fake arguments to parse.
args := []string{
	"-vv",
	"--offset=5",
	"-n", "Me",
	"-p", "3",
	"-s", "hello",
	"-s", "world",
	"--ptrslice", "hello",
	"--ptrslice", "world",
	"--intmap", "a:1",
	"--intmap", "b:5",
	"--filename", "hello.go",
	"id",
	"10",
	"remaining1",
	"remaining2",
}

// Parse flags from `args`. Note that here we use flags.ParseArgs for
// the sake of making a working example. Normally, you would simply use
// flags.Parse(&opts) which uses os.Args
_, err := ParseArgs(&opts, args)

if err != nil {
	panic(err)
}

fmt.Printf("Verbosity: %v\n", opts.Verbose)
fmt.Printf("Offset: %d\n", opts.Offset)
fmt.Printf("Name: %s\n", opts.Name)
fmt.Printf("Ptr: %d\n", *opts.Ptr)
fmt.Printf("StringSlice: %v\n", opts.StringSlice)
fmt.Printf("PtrSlice: [%v %v]\n", *opts.PtrSlice[0], *opts.PtrSlice[1])
fmt.Printf("IntMap: [a:%v b:%v]\n", opts.IntMap["a"], opts.IntMap["b"])
fmt.Printf("Filename: %v\n", opts.Filename)
fmt.Printf("Args.ID: %s\n", opts.Args.ID)
fmt.Printf("Args.Num: %d\n", opts.Args.Num)
fmt.Printf("Args.Rest: %v\n", opts.Args.Rest)
Output:
Verbosity: [true true]
Offset: 5
Name: Me
Ptr: 3
StringSlice: [hello world]
PtrSlice: [hello world]
IntMap: [a:1 b:5]
Filename: hello.go
Args.ID: id
Args.Num: 10
Args.Rest: [remaining1 remaining2]
Example (ErrorHandling)
var opts struct {
	Name string `long:"name" required:"yes"`
}

parser := NewParser(&opts, Default&^PrintErrors)
_, err := parser.ParseArgs([]string{"--help"})

if err != nil {
	var ferr *Error
	if errors.As(err, &ferr) && ferr.Type == ErrHelp {
		fmt.Println("help requested")
		return
	}

	fmt.Println("parse error")
	return
}

fmt.Println("ok")
Output:
help requested

Index

Examples

Constants

View Source
const (
	// DocTemplateHTMLDefault is the built-in HTML template name.
	DocTemplateHTMLDefault = "html/default"
	// DocTemplateHTMLStyled is the built-in styled HTML template name.
	DocTemplateHTMLStyled = "html/styled"
	// DocTemplateManDefault is the built-in man page template name.
	DocTemplateManDefault = "man/default"
	// DocTemplateMarkdownCode is the built-in markdown code-block template name.
	DocTemplateMarkdownCode = "markdown/code"
	// DocTemplateMarkdownList is the built-in markdown list template name.
	DocTemplateMarkdownList = "markdown/list"
	// DocTemplateMarkdownTable is the built-in markdown table template name.
	DocTemplateMarkdownTable = "markdown/table"
)
View Source
const (
	// IniNone indicates no options.
	IniNone IniOptions = 0

	// IniIncludeDefaults indicates that default values should be written.
	IniIncludeDefaults = 1 << iota

	// IniCommentDefaults indicates that if IniIncludeDefaults is used
	// options with default values are written but commented out.
	IniCommentDefaults

	// IniIncludeComments indicates that comments containing the description
	// of an option should be written.
	IniIncludeComments

	// IniDefault provides a default set of options.
	IniDefault = IniIncludeComments
)
View Source
const (
	// None indicates no options.
	None Options = 0

	// HelpFlag adds a default Help Options group to the parser containing
	// -h and --help options. When either -h or --help is specified on the
	// command line, the parser will return the special error of type
	// ErrHelp. When PrintErrors is also specified, then the help message
	// will also be automatically printed to os.Stdout unless PrintHelpOnStderr
	// is set.
	HelpFlag = 1 << iota

	// VersionFlag adds built-in -v/--version option to the Help Options group.
	// When specified, parser returns ErrVersion and the version message.
	VersionFlag

	// PassDoubleDash passes all arguments after a double dash, --, as
	// remaining command line arguments (i.e. they will not be parsed for
	// flags).
	PassDoubleDash

	// IgnoreUnknown ignores any unknown options and passes them as
	// remaining command line arguments instead of generating an error.
	IgnoreUnknown

	// PrintErrors prints any errors which occurred during parsing to
	// os.Stderr. In the special case of ErrHelp, the message will be printed
	// to os.Stdout unless PrintHelpOnStderr is set.
	PrintErrors

	// PrintHelpOnStderr routes built-in help output (ErrHelp) to os.Stderr
	// when PrintErrors is enabled.
	PrintHelpOnStderr

	// PrintErrorsOnStdout routes non-help parse errors to os.Stdout
	// when PrintErrors is enabled.
	PrintErrorsOnStdout

	// PrintHelpOnInputErrors prints built-in help before common user-input
	// parser errors (for example required/unknown flags or command issues).
	PrintHelpOnInputErrors

	// SilenceDeprecationWarnings suppresses the stderr warning emitted when
	// a deprecated option or command is used during parsing.
	SilenceDeprecationWarnings

	// PassAfterNonOption passes all arguments after the first non option
	// as remaining command line arguments. This is equivalent to strict
	// POSIX processing.
	PassAfterNonOption

	// AllowBoolValues allows a user to assign true/false to a boolean value
	// rather than raising an error stating it cannot have an argument.
	AllowBoolValues

	// DefaultsIfEmpty applies tag/env defaults only to options whose current
	// values are empty. This keeps pre-populated option values intact unless
	// they were explicitly set on the command line.
	DefaultsIfEmpty

	// RequiredFromValues treats pre-populated non-empty option values as
	// satisfying `required` checks, even when the option was not explicitly
	// set by CLI/env/default processing.
	RequiredFromValues

	// KeepDescriptionWhitespace keeps leading/trailing whitespace in
	// help-rendered descriptions instead of trimming each line before wrapping.
	// This is useful for preserving indentation in lists and code examples.
	KeepDescriptionWhitespace

	// EnvProvisioning auto-generates env keys from long option names when an
	// option does not define an explicit `env` tag. Generated keys are
	// uppercased and punctuation is replaced with underscores.
	EnvProvisioning

	// ShowCommandAliases forces alias display in the built-in "Available commands"
	// list even when a command has no short description. Without this flag,
	// aliases are shown only for commands that already render a short description.
	ShowCommandAliases

	// ShowRepeatableInHelp appends a repeatable marker to option descriptions
	// (slice/map options) and repeatable positional arguments (slice).
	ShowRepeatableInHelp

	// ShowChoiceListInHelp forces rendering choices as a vertical list
	// in built-in help output.
	ShowChoiceListInHelp

	// AutoShowChoiceListInHelp enables adaptive rendering of choices as
	// a vertical list in built-in help output when available width is tight.
	// ShowChoiceListInHelp has priority and always forces list rendering.
	AutoShowChoiceListInHelp

	// HideEnvInHelp suppresses environment variable placeholders in built-in
	// help output.
	HideEnvInHelp

	// ColorHelp enables ANSI-colored built-in help output.
	ColorHelp

	// ColorErrors enables ANSI-colored parser errors according to error severity.
	ColorErrors

	// SetTerminalTitle updates terminal window title during ParseArgs using
	// TerminalTitle or parser Name.
	SetTerminalTitle

	// HelpCommand adds a built-in `help` command that writes parser help.
	HelpCommand

	// VersionCommand adds a built-in `version` command that writes version info.
	VersionCommand

	// CompletionCommand adds a built-in `completion` command that writes shell
	// completion scripts.
	CompletionCommand

	// DocsCommand adds a built-in `docs` command with format subcommands.
	DocsCommand

	// ConfigCommand adds a built-in `config` command that writes an example INI
	// configuration.
	ConfigCommand

	// DetectShellFlagStyle enables shell-based flag style rendering in help
	// and doc output when no explicit render style is set.
	DetectShellFlagStyle

	// DetectShellEnvStyle enables shell-based env placeholder rendering in
	// help and doc output when no explicit render style is set.
	DetectShellEnvStyle

	// CommandChain executes every active command implementing Commander from
	// parent to leaf. Without this option only the last active command runs.
	CommandChain

	// Default is a convenient default set of options which should cover
	// most of the uses of the flags package.
	Default = HelpFlag | PrintErrors | PassDoubleDash

	// HelpCommands enables all built-in help-related commands.
	HelpCommands = HelpCommand | VersionCommand | CompletionCommand | DocsCommand | ConfigCommand

	// ConfiguredValues is a convenience mode for config-first flows
	// (for example YAML/JSON prefill before Parse):
	//   - keep prefilled values intact (DefaultsIfEmpty)
	//   - treat non-empty prefilled values as satisfying `required`
	//     (RequiredFromValues)
	ConfiguredValues = DefaultsIfEmpty | RequiredFromValues
)
View Source
const (
	// FlagTagShort configures a one-character short flag name (`-v`).
	FlagTagShort = "short"
	// FlagTagLong configures a long flag name (`--verbose`).
	FlagTagLong = "long"
	// FlagTagRequired marks option or positional argument as required.
	FlagTagRequired = "required"
	// FlagTagXor declares mutually exclusive option relation groups.
	FlagTagXor = "xor"
	// FlagTagAnd declares option relation groups that must be used together.
	FlagTagAnd = "and"
	// FlagTagCounter enables counter mode for integer flags.
	FlagTagCounter = "counter"
	// FlagTagIO marks positional argument I/O role (in|out).
	FlagTagIO = "io"
	// FlagTagIOKind configures positional I/O kind (auto|stream|file|string).
	FlagTagIOKind = "io-kind"
	// FlagTagIOStream configures default/target stream (stdin|stdout|stderr).
	FlagTagIOStream = "io-stream"
	// FlagTagIOOpen configures output file open mode (truncate|append).
	FlagTagIOOpen = "io-open"
	// FlagTagDescription provides short help text.
	FlagTagDescription = "description"
	// FlagTagDescriptionI18n provides i18n key for description text.
	FlagTagDescriptionI18n = "description-i18n"
	// FlagTagLongDescription provides extended text (used in man/help contexts).
	FlagTagLongDescription = "long-description"
	// FlagTagLongDescriptionI18n provides i18n key for long description text.
	FlagTagLongDescriptionI18n = "long-description-i18n"
	// FlagTagNoFlag excludes the field from command-line flag parsing.
	FlagTagNoFlag = "no-flag"
	// FlagTagOptional marks option argument as optional.
	FlagTagOptional = "optional"
	// FlagTagOptionalValue defines fallback value when optional arg is omitted.
	FlagTagOptionalValue = "optional-value"
	// FlagTagOrder sets display/completion priority order for options and commands.
	FlagTagOrder = "order"
	// FlagTagDefault sets default option value (repeatable for slices/maps).
	FlagTagDefault = "default"
	// FlagTagDefaults sets multiple default option values as a delimiter-separated list.
	FlagTagDefaults = "defaults"
	// FlagTagDefaultMask customizes how default is shown in generated help.
	FlagTagDefaultMask = "default-mask"
	// FlagTagDeprecated marks an option or command as deprecated.
	// The value is a short replacement hint shown in help output and parse warnings.
	FlagTagDeprecated = "deprecated"
	// FlagTagSecret marks option values as sensitive in rendered output.
	FlagTagSecret = "secret"
	// FlagTagEnv maps option default to an environment variable key.
	FlagTagEnv = "env"
	// FlagTagAutoEnv enables deriving env key from long flag name.
	FlagTagAutoEnv = "auto-env"
	// FlagTagEnvDelim splits env-provided list/map values by delimiter.
	FlagTagEnvDelim = "env-delim"
	// FlagTagValueName customizes value placeholder shown in help.
	FlagTagValueName = "value-name"
	// FlagTagValueNameI18n provides i18n key for value placeholder.
	FlagTagValueNameI18n = "value-name-i18n"
	// FlagTagChoice restricts allowed option values (repeatable).
	FlagTagChoice = "choice"
	// FlagTagChoices restricts allowed option values as a delimiter-separated list.
	FlagTagChoices = "choices"
	// FlagTagCompletion configures completion hint (file, dir, none).
	FlagTagCompletion = "completion"
	// FlagTagHidden hides option/group/command from help and completion output.
	FlagTagHidden = "hidden"
	// FlagTagImmediate marks options/groups/commands that should bypass required checks.
	FlagTagImmediate = "immediate"
	// FlagTagBase sets radix for integer parsing.
	FlagTagBase = "base"
	// FlagTagIniName overrides key name used for INI parse/write.
	FlagTagIniName = "ini-name"
	// FlagTagIniGroup overrides section token used for INI group/command blocks.
	FlagTagIniGroup = "ini-group"
	// FlagTagNoIni excludes the field from INI parse/write.
	FlagTagNoIni = "no-ini"
	// FlagTagGroup turns a nested struct field into an option group.
	FlagTagGroup = "group"
	// FlagTagGroupI18n provides i18n key for group display name.
	FlagTagGroupI18n = "group-i18n"
	// FlagTagNamespace prefixes long option names for grouped options.
	FlagTagNamespace = "namespace"
	// FlagTagEnvNamespace prefixes environment variable names for grouped options.
	FlagTagEnvNamespace = "env-namespace"
	// FlagTagCommand turns a field into a subcommand.
	FlagTagCommand = "command"
	// FlagTagCommandI18n provides i18n key for command short description.
	FlagTagCommandI18n = "command-i18n"
	// FlagTagCommandGroup groups commands in help and documentation output.
	FlagTagCommandGroup = "command-group"
	// FlagTagSubCommandsOptional makes child subcommands optional.
	FlagTagSubCommandsOptional = "subcommands-optional"
	// FlagTagAlias adds extra command names (repeatable).
	FlagTagAlias = "alias"
	// FlagTagAliases adds extra command names as a delimiter-separated list.
	FlagTagAliases = "aliases"
	// FlagTagLongAlias adds extra long option names (repeatable).
	FlagTagLongAlias = "long-alias"
	// FlagTagLongAliases adds extra long option names as a delimiter-separated list.
	FlagTagLongAliases = "long-aliases"
	// FlagTagShortAlias adds extra short option names (repeatable).
	FlagTagShortAlias = "short-alias"
	// FlagTagShortAliases adds extra short option names as a delimiter-separated list.
	FlagTagShortAliases = "short-aliases"
	// FlagTagPositionalArgs marks a struct as positional arguments container.
	FlagTagPositionalArgs = "positional-args"
	// FlagTagPositionalArgName sets display name for a positional argument.
	FlagTagPositionalArgName = "positional-arg-name"
	// FlagTagArgNameI18n provides i18n key for positional arg display name.
	FlagTagArgNameI18n = "arg-name-i18n"
	// FlagTagArgDescriptionI18n provides i18n key for positional arg description.
	FlagTagArgDescriptionI18n = "arg-description-i18n"
	// FlagTagKeyValueDelimiter customizes map key/value delimiter.
	FlagTagKeyValueDelimiter = "key-value-delimiter"
	// FlagTagPassAfterNonOption enables command-local strict POSIX behavior.
	FlagTagPassAfterNonOption = "pass-after-non-option"
	// FlagTagDefaultCommand marks a subcommand as the default when no explicit
	// command token is provided. Only one subcommand per parent may be marked.
	FlagTagDefaultCommand = "default-command"
	// FlagTagUnquote controls automatic unquoting of string arguments.
	FlagTagUnquote = "unquote"
	// FlagTagTerminator marks an option that consumes arguments until terminator token.
	FlagTagTerminator = "terminator"
	// FlagTagValidateExistingFile requires a path to be an existing file.
	FlagTagValidateExistingFile = "validate-existing-file"
	// FlagTagValidateExistingDir requires a path to be an existing directory.
	FlagTagValidateExistingDir = "validate-existing-dir"
	// FlagTagValidateReadable requires a path to be readable.
	FlagTagValidateReadable = "validate-readable"
	// FlagTagValidateWritable requires a path to be writable.
	FlagTagValidateWritable = "validate-writable"
	// FlagTagValidateNonEmpty requires a string value to be non-empty.
	FlagTagValidateNonEmpty = "validate-non-empty"
	// FlagTagValidateRegex requires a string value to match a regular expression.
	FlagTagValidateRegex = "validate-regex"
	// FlagTagValidateMinLen requires a string value to have at least this length.
	FlagTagValidateMinLen = "validate-min-len"
	// FlagTagValidateMaxLen requires a string value to have at most this length.
	FlagTagValidateMaxLen = "validate-max-len"
	// FlagTagValidateMin requires a numeric value to be at least this value.
	FlagTagValidateMin = "validate-min"
	// FlagTagValidateMax requires a numeric value to be at most this value.
	FlagTagValidateMax = "validate-max"
	// FlagTagValidatePathAbs requires a path value to be absolute.
	FlagTagValidatePathAbs = "validate-path-abs"
)

FlagTag* constants define canonical struct tag keys used by the parser. They correspond to struct field tags read during parser/group/command scan.

View Source
const (
	// DefaultMaxLongNameLength is the default maximum length for `long` names.
	// Set parser MaxLongNameLength to 0 to disable this limit.
	DefaultMaxLongNameLength = 32
)

Variables

View Source
var (
	// ErrNotPointerToStruct indicates that a provided data container is not
	// a pointer to a struct. Only pointers to structs are valid data containers
	// for options.
	ErrNotPointerToStruct = errors.New("provided data is not a pointer to struct")

	// ErrEmptyCommandName indicates that completion generation was requested
	// without a command name.
	ErrEmptyCommandName = errors.New("command name must not be empty")

	// ErrNilWriter indicates that a nil output writer was passed.
	ErrNilWriter = errors.New("nil writer")

	// ErrNegativeMaxLongNameLength indicates an invalid negative limit.
	ErrNegativeMaxLongNameLength = errors.New("max long name length cannot be negative")

	// ErrNegativeCommandOptionIndent indicates an invalid negative indent.
	ErrNegativeCommandOptionIndent = errors.New("command option indent cannot be negative")

	// ErrNegativeHelpWidth indicates an invalid negative help width.
	ErrNegativeHelpWidth = errors.New("help width cannot be negative")

	// ErrNULTagListDelimiter indicates that zero rune was used as delimiter.
	ErrNULTagListDelimiter = errors.New("tag list delimiter cannot be NUL")

	// ErrSetConsoleTitleFailed indicates an unknown SetConsoleTitleW failure.
	ErrSetConsoleTitleFailed = errors.New("SetConsoleTitleW failed")

	// ErrCounterNonNegative indicates that counter increment cannot be negative.
	ErrCounterNonNegative = errors.New("counter increment must be non-negative")

	// ErrCounterOverflow indicates counter arithmetic overflow.
	ErrCounterOverflow = errors.New("counter overflow")

	// ErrCounterIncrementTooLarge indicates counter increment is too large.
	ErrCounterIncrementTooLarge = errors.New("counter increment is too large")

	// ErrCounterInvalidType indicates invalid type for counter option.
	ErrCounterInvalidType = errors.New("counter option must use integer type")

	// ErrRequiredRangeMissingMinimum indicates a required range without minimum.
	ErrRequiredRangeMissingMinimum = errors.New("missing minimum")
)
View Source
var (
	// ErrI18nInvalidJSONCatalog indicates malformed/unsupported catalog format.
	ErrI18nInvalidJSONCatalog = errors.New("invalid i18n json catalog format")
)

Functions

func DetectColorSupport

func DetectColorSupport(writer io.Writer) bool

DetectColorSupport reports whether ANSI colors should be used for a writer. Colors are enabled for tty writers, disabled when NO_COLOR is set, and can be forced with FORCE_COLOR.

func DetectFDTTY

func DetectFDTTY(fd uintptr) bool

DetectFDTTY reports whether file descriptor points to a tty.

func DetectFileTTY

func DetectFileTTY(file *os.File) bool

DetectFileTTY reports whether an open file descriptor is a tty.

func DetectLocale

func DetectLocale() string

DetectLocale returns detected locale using environment variables and OS-specific fallback.

func DetectShell

func DetectShell() string

DetectShell returns detected shell name (for example: bash, zsh, pwsh). Returns empty string when shell cannot be detected.

func DetectTerminalSize

func DetectTerminalSize() (int, int)

DetectTerminalSize returns detected terminal size in columns and rows.

func DetectWriterTTY

func DetectWriterTTY(writer io.Writer) bool

DetectWriterTTY reports whether writer is a tty-capable output. Non-file writers are treated as tty to preserve historical behavior.

func IniParse

func IniParse(filename string, data any) error

IniParse is a convenience function to parse command line options with default settings from an ini formatted file. The provided data is a pointer to a struct representing the default option group (named "Application Options"). For more control, use flags.NewParser.

func ListBuiltinTemplates

func ListBuiltinTemplates() []string

ListBuiltinTemplates returns sorted names of built-in templates.

func Parse

func Parse(data any) ([]string, error)

Parse is a convenience function to parse command line options with default settings. The provided data is a pointer to a struct representing the default option group (named "Application Options"). For more control, use flags.NewParser.

func ParseArgs

func ParseArgs(data any, args []string) ([]string, error)

ParseArgs is a convenience function to parse command line options with default settings. The provided data is a pointer to a struct representing the default option group (named "Application Options"). The args argument is the list of command line arguments to parse. If you just want to parse the default program command line arguments (i.e. os.Args), then use flags.Parse instead. For more control, use flags.NewParser.

func RuntimeOS

func RuntimeOS() string

RuntimeOS returns runtime OS identifier (for example: windows, linux, darwin).

func WriteBuiltinTemplate

func WriteBuiltinTemplate(w io.Writer, name string) error

WriteBuiltinTemplate writes a built-in template source by name.

func WroteHelp

func WroteHelp(err error) bool

WroteHelp is a helper to test the error from ParseArgs() to determine if the help message was written. It is safe to call without first checking that error is nil.

Types

type ANSIColor

type ANSIColor uint8

ANSIColor is an ANSI 16-color palette entry.

const (
	// ColorBlack is ANSI black.
	ColorBlack ANSIColor = iota
	// ColorRed is ANSI red.
	ColorRed
	// ColorGreen is ANSI green.
	ColorGreen
	// ColorYellow is ANSI yellow.
	ColorYellow
	// ColorBlue is ANSI blue.
	ColorBlue
	// ColorMagenta is ANSI magenta.
	ColorMagenta
	// ColorCyan is ANSI cyan.
	ColorCyan
	// ColorWhite is ANSI white.
	ColorWhite
	// ColorBrightBlack is ANSI bright black.
	ColorBrightBlack
	// ColorBrightRed is ANSI bright red.
	ColorBrightRed
	// ColorBrightGreen is ANSI bright green.
	ColorBrightGreen
	// ColorBrightYellow is ANSI bright yellow.
	ColorBrightYellow
	// ColorBrightBlue is ANSI bright blue.
	ColorBrightBlue
	// ColorBrightMagenta is ANSI bright magenta.
	ColorBrightMagenta
	// ColorBrightCyan is ANSI bright cyan.
	ColorBrightCyan
	// ColorBrightWhite is ANSI bright white.
	ColorBrightWhite
)

type Arg

type Arg struct {

	// The name of the positional argument (used in the help)
	Name string

	// Optional i18n key for Name.
	NameI18nKey string

	// A description of the positional argument (used in the help)
	Description string

	// Optional i18n key for Description.
	DescriptionI18nKey string

	// The default value(s) of the positional argument.
	Default []string

	// The minimal number of required positional arguments
	Required int

	// The maximum number of required positional arguments
	RequiredMaximum int
	// contains filtered or unexported fields
}

Arg represents a positional argument on the command line.

func (*Arg) SetCompletionFunc added in v0.5.0

func (a *Arg) SetCompletionFunc(fn func(match string) []Completion)

SetCompletionFunc registers a callback that generates dynamic completions for this positional argument. The callback is invoked during shell completion with the partial input typed so far. It takes priority over the hint fallback but yields to the Completer interface on the value type. Pass nil to remove a previously set callback.

func (*Arg) SetDefault

func (a *Arg) SetDefault(values ...string)

SetDefault replaces positional argument default values.

func (*Arg) SetDescription

func (a *Arg) SetDescription(description string)

SetDescription updates positional argument description used in help/docs.

func (*Arg) SetDescriptionI18nKey

func (a *Arg) SetDescriptionI18nKey(key string)

SetDescriptionI18nKey sets i18n key used to localize positional argument description.

func (*Arg) SetName

func (a *Arg) SetName(name string)

SetName updates positional argument name used in usage/help placeholders.

func (*Arg) SetNameI18nKey

func (a *Arg) SetNameI18nKey(key string)

SetNameI18nKey sets i18n key used to localize positional argument name.

func (*Arg) SetRequired

func (a *Arg) SetRequired(required bool)

SetRequired toggles required state for positional argument.

func (*Arg) SetRequiredRange

func (a *Arg) SetRequiredRange(requiredMin int, requiredMax int) error

SetRequiredRange sets positional required bounds. Use requiredMax = -1 for "at least requiredMin".

type Command

type Command struct {

	// Embedded, see Group for more information
	*Group

	// The active sub command (set by parsing) or nil
	Active *Command

	// The name by which the command can be invoked
	Name string

	// Group name used to organize commands in help/docs.
	CommandGroup string

	// Optional i18n key for CommandGroup.
	CommandGroupI18nKey string

	// If non-empty, marks this command as deprecated. The value is a short
	// replacement hint shown in help output and parse warnings.
	Deprecated string

	// Aliases for the command
	Aliases []string

	// Display sort index used in help/docs command ordering.
	// Positive values are shown first, then zero, then negative.
	Order int

	// Whether subcommands are optional
	SubcommandsOptional bool

	// Whether positional arguments are required
	ArgsRequired bool

	// Whether to pass all arguments after the first non option as remaining
	// command line arguments. This is equivalent to strict POSIX processing.
	// This is command-local version of PassAfterNonOption Parser flag. It
	// cannot be turned off when PassAfterNonOption Parser flag is set.
	PassAfterNonOption bool
	// contains filtered or unexported fields
}

Command represents an application command. Commands can be added to the parser (which itself is a command) and are selected/executed when its name is specified on the command line. The Command type embeds a Group and therefore also carries a set of command specific options.

func (*Command) AddAlias

func (c *Command) AddAlias(alias string)

AddAlias appends one command alias.

func (*Command) AddCommand

func (c *Command) AddCommand(command string, shortDescription string, longDescription string, data any) (*Command, error)

AddCommand adds a new command to the parser with the given name and data. The data needs to be a pointer to a struct from which the fields indicate which options are in the command. The provided data can implement the Command and Usage interfaces.

func (*Command) AddGroup

func (c *Command) AddGroup(shortDescription string, longDescription string, data any) (*Group, error)

AddGroup adds a new group to the command with the given name and data. The data needs to be a pointer to a struct from which the fields indicate which options are in the group.

func (*Command) Args

func (c *Command) Args() []*Arg

Args returns a list of positional arguments associated with this command.

func (*Command) Commands

func (c *Command) Commands() []*Command

Commands returns a list of subcommands of this command.

func (*Command) Find

func (c *Command) Find(name string) *Command

Find locates the subcommand with the given name and returns it. If no such command can be found Find will return nil.

func (*Command) FindOptionByLongName

func (c *Command) FindOptionByLongName(longName string) (option *Option)

FindOptionByLongName finds an option that is part of the command, or any of its parent commands, by matching its long name (including the option namespace).

func (*Command) FindOptionByShortName

func (c *Command) FindOptionByShortName(shortName rune) (option *Option)

FindOptionByShortName finds an option that is part of the command, or any of its parent commands, by matching its long name (including the option namespace).

func (*Command) IsDeprecated added in v0.5.0

func (c *Command) IsDeprecated() bool

IsDeprecated reports whether this command is marked as deprecated.

func (*Command) SetAliases

func (c *Command) SetAliases(aliases ...string)

SetAliases replaces command aliases used for lookup and help output.

func (*Command) SetArgsRequired

func (c *Command) SetArgsRequired(required bool)

SetArgsRequired configures whether positional args are required by default.

func (*Command) SetCommandGroup

func (c *Command) SetCommandGroup(group string)

SetCommandGroup updates help/docs group used for this command.

func (*Command) SetDefaultSubcommand added in v0.6.0

func (c *Command) SetDefaultSubcommand(name string)

SetDefaultSubcommand sets the subcommand to activate when no explicit command token is provided. The named subcommand must already be registered. Call with an empty string to clear the default.

func (*Command) SetDeprecated added in v0.5.0

func (c *Command) SetDeprecated(msg string)

SetDeprecated marks the command as deprecated with the given replacement hint. An empty string clears the deprecation marker.

func (*Command) SetHidden

func (c *Command) SetHidden(hidden bool)

SetHidden controls command visibility in help/completion/docs.

func (*Command) SetIniName

func (c *Command) SetIniName(name string)

SetIniName updates stable INI section token used for this command block.

func (*Command) SetLongDescription

func (c *Command) SetLongDescription(description string)

SetLongDescription updates command long description.

func (*Command) SetLongDescriptionI18nKey

func (c *Command) SetLongDescriptionI18nKey(key string)

SetLongDescriptionI18nKey sets i18n key for command long description.

func (*Command) SetName

func (c *Command) SetName(name string)

SetName updates command name used for lookup and help output.

func (*Command) SetOrder

func (c *Command) SetOrder(order int)

SetOrder updates display sort index used for help/docs command ordering.

func (*Command) SetPassAfterNonOption

func (c *Command) SetPassAfterNonOption(enabled bool)

SetPassAfterNonOption configures command-local strict POSIX pass-through behavior.

func (*Command) SetShortDescription

func (c *Command) SetShortDescription(description string)

SetShortDescription updates command short description.

func (*Command) SetShortDescriptionI18nKey

func (c *Command) SetShortDescriptionI18nKey(key string)

SetShortDescriptionI18nKey sets i18n key for command short description.

func (*Command) SetSubcommandsOptional

func (c *Command) SetSubcommandsOptional(optional bool)

SetSubcommandsOptional configures whether subcommand selection is optional.

type CommandDescriptionI18nKeys added in v0.3.0

type CommandDescriptionI18nKeys struct {
	Short string
	Long  string
}

CommandDescriptionI18nKeys contains localization keys for command descriptions.

type CommandDescriptions added in v0.3.0

type CommandDescriptions struct {
	Short string
	Long  string
}

CommandDescriptions contains short and long user-facing command descriptions.

type CommandSortMode

type CommandSortMode uint8

CommandSortMode configures how commands are ordered in help/docs.

const (
	// CommandSortByDeclaration keeps original declaration order.
	CommandSortByDeclaration CommandSortMode = iota
	// CommandSortByNameAsc sorts by command name ascending.
	CommandSortByNameAsc
	// CommandSortByNameDesc sorts by command name descending.
	CommandSortByNameDesc
)

type Commander

type Commander interface {
	// Execute will be called for the selected command. The args argument
	// contains the remaining command line arguments. The error that Execute
	// returns will be eventually passed out of the Parse method of the Parser.
	Execute(args []string) error
}

Commander is an interface which can be implemented by any command added in the options. When implemented, the Execute method will be called for the selected command providing the remaining command line arguments. When parser option CommandChain is enabled, Execute is called for every active command implementing Commander from parent to leaf.

type Completer

type Completer interface {
	// Complete receives a prefix representing a (partial) value
	// for its type and should provide a list of possible valid
	// completions.
	Complete(match string) []Completion
}

Completer is an interface which can be implemented by types to provide custom command line argument completion.

type Completion

type Completion struct {
	// The completed item
	Item string

	// A description of the completed item (optional)
	Description string
}

Completion is a type containing information of a completion.

type CompletionShell

type CompletionShell string

CompletionShell identifies a shell script format for completion output.

const (
	// CompletionShellBash generates a Bash completion script.
	CompletionShellBash CompletionShell = "bash"

	// CompletionShellZsh generates a Zsh completion script.
	CompletionShellZsh CompletionShell = "zsh"

	// CompletionShellPwsh generates a PowerShell completion script.
	CompletionShellPwsh CompletionShell = "pwsh"
)

func DetectCompletionShell

func DetectCompletionShell() CompletionShell

DetectCompletionShell returns detected completion shell format. Unsupported/unknown shells fallback to bash.

type Configurer

type Configurer interface {
	ConfigureFlags(parser *Parser) error
}

Configurer can be implemented by option/group/command data structs to programmatically adjust parser metadata after tag scanning.

ConfigureFlags is called before parsing when parser topology changes (for example after AddGroup/AddCommand, SetTagPrefix, SetFlagTags).

type DefaultProvider

type DefaultProvider interface {
	// Default returns one or more default string values that will be applied
	// as if they were specified through repeated `default` tags.
	Default() ([]string, error)
}

DefaultProvider is the interface implemented by types that can provide dynamic default values at runtime.

type DocFormat

type DocFormat string

DocFormat identifies output format for parser documentation rendering.

const (
	// DocFormatMan renders classic man page output.
	DocFormatMan DocFormat = "man"
	// DocFormatMarkdown renders markdown documentation.
	DocFormatMarkdown DocFormat = "markdown"
	// DocFormatHTML renders HTML documentation.
	DocFormatHTML DocFormat = "html"
	// DocFormatJSON renders the doc model as a JSON manifest.
	DocFormatJSON DocFormat = "json"
)

type DocOption

type DocOption func(*docRenderOptions) error

DocOption configures WriteDoc behavior.

func WithBuiltinCommands added in v0.6.0

func WithBuiltinCommands(names []string) DocOption

WithBuiltinCommands sets the list of built-in command names to include in the documentation output. Pass nil to include all built-in commands. Pass an empty slice to exclude all built-in commands. The default when using the built-in docs command is help, version, completion.

func WithBuiltinTemplate

func WithBuiltinTemplate(name string) DocOption

WithBuiltinTemplate selects a built-in template by name.

func WithDocRenderStyle added in v0.3.3

func WithDocRenderStyle(style RenderStyle) DocOption

WithDocRenderStyle configures how flag tokens and environment placeholders are rendered in generated documentation for this WriteDoc call.

func WithDocWrapWidth added in v0.4.0

func WithDocWrapWidth(width int) DocOption

WithDocWrapWidth configures markdown text wrapping width for one WriteDoc call. A width of zero disables wrapping.

func WithIncludeHidden

func WithIncludeHidden(include bool) DocOption

WithIncludeHidden controls whether hidden options/groups/commands are included.

func WithMarkHidden

func WithMarkHidden(mark bool) DocOption

WithMarkHidden controls hidden markers in rendered output. It does not include hidden entities by itself. Use WithIncludeHidden(true) to include hidden groups/options/commands in the rendered model.

func WithProgramName added in v0.3.0

func WithProgramName(name string) DocOption

WithProgramName overrides program/binary name in the generated doc model. It affects all templates/formats through Doc.Name and usage lines.

func WithTOC added in v0.3.0

func WithTOC(enabled bool) DocOption

WithTOC enables table-of-contents rendering for templates supporting it.

func WithTemplateBytes

func WithTemplateBytes(data []byte) DocOption

WithTemplateBytes sets custom template content from bytes.

func WithTemplateData

func WithTemplateData(data map[string]any) DocOption

WithTemplateData injects additional template data.

func WithTemplateString

func WithTemplateString(text string) DocOption

WithTemplateString sets custom template content.

func WithTrimDescriptions added in v0.3.0

func WithTrimDescriptions(enabled bool) DocOption

WithTrimDescriptions forces description trimming in doc model rendering. When enabled, leading/trailing spaces are trimmed per line for parser/command/group/option/argument descriptions.

type EnvironmentInfo

type EnvironmentInfo struct {
	// OS is runtime OS identifier (for example: windows, linux, darwin).
	OS string
	// Shell is detected shell name (for example: bash, zsh, pwsh).
	Shell string
	// CompletionShell is detected completion script format.
	CompletionShell CompletionShell
	// Locale is detected locale identifier.
	Locale string
	// TerminalColumns is detected terminal width in columns.
	TerminalColumns int
	// TerminalRows is detected terminal height in rows.
	TerminalRows int
	// TTY is tty state snapshot for standard streams.
	TTY TTYInfo
	// ShellStyle is detected render style for flags and env placeholders.
	ShellStyle RenderStyle
}

EnvironmentInfo describes detected runtime environment hints.

func DetectEnvironment

func DetectEnvironment() EnvironmentInfo

DetectEnvironment returns a snapshot of detected runtime environment hints.

type Error

type Error struct {
	// The error message
	Message string

	// The type of error
	Type ErrorType
}

Error represents a parser error. The error returned from Parse is of this type. The error contains both a Type and Message.

func (*Error) Error

func (e *Error) Error() string

Error returns the error's message

type ErrorColorScheme

type ErrorColorScheme struct {
	Warning  HelpTextStyle
	Critical HelpTextStyle
}

ErrorColorScheme configures parser error color roles.

func DefaultErrorColorScheme

func DefaultErrorColorScheme() ErrorColorScheme

DefaultErrorColorScheme returns default parser error color roles.

func GrayErrorColorScheme

func GrayErrorColorScheme() ErrorColorScheme

GrayErrorColorScheme is an alias of DefaultErrorColorScheme. Error output keeps warning/critical contrast (yellow/red) for readability.

func HighContrastErrorColorScheme

func HighContrastErrorColorScheme() ErrorColorScheme

HighContrastErrorColorScheme returns a high-contrast parser error scheme.

type ErrorType

type ErrorType uint

ErrorType represents the type of error.

const (
	// ErrUnknown indicates a generic error.
	ErrUnknown ErrorType = iota

	// ErrExpectedArgument indicates that an argument was expected.
	ErrExpectedArgument

	// ErrUnknownFlag indicates an unknown flag.
	ErrUnknownFlag

	// ErrUnknownGroup indicates an unknown group.
	ErrUnknownGroup

	// ErrMarshal indicates a marshalling error while converting values.
	ErrMarshal

	// ErrHelp indicates that the built-in help was shown (the error
	// contains the help message).
	ErrHelp

	// ErrVersion indicates that the built-in version output was shown.
	ErrVersion

	// ErrNoArgumentForBool indicates that an argument was given for a
	// boolean flag (which don't not take any arguments).
	ErrNoArgumentForBool

	// ErrRequired indicates that a required flag was not provided.
	ErrRequired

	// ErrShortNameTooLong indicates that a short flag name was specified,
	// longer than one character.
	ErrShortNameTooLong

	// ErrDuplicatedFlag indicates that a short or long flag has been
	// defined more than once
	ErrDuplicatedFlag

	// ErrTag indicates an error while parsing flag tags.
	ErrTag

	// ErrCommandRequired indicates that a command was required but not
	// specified
	ErrCommandRequired

	// ErrUnknownCommand indicates that an unknown command was specified.
	ErrUnknownCommand

	// ErrInvalidChoice indicates an invalid option value which only allows
	// a certain number of choices.
	ErrInvalidChoice

	// ErrInvalidTag indicates an invalid tag or invalid use of an existing tag
	ErrInvalidTag

	// ErrOptionConflict indicates that mutually exclusive options were used together.
	ErrOptionConflict

	// ErrOptionRequirement indicates that an option relation requirement failed.
	ErrOptionRequirement

	// ErrValidation indicates that parsed value validation failed.
	ErrValidation
)

func (ErrorType) Error

func (e ErrorType) Error() string

func (ErrorType) IsWarning

func (e ErrorType) IsWarning() bool

IsWarning reports whether the error type should be treated as warning-level.

func (ErrorType) String

func (e ErrorType) String() string

type Filename

type Filename string

Filename is a string alias which provides filename completion.

func (*Filename) Complete

func (f *Filename) Complete(match string) []Completion

Complete returns a list of existing files with the given prefix.

type FlagTags

type FlagTags struct {
	// Short maps to short option name tag (default: "short").
	Short string
	// Long maps to long option name tag (default: "long").
	Long string
	// Required maps to required marker tag (default: "required").
	Required string
	// Xor maps to mutually exclusive option relation groups tag.
	Xor string
	// And maps to option relation groups that must be used together tag.
	And string
	// Counter maps to counter mode tag for integer flags.
	Counter string
	// IO maps to positional I/O role tag.
	IO string
	// IOKind maps to positional I/O kind tag.
	IOKind string
	// IOStream maps to positional stream selector tag.
	IOStream string
	// IOOpen maps to positional output file open mode tag.
	IOOpen string
	// Description maps to short help text tag (default: "description").
	Description string
	// DescriptionI18n maps to i18n key for short help text (default: "description-i18n").
	DescriptionI18n string
	// LongDescription maps to extended help/man text tag (default: "long-description").
	LongDescription string
	// LongDescriptionI18n maps to i18n key for extended help/man text.
	LongDescriptionI18n string
	// NoFlag maps to option exclusion tag (default: "no-flag").
	NoFlag string
	// Optional maps to optional argument marker tag (default: "optional").
	Optional string
	// OptionalValue maps to fallback optional value tag (default: "optional-value").
	OptionalValue string
	// Order maps to option sorting priority tag (default: "order").
	Order string
	// Default maps to default value tag (default: "default").
	Default string
	// Defaults maps to multi-default value tag (default: "defaults").
	Defaults string
	// DefaultMask maps to help default-mask tag (default: "default-mask").
	DefaultMask string
	// Deprecated maps to deprecation marker tag (default: "deprecated").
	Deprecated string
	// Secret maps to sensitive value policy tag (default: "secret").
	Secret string
	// Env maps to environment variable key tag (default: "env").
	Env string
	// AutoEnv maps to env auto-derivation toggle tag (default: "auto-env").
	AutoEnv string
	// EnvDelim maps to env list/map delimiter tag (default: "env-delim").
	EnvDelim string
	// ValueName maps to help placeholder tag (default: "value-name").
	ValueName string
	// ValueNameI18n maps to i18n key for value placeholder tag.
	ValueNameI18n string
	// Choice maps to allowed-values tag (default: "choice").
	Choice string
	// Choices maps to multi allowed-values tag (default: "choices").
	Choices string
	// Completion maps to completion hint tag (default: "completion").
	Completion string
	// Hidden maps to hide-from-help tag (default: "hidden").
	Hidden string
	// Immediate maps to immediate-processing tag (default: "immediate").
	Immediate string
	// Base maps to integer radix tag (default: "base").
	Base string
	// IniName maps to INI key override tag (default: "ini-name").
	IniName string
	// IniGroup maps to INI section token override tag (default: "ini-group").
	IniGroup string
	// NoIni maps to INI exclusion tag (default: "no-ini").
	NoIni string
	// Group maps to group declaration tag (default: "group").
	Group string
	// GroupI18n maps to i18n key for group display name tag.
	GroupI18n string
	// Namespace maps to long-name namespace tag (default: "namespace").
	Namespace string
	// EnvNamespace maps to env-name namespace tag (default: "env-namespace").
	EnvNamespace string
	// Command maps to subcommand declaration tag (default: "command").
	Command string
	// CommandI18n maps to i18n key for command short description tag.
	CommandI18n string
	// CommandGroup maps to command group tag (default: "command-group").
	CommandGroup string
	// SubCommandsOptional maps to optional-subcommands tag (default: "subcommands-optional").
	SubCommandsOptional string
	// Alias maps to command alias tag (default: "alias").
	Alias string
	// Aliases maps to multi command aliases tag (default: "aliases").
	Aliases string
	// LongAlias maps to option long alias tag (default: "long-alias").
	LongAlias string
	// LongAliases maps to multi option long aliases tag (default: "long-aliases").
	LongAliases string
	// ShortAlias maps to option short alias tag (default: "short-alias").
	ShortAlias string
	// ShortAliases maps to multi option short aliases tag (default: "short-aliases").
	ShortAliases string
	// PositionalArgs maps to positional args struct tag (default: "positional-args").
	PositionalArgs string
	// PositionalArgName maps to positional display-name tag (default: "positional-arg-name").
	PositionalArgName string
	// ArgNameI18n maps to positional i18n display-name tag.
	ArgNameI18n string
	// ArgDescriptionI18n maps to positional i18n description tag.
	ArgDescriptionI18n string
	// KeyValueDelimiter maps to map key/value delimiter tag (default: "key-value-delimiter").
	KeyValueDelimiter string
	// PassAfterNonOption maps to command-local POSIX behavior tag (default: "pass-after-non-option").
	PassAfterNonOption string
	// Unquote maps to string unquoting control tag (default: "unquote").
	Unquote string
	// Terminator maps to terminated-arguments tag (default: "terminator").
	Terminator string
	// ValidateExistingFile maps to existing file validation tag.
	ValidateExistingFile string
	// ValidateExistingDir maps to existing directory validation tag.
	ValidateExistingDir string
	// ValidateReadable maps to readable path validation tag.
	ValidateReadable string
	// ValidateWritable maps to writable path validation tag.
	ValidateWritable string
	// ValidateNonEmpty maps to non-empty string validation tag.
	ValidateNonEmpty string
	// ValidateRegex maps to regular expression validation tag.
	ValidateRegex string
	// ValidateMinLen maps to minimum string length validation tag.
	ValidateMinLen string
	// ValidateMaxLen maps to maximum string length validation tag.
	ValidateMaxLen string
	// ValidateMin maps to minimum numeric validation tag.
	ValidateMin string
	// ValidateMax maps to maximum numeric validation tag.
	ValidateMax string
	// ValidatePathAbs maps to absolute path validation tag.
	ValidatePathAbs string
}

FlagTags defines all configurable struct tag keys used by the parser. Override fields to avoid collisions with other libraries using struct tags. Typical usage is NewFlagTagsWithPrefix("flag-") and then optional per-field overrides for mixed schemas.

func NewFlagTags

func NewFlagTags() FlagTags

NewFlagTags returns default tag names.

func NewFlagTagsWithPrefix

func NewFlagTagsWithPrefix(prefix string) FlagTags

NewFlagTagsWithPrefix returns default tag names with a custom prefix.

type Group

type Group struct {

	// A short description of the group. The
	// short description is primarily used in the built-in generated help
	// message
	ShortDescription string

	// Optional i18n key for ShortDescription.
	ShortDescriptionI18nKey string

	// A long description of the group. The long
	// description is primarily used to present information on commands
	// (Command embeds Group) in the built-in generated help and man pages.
	LongDescription string

	// Optional i18n key for LongDescription.
	LongDescriptionI18nKey string

	// The namespace of the group
	Namespace string

	// The environment namespace of the group
	EnvNamespace string

	// Stable INI section token for this group. When empty, ShortDescription is used.
	IniName string

	// If true, the group is not displayed in the help or man page
	Hidden bool

	// If true, options in this group bypass required checks and command execution.
	Immediate bool
	// contains filtered or unexported fields
}

Group represents an option group. Option groups can be used to logically group options together under a description. Groups are only used to provide more structure to options both for the user (as displayed in the help message) and for you, since groups can be nested.

func (*Group) AddGroup

func (g *Group) AddGroup(shortDescription string, longDescription string, data any) (*Group, error)

AddGroup adds a new group to the command with the given name and data. The data needs to be a pointer to a struct from which the fields indicate which options are in the group.

func (*Group) AddOption

func (g *Group) AddOption(option *Option, data any)

AddOption adds a new option to this group.

func (*Group) Data

func (g *Group) Data() any

Data returns the user-provided struct pointer backing this group.

func (*Group) Find

func (g *Group) Find(shortDescription string) *Group

Find locates the subgroup with the given short description and returns it. If no such group can be found Find will return nil. Note that the description is matched case insensitively.

func (*Group) FindOptionByLongName

func (g *Group) FindOptionByLongName(longName string) *Option

FindOptionByLongName finds an option that is part of the group, or any of its subgroups, by matching its long name (including the option namespace).

func (*Group) FindOptionByShortName

func (g *Group) FindOptionByShortName(shortName rune) *Option

FindOptionByShortName finds an option that is part of the group, or any of its subgroups, by matching its short name.

func (*Group) Groups

func (g *Group) Groups() []*Group

Groups returns the list of groups embedded in this group.

func (*Group) Options

func (g *Group) Options() []*Option

Options returns the list of options in this group.

func (*Group) SetEnvNamespace

func (g *Group) SetEnvNamespace(namespace string)

SetEnvNamespace updates env-variable namespace prefix for child options.

func (*Group) SetHidden

func (g *Group) SetHidden(hidden bool)

SetHidden controls group visibility in help/completion/docs.

func (*Group) SetImmediate

func (g *Group) SetImmediate(immediate bool)

SetImmediate controls immediate parse behavior for this group subtree.

func (*Group) SetIniName

func (g *Group) SetIniName(name string)

SetIniName updates stable INI section token used by INI read/write.

func (*Group) SetLongDescription

func (g *Group) SetLongDescription(description string)

SetLongDescription updates group long description used in docs output.

func (*Group) SetLongDescriptionI18nKey

func (g *Group) SetLongDescriptionI18nKey(key string)

SetLongDescriptionI18nKey sets i18n key for group long description.

func (*Group) SetNamespace

func (g *Group) SetNamespace(namespace string)

SetNamespace updates long-option namespace prefix for child options.

func (*Group) SetShortDescription

func (g *Group) SetShortDescription(description string)

SetShortDescription updates group short description used in help/docs output.

func (*Group) SetShortDescriptionI18nKey

func (g *Group) SetShortDescriptionI18nKey(key string)

SetShortDescriptionI18nKey sets i18n key for group short description.

type HelpColorScheme

type HelpColorScheme struct {
	BaseText                HelpTextStyle
	Banner                  HelpTextStyle
	HelpHeader              HelpTextStyle
	HelpFooter              HelpTextStyle
	LongDescription         HelpTextStyle
	VersionLabel            HelpTextStyle
	VersionValue            HelpTextStyle
	SubcommandOptionsHeader HelpTextStyle
	OptionShort             HelpTextStyle
	OptionLong              HelpTextStyle
	OptionValueName         HelpTextStyle
	OptionPunctuation       HelpTextStyle
	OptionDesc              HelpTextStyle
	OptionEnv               HelpTextStyle
	OptionDefault           HelpTextStyle
	OptionChoices           HelpTextStyle
	UsageHeader             HelpTextStyle
	UsageText               HelpTextStyle
	CommandSectionHeader    HelpTextStyle
	CommandGroupHeader      HelpTextStyle
	CommandName             HelpTextStyle
	CommandDesc             HelpTextStyle
	CommandAliases          HelpTextStyle
	ArgumentsHeader         HelpTextStyle
	ArgumentName            HelpTextStyle
	ArgumentDesc            HelpTextStyle
	GroupHeader             HelpTextStyle
}

HelpColorScheme configures help color roles.

func DefaultHelpColorScheme

func DefaultHelpColorScheme() HelpColorScheme

DefaultHelpColorScheme returns the default built-in color scheme.

func GrayHelpColorScheme

func GrayHelpColorScheme() HelpColorScheme

GrayHelpColorScheme returns a subtle gray-toned scheme for help/version while keeping most default role colors intact.

func HighContrastHelpColorScheme

func HighContrastHelpColorScheme() HelpColorScheme

HighContrastHelpColorScheme returns a high-contrast built-in color scheme.

type HelpRenderOptions added in v0.5.0

type HelpRenderOptions struct {
	// Width overrides the output wrapping width for this call.
	// Zero (the default) uses the parser's configured width or auto-detects
	// the terminal width. Set to a large value to approximate unlimited width.
	Width int
	// FlagStyle overrides the flag render style. RenderStyleAuto (the default)
	// uses the parser's configured style.
	FlagStyle RenderStyle
	// EnvStyle overrides the env render style. RenderStyleAuto (the default)
	// uses the parser's configured style.
	EnvStyle RenderStyle
	// IncludeHidden includes hidden options and groups in the output.
	IncludeHidden bool
}

HelpRenderOptions configures a single WriteHelpWithOptions call without mutating the parser. Zero-value fields use the parser's existing settings.

type HelpTextStyle

type HelpTextStyle struct {
	FG        ANSIColor
	BG        ANSIColor
	UseFG     bool
	UseBG     bool
	Bold      bool
	Italic    bool
	Underline bool
}

HelpTextStyle describes color and font style attributes for help output.

type I18nCatalog

type I18nCatalog interface {
	Lookup(locale, key string) (string, bool)
}

I18nCatalog resolves localized text by locale and key.

func NewJSONCatalog

func NewJSONCatalog(data []byte) (I18nCatalog, error)

NewJSONCatalog parses JSON catalog bytes into an I18nCatalog.

func NewJSONCatalogDirFS

func NewJSONCatalogDirFS(fsys fs.FS, dir string) (I18nCatalog, error)

NewJSONCatalogDirFS loads and merges all .json catalogs from the given fs directory. Files are processed in lexical order for deterministic conflict resolution.

func NewJSONCatalogFS

func NewJSONCatalogFS(fsys fs.FS, path string) (I18nCatalog, error)

NewJSONCatalogFS parses JSON catalog from fs path into an I18nCatalog.

type I18nConfig

type I18nConfig struct {
	ModuleCatalog   I18nCatalog
	UserCatalog     I18nCatalog
	Locale          string
	FallbackLocales []string
}

I18nConfig configures parser localization behavior.

type I18nCoverageConfig

type I18nCoverageConfig struct {
	ModuleCatalog     I18nCatalog
	UserCatalog       I18nCatalog
	BaseLocale        string
	Locales           []string
	CheckPlaceholders bool
}

I18nCoverageConfig configures merged catalog coverage validation.

type I18nCoverageReport

type I18nCoverageReport struct {
	Locale                string
	MissingKeys           []string
	PlaceholderMismatches []I18nPlaceholderMismatch
}

I18nCoverageReport describes missing translation keys for one locale.

func CheckCatalogCoverage

func CheckCatalogCoverage(catalog I18nCatalog, baseLocale string, locales ...string) ([]I18nCoverageReport, error)

CheckCatalogCoverage compares locale key sets against base locale keys. It reports keys that are present in base locale but missing in each target locale. If no target locales are provided, all catalog locales except base are checked.

func CheckMergedCatalogCoverage

func CheckMergedCatalogCoverage(cfg I18nCoverageConfig) ([]I18nCoverageReport, error)

CheckMergedCatalogCoverage compares effective locale key sets after applying user catalog overrides over module catalog messages.

type I18nPlaceholderMismatch

type I18nPlaceholderMismatch struct {
	Key  string
	Base []string
	Got  []string
}

I18nPlaceholderMismatch describes placeholder differences for one key.

type IniError

type IniError struct {
	// The error message.
	Message string

	// The filename of the file in which the error occurred.
	File string

	// The line number at which the error occurred.
	LineNumber uint
}

IniError contains location information on where an error occurred.

func (*IniError) Error

func (x *IniError) Error() string

Error provides a "file:line: message" formatted message of the ini error.

type IniExampleOptions

type IniExampleOptions struct {
	// CommentWidth is max width for wrapped comment lines (without "; " prefix).
	// When <= 0, default width is used.
	CommentWidth int
}

IniExampleOptions configures example INI rendering.

type IniOptions

type IniOptions uint

IniOptions for writing

type IniParser

type IniParser struct {
	ParseAsDefaults bool // override default flags
	// contains filtered or unexported fields
}

IniParser is a utility to read and write flags options from and to ini formatted strings.

func NewIniParser

func NewIniParser(p *Parser) *IniParser

NewIniParser creates a new ini parser for a given Parser.

func (*IniParser) Parse

func (i *IniParser) Parse(reader io.Reader) error

Parse parses flags from an ini format. You can use ParseFile as a convenience function to parse from a filename instead of a general io.Reader.

The format of the ini file is as follows:

[Option group name]
option = value

Each section in the ini file represents an option group or command in the flags parser. The default flags parser option group (i.e. when using flags.Parse) is named 'Application Options'. The ini option name is matched in the following order:

  1. Compared to the ini-name tag on the option struct field (if present)
  2. Compared to the struct field name
  3. Compared to the option long name (if present)
  4. Compared to the option short name (if present)

Sections for nested groups and commands can be addressed using a dot `.`. namespacing notation (i.e [subcommand.Options]). Group section names are matched case insensitive.

The returned errors can be of the type flags.Error or flags.IniError.

func (*IniParser) ParseFile

func (i *IniParser) ParseFile(filename string) error

ParseFile parses flags from an ini formatted file. See Parse for more information on the ini file format. The returned errors can be of the type flags.Error or flags.IniError.

func (*IniParser) Write

func (i *IniParser) Write(writer io.Writer, options IniOptions)

Write writes the current values of all the flags to an ini format. See Parse for more information on the ini file format. You typically call this only after settings have been parsed since the default values of each option are stored just before parsing the flags (this is only relevant when IniIncludeDefaults is _not_ set in options).

func (*IniParser) WriteExample

func (i *IniParser) WriteExample(writer io.Writer)

WriteExample writes an example INI with descriptive comments and defaults. Required options are always rendered as active keys.

func (*IniParser) WriteExampleWithOptions

func (i *IniParser) WriteExampleWithOptions(writer io.Writer, opts IniExampleOptions)

WriteExampleWithOptions writes an example INI with configurable formatting.

func (*IniParser) WriteFile

func (i *IniParser) WriteFile(filename string, options IniOptions) error

WriteFile writes the flags as ini format into a file. See Write for more information. The returned error occurs when the specified file could not be opened for writing.

type Localizer

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

Localizer resolves localized text from an I18nConfig without requiring a Parser. It is useful for application messages that share the same catalogs and locale chain as CLI help and parser errors.

func NewLocalizer

func NewLocalizer(cfg I18nConfig) *Localizer

NewLocalizer creates a standalone localizer with the provided config.

func (*Localizer) LocaleChain

func (l *Localizer) LocaleChain() []string

LocaleChain returns resolved locale lookup order for the localizer.

func (*Localizer) Localize

func (l *Localizer) Localize(key, fallback string, data map[string]string) string

Localize returns localized text for key with source fallback and optional placeholder substitutions.

type Marshaler

type Marshaler interface {
	// MarshalFlag marshals a flag value to its string representation.
	MarshalFlag() (string, error)
}

Marshaler is the interface implemented by types that can marshal themselves to a string representation of the flag.

type Option

type Option struct {

	// The description of the option flag. This description is shown
	// automatically in the built-in help.
	Description string

	// Optional i18n key for Description.
	DescriptionI18nKey string

	// The long name of the option. If not "", the option flag can be
	// activated using --<LongName>. Either ShortName or LongName needs
	// to be non-empty.
	LongName string

	// The optional environment default value key name.
	EnvDefaultKey string

	// The optional delimiter string for EnvDefaultKey values.
	EnvDefaultDelim string

	// A name for the value of an option shown in the Help as --flag [ValueName]
	ValueName string

	// Optional i18n key for ValueName.
	ValueNameI18nKey string

	// A mask value to show in the help instead of the default value. This
	// is useful for hiding sensitive information in the help, such as
	// passwords.
	DefaultMask string

	// If non-empty, the option consumes arguments until this exact token is
	// reached (or until end-of-input). This supports find -exec style argument
	// blocks. Only slice and slice-of-slices options are valid with terminator.
	Terminator string

	// If non-empty, marks this option as deprecated. The value is a short
	// replacement hint shown in help output and parse warnings.
	Deprecated string

	// Additional long names for the option (without namespace prefix in tags).
	LongAliases []string

	// The default value of the option.
	Default []string

	// The optional value of the option. The optional value is used when
	// the option flag is marked as having an OptionalArgument. This means
	// that when the flag is specified, but no option argument is given,
	// the value of the field this option represents will be set to
	// OptionalValue. This is only valid for non-boolean options.
	OptionalValue []string

	// If non empty, only a certain set of values is allowed for an option.
	Choices []string

	// Relation groups where only one option can be used.
	XorGroups []string

	// Relation groups where all options must be used together.
	AndGroups []string

	// Additional short names for the option.
	ShortAliases []rune

	// Display and completion priority within the option's group block.
	// Positive values move options to the top, negative to the bottom,
	// and zero keeps them in the normal sort mode.
	Order int

	// The short name of the option (a single character). If not 0, the
	// option flag can be 'activated' using -<ShortName>. Either ShortName
	// or LongName needs to be non-empty.
	ShortName rune

	// If true, values for this option are redacted in rendered output and
	// parser errors.
	Secret bool

	// If true, specifies that the argument to an option flag is optional.
	// When no argument to the flag is specified on the command line, the
	// value of OptionalValue will be set in the field this option represents.
	// This is only valid for non-boolean options.
	OptionalArgument bool

	// If true, the option _must_ be specified on the command line. If the
	// option is not specified, the parser will generate an ErrRequired type
	// error.
	Required bool

	// If true, the option acts as a counter:
	// each flag occurrence increments by 1,
	// and explicit numeric values increment by that amount.
	Counter bool

	// If true, the option is not displayed in the help or man page
	Hidden bool

	// If true, this option participates in immediate parse mode.
	Immediate bool
	// contains filtered or unexported fields
}

Option flag information. Contains a description of the option, short and long name as well as a default value and whether an argument for this flag is optional.

func (*Option) AddLongAlias

func (option *Option) AddLongAlias(alias string) error

AddLongAlias appends one long option alias.

func (*Option) AddShortAlias

func (option *Option) AddShortAlias(alias rune) error

AddShortAlias appends one short option alias.

func (*Option) EnvKeyWithNamespace

func (option *Option) EnvKeyWithNamespace() string

EnvKeyWithNamespace returns the option's env key with the group namespaces prepended by walking up the option's group tree. Namespaces and the env key itself are separated by the parser's namespace delimiter. If the env key is empty an empty string is returned.

func (*Option) Field

func (option *Option) Field() reflect.StructField

Field returns the reflect struct field of the option.

func (*Option) IsDeprecated added in v0.5.0

func (option *Option) IsDeprecated() bool

IsDeprecated reports whether this option is marked as deprecated.

func (*Option) IsImmediate

func (option *Option) IsImmediate() bool

IsImmediate reports whether this option is immediate directly or via parent groups.

func (*Option) IsSecret added in v0.4.0

func (option *Option) IsSecret() bool

IsSecret reports whether option values are redacted in rendered output and parser errors.

func (*Option) IsSet

func (option *Option) IsSet() bool

IsSet returns true if option has been set

func (*Option) IsSetDefault

func (option *Option) IsSetDefault() bool

IsSetDefault returns true if option has been set via the default option tag

func (*Option) LongAliasesWithNamespace

func (option *Option) LongAliasesWithNamespace() []string

LongAliasesWithNamespace returns option long aliases with group namespaces applied.

func (*Option) LongNameWithNamespace

func (option *Option) LongNameWithNamespace() string

LongNameWithNamespace returns the option's long name with the group namespaces prepended by walking up the option's group tree. Namespaces and the long name itself are separated by the parser's namespace delimiter. If the long name is empty an empty string is returned.

func (*Option) Set

func (option *Option) Set(value *string) error

Set the value of an option to the specified value. An error will be returned if the specified value could not be converted to the corresponding option value type.

func (*Option) SetAndGroups added in v0.2.0

func (option *Option) SetAndGroups(groups ...string)

SetAndGroups replaces all-or-none relation groups for this option.

func (*Option) SetAutoEnv

func (option *Option) SetAutoEnv(enabled bool) error

SetAutoEnv enables or disables env-key derivation from long option name. When enabled and env key is currently empty, a key is derived automatically.

func (*Option) SetBase

func (option *Option) SetBase(base int) error

SetBase configures numeric radix for integer parse/format. Use 0 for automatic base detection from prefixes (Go-style).

func (*Option) SetChoices

func (option *Option) SetChoices(values ...string)

SetChoices replaces allowed option values.

func (*Option) SetCompletionFunc added in v0.5.0

func (option *Option) SetCompletionFunc(fn func(match string) []Completion)

SetCompletionFunc registers a callback that generates dynamic completions for this option. The callback is invoked during shell completion with the partial input typed so far. It takes priority over Choices but yields to the Completer interface on the value type. Pass nil to remove a previously set callback.

func (*Option) SetDefault

func (option *Option) SetDefault(values ...string)

SetDefault replaces option default values.

func (*Option) SetDefaultMask

func (option *Option) SetDefaultMask(mask string)

SetDefaultMask sets displayed default mask used in help/docs.

func (*Option) SetDeprecated added in v0.5.0

func (option *Option) SetDeprecated(msg string)

SetDeprecated marks the option as deprecated with the given replacement hint. An empty string clears the deprecation marker.

func (*Option) SetDescription

func (option *Option) SetDescription(description string)

SetDescription updates option description used in help/docs output.

func (*Option) SetDescriptionI18nKey

func (option *Option) SetDescriptionI18nKey(key string)

SetDescriptionI18nKey sets i18n key used to localize option description.

func (*Option) SetEnv

func (option *Option) SetEnv(key string, delim string) error

SetEnv sets environment key and optional split delimiter for env value.

func (*Option) SetHidden

func (option *Option) SetHidden(hidden bool)

SetHidden controls whether option is shown in help/completion/docs.

func (*Option) SetImmediate

func (option *Option) SetImmediate(immediate bool)

SetImmediate enables or disables immediate parse mode for the option.

func (*Option) SetIniName

func (option *Option) SetIniName(name string)

SetIniName overrides key name used for INI read/write.

func (*Option) SetKeyValueDelimiter

func (option *Option) SetKeyValueDelimiter(delimiter string)

SetKeyValueDelimiter configures map key/value separator (default is ":").

func (*Option) SetLongAliases

func (option *Option) SetLongAliases(aliases ...string) error

SetLongAliases replaces all long option aliases.

func (*Option) SetLongName

func (option *Option) SetLongName(name string) error

SetLongName updates canonical long option name.

func (*Option) SetNoIni

func (option *Option) SetNoIni(disabled bool)

SetNoIni enables or disables INI read/write participation for the option.

func (*Option) SetOptional

func (option *Option) SetOptional(optional bool, values ...string)

SetOptional configures optional argument behavior and fallback value(s).

func (*Option) SetOrder

func (option *Option) SetOrder(order int)

SetOrder updates help/completion sorting priority for this option.

func (*Option) SetRequired

func (option *Option) SetRequired(required bool)

SetRequired enables or disables required option validation.

func (*Option) SetRequiredRange added in v0.2.0

func (option *Option) SetRequiredRange(requiredMin int, requiredMax int) error

SetRequiredRange sets required value bounds for repeatable options. Use requiredMax = -1 for "at least requiredMin".

func (*Option) SetSecret added in v0.4.0

func (option *Option) SetSecret(secret bool)

SetSecret controls whether option values are redacted in rendered output and parser errors.

func (*Option) SetShortAliases

func (option *Option) SetShortAliases(aliases ...rune) error

SetShortAliases replaces all short option aliases.

func (*Option) SetShortName

func (option *Option) SetShortName(name rune) error

SetShortName updates canonical short option name.

func (*Option) SetTerminated

func (option *Option) SetTerminated(values []string) error

SetTerminated sets all values collected for a terminated option. For []T options this replaces the current slice value. For [][]T options this appends one collected argument batch.

func (*Option) SetTerminator

func (option *Option) SetTerminator(terminator string)

SetTerminator configures terminated-argument mode for slice options.

func (*Option) SetUnquote

func (option *Option) SetUnquote(enabled bool)

SetUnquote controls automatic unquoting for quoted string arguments.

func (*Option) SetValueName

func (option *Option) SetValueName(name string)

SetValueName updates help placeholder for option argument.

func (*Option) SetValueNameI18nKey

func (option *Option) SetValueNameI18nKey(key string)

SetValueNameI18nKey sets i18n key used to localize option value placeholder.

func (*Option) SetXorGroups added in v0.2.0

func (option *Option) SetXorGroups(groups ...string)

SetXorGroups replaces mutually exclusive relation groups for this option.

func (*Option) String

func (option *Option) String() string

String converts an option to a human friendly readable string describing the option.

func (*Option) Value

func (option *Option) Value() any

Value returns the option value as an interface{}.

type OptionSortMode

type OptionSortMode uint8

OptionSortMode configures how options are ordered within each group block.

const (
	// OptionSortByDeclaration keeps original declaration order.
	OptionSortByDeclaration OptionSortMode = iota
	// OptionSortByNameAsc sorts by option name ascending.
	OptionSortByNameAsc
	// OptionSortByNameDesc sorts by option name descending.
	OptionSortByNameDesc
	// OptionSortByType sorts by configured type rank, then by name.
	OptionSortByType
)

type OptionTypeClass

type OptionTypeClass uint8

OptionTypeClass groups option value types for type-based sorting.

const (
	// OptionTypeBool classifies boolean option values.
	OptionTypeBool OptionTypeClass = iota
	// OptionTypeNumber classifies integer/float option values.
	OptionTypeNumber
	// OptionTypeString classifies string option values.
	OptionTypeString
	// OptionTypeDuration classifies time.Duration option values.
	OptionTypeDuration
	// OptionTypeCollection classifies slice/map/array option values.
	OptionTypeCollection
	// OptionTypeCustom classifies all remaining option value types.
	OptionTypeCustom
)

type Options

type Options uint

Options provides parser options that change the behavior of the option parser.

type Parser

type Parser struct {

	// Embedded, see Command for more information
	*Command

	// UnknownOptionsHandler is a function which gets called when the parser
	// encounters an unknown option. The function receives the unknown option
	// name, a SplitArgument which specifies its value if set with an argument
	// separator, and the remaining command line arguments.
	// It should return a new list of remaining arguments to continue parsing,
	// or an error to indicate a parse failure.
	UnknownOptionHandler func(option string, arg SplitArgument, args []string) ([]string, error)

	// CompletionHandler is a function gets called to handle the completion of
	// items. By default, the items are printed and the application is exited.
	// You can override this default behavior by specifying a custom CompletionHandler.
	CompletionHandler func(items []Completion)

	// CommandHandler is a function that gets called to handle execution of a
	// command. By default, the command will simply be executed. This can be
	// overridden to perform certain actions (such as applying global flags)
	// just before the command is executed. Note that if you override the
	// handler it is your responsibility to call the command.Execute function.
	//
	// The command passed into CommandHandler may be nil in case there is no
	// command to be executed when parsing has finished.
	CommandHandler func(command Commander, args []string) error

	// A usage string to be displayed in the help message.
	Usage string

	// NamespaceDelimiter separates group namespaces and option long names
	NamespaceDelimiter string

	// EnvNamespaceDelimiter separates group env namespaces and env keys
	EnvNamespaceDelimiter string

	// EnvPrefix prepends all resolved environment variable keys.
	EnvPrefix string

	// TerminalTitle overrides terminal title text when SetTerminalTitle is enabled.
	// If empty, parser Name is used.
	TerminalTitle string

	// MaxLongNameLength limits allowed rune length of option `long` names.
	// Zero disables the limit.
	MaxLongNameLength int

	// Option flags changing the behavior of the parser.
	Options Options

	// TagListDelimiter splits values for list-based struct tags such as
	// defaults/choices/aliases.
	TagListDelimiter rune
	// contains filtered or unexported fields
}

A Parser provides command line option parsing. It can contain several option groups each with their own set of options.

func NewNamedParser

func NewNamedParser(appname string, options Options) *Parser

NewNamedParser creates a new parser. The appname is used to display the executable name in the built-in help message. Option groups and commands can be added to this parser by using AddGroup and AddCommand.

func NewParser

func NewParser(data any, options Options) *Parser

NewParser creates a new parser. It uses os.Args[0] as the application name and then calls Parser.NewNamedParser (see Parser.NewNamedParser for more details). The provided data is a pointer to a struct representing the default option group (named "Application Options"), or nil if the default group should not be added. The options parameter specifies a set of options for the parser.

func (*Parser) BuiltinHelpOption

func (p *Parser) BuiltinHelpOption() *Option

BuiltinHelpOption returns built-in help option when HelpFlag is enabled. It materializes built-in options lazily and returns nil when unavailable.

func (*Parser) BuiltinVersionOption

func (p *Parser) BuiltinVersionOption() *Option

BuiltinVersionOption returns built-in version option when VersionFlag is enabled. It materializes built-in options lazily and returns nil when unavailable.

func (*Parser) DisableI18n

func (p *Parser) DisableI18n()

DisableI18n disables parser localization.

func (*Parser) EnsureBuiltinCommands

func (p *Parser) EnsureBuiltinCommands() error

EnsureBuiltinCommands materializes built-in commands when enabled.

func (*Parser) EnsureBuiltinOptions

func (p *Parser) EnsureBuiltinOptions()

EnsureBuiltinOptions materializes built-in help/version options (when enabled) so they can be discovered and tuned before parsing.

func (*Parser) LocaleChain

func (p *Parser) LocaleChain() []string

LocaleChain returns resolved locale lookup order for the parser.

func (*Parser) Localize

func (p *Parser) Localize(key, fallback string, data map[string]string) string

Localize returns localized text for key with source fallback and optional placeholder substitutions.

func (*Parser) Parse

func (p *Parser) Parse() ([]string, error)

Parse parses the command line arguments from os.Args using Parser.ParseArgs. For more detailed information see ParseArgs.

func (*Parser) ParseArgs

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

ParseArgs parses the command line arguments according to the option groups that were added to the parser. On successful parsing of the arguments, the remaining, non-option, arguments (if any) are returned. The returned error indicates a parsing error and can be used with PrintError to display contextual information on where the error occurred exactly.

When the common help group has been added (AddHelp) and either -h or --help was specified in the command line arguments, a help message will be automatically printed if the PrintErrors option is enabled. Furthermore, the special error type ErrHelp is returned. It is up to the caller to exit the program if so desired.

func (*Parser) Rebuild

func (p *Parser) Rebuild() error

Rebuild rescans groups and commands using current tag mapping options.

func (*Parser) SetBanner added in v0.4.0

func (p *Parser) SetBanner(text string)

SetBanner configures raw banner text rendered after the help header and before normal built-in help output.

func (*Parser) SetBuiltinCommandGroup

func (p *Parser) SetBuiltinCommandGroup(group string)

SetBuiltinCommandGroup configures the display group used by built-in commands in help/docs. Use an empty string to render them without a group.

func (*Parser) SetBuiltinCommandHidden added in v0.3.3

func (p *Parser) SetBuiltinCommandHidden(name string, hidden bool) error

SetBuiltinCommandHidden controls visibility of an enabled built-in command in help, completion, and generated documentation.

func (*Parser) SetCommandDescriptionI18nKeys added in v0.3.0

func (p *Parser) SetCommandDescriptionI18nKeys(keys map[string]CommandDescriptionI18nKeys)

SetCommandDescriptionI18nKeys updates short and long description i18n keys for multiple commands. Missing command names are ignored.

func (*Parser) SetCommandDescriptions added in v0.3.0

func (p *Parser) SetCommandDescriptions(descriptions map[string]CommandDescriptions)

SetCommandDescriptions updates short and long descriptions for multiple commands. Missing command names are ignored.

func (*Parser) SetCommandLongDescriptionI18nKeys added in v0.3.0

func (p *Parser) SetCommandLongDescriptionI18nKeys(keys map[string]string)

SetCommandLongDescriptionI18nKeys updates long description i18n keys for multiple commands. Missing command names are ignored.

func (*Parser) SetCommandLongDescriptions added in v0.3.0

func (p *Parser) SetCommandLongDescriptions(descriptions map[string]string)

SetCommandLongDescriptions updates long descriptions for multiple commands. Missing command names are ignored.

func (*Parser) SetCommandOptionIndent

func (p *Parser) SetCommandOptionIndent(indent int) error

SetCommandOptionIndent configures extra spaces before command option rows in built-in help output. The default is 0, so top-level and command options use the same indentation.

func (*Parser) SetCommandShortDescriptionI18nKeys added in v0.3.0

func (p *Parser) SetCommandShortDescriptionI18nKeys(keys map[string]string)

SetCommandShortDescriptionI18nKeys updates short description i18n keys for multiple commands. Missing command names are ignored.

func (*Parser) SetCommandShortDescriptions added in v0.3.0

func (p *Parser) SetCommandShortDescriptions(descriptions map[string]string)

SetCommandShortDescriptions updates short descriptions for multiple commands. Missing command names are ignored.

func (*Parser) SetCommandSort

func (p *Parser) SetCommandSort(mode CommandSortMode)

SetCommandSort configures command order mode for help/docs presentation.

func (*Parser) SetDefaultCommand added in v0.6.0

func (p *Parser) SetDefaultCommand(name string)

SetDefaultCommand sets the root subcommand to activate when no explicit command token is provided. Equivalent to calling SetDefaultSubcommand on the root Command. The named subcommand must already be registered. Call with an empty string to clear the default.

func (*Parser) SetEnvPrefix

func (p *Parser) SetEnvPrefix(prefix string)

SetEnvPrefix configures a global prefix for all environment variable keys. For example, with prefix "MY_APP" and delimiter "_", env key "PORT" becomes "MY_APP_PORT", and grouped keys become "MY_APP_<GROUP>_<KEY>".

func (*Parser) SetErrorColorScheme

func (p *Parser) SetErrorColorScheme(scheme ErrorColorScheme)

SetErrorColorScheme configures color roles used by parser error rendering.

func (*Parser) SetFlagTags

func (p *Parser) SetFlagTags(tags FlagTags) error

SetFlagTags configures custom struct tag names used by the parser. It rescans already attached top-level groups and commands.

func (*Parser) SetHelpColorScheme

func (p *Parser) SetHelpColorScheme(scheme HelpColorScheme)

SetHelpColorScheme configures color roles used by built-in help rendering.

func (*Parser) SetHelpEnvRenderStyle

func (p *Parser) SetHelpEnvRenderStyle(style RenderStyle)

SetHelpEnvRenderStyle configures how env placeholders are rendered in built-in help and doc templates.

func (*Parser) SetHelpFlagRenderStyle

func (p *Parser) SetHelpFlagRenderStyle(style RenderStyle)

SetHelpFlagRenderStyle configures how flag tokens are rendered in built-in help and doc templates.

func (*Parser) SetHelpFooter added in v0.4.0

func (p *Parser) SetHelpFooter(text string)

SetHelpFooter configures raw text rendered after normal built-in help output.

func (*Parser) SetHelpHeader added in v0.4.0

func (p *Parser) SetHelpHeader(text string)

SetHelpHeader configures raw text rendered before the banner and normal built-in help output.

func (*Parser) SetHelpWidth

func (p *Parser) SetHelpWidth(width int) error

SetHelpWidth configures built-in help output wrapping width. When unset, help uses the current terminal width with a fallback of 80 columns. Width 0 disables wrapping.

func (*Parser) SetI18n

func (p *Parser) SetI18n(cfg I18nConfig)

SetI18n enables parser localization with the provided config.

func (*Parser) SetI18nFallbackLocales

func (p *Parser) SetI18nFallbackLocales(locales ...string)

SetI18nFallbackLocales updates i18n fallback locale chain. If i18n is not enabled yet, it enables i18n with default module catalog.

func (*Parser) SetManSection added in v0.6.0

func (p *Parser) SetManSection(section int)

SetManSection sets the man page section number used in the .TH header line. Valid values are 1–9. The default is 1 (user commands).

func (*Parser) SetMaxLongNameLength

func (p *Parser) SetMaxLongNameLength(length int) error

SetMaxLongNameLength sets the maximum allowed length for option `long` names. Value 0 disables the limit. Negative values are rejected. Existing parser groups/commands are rescanned so the new rule is applied immediately.

func (*Parser) SetOptionSort

func (p *Parser) SetOptionSort(mode OptionSortMode)

SetOptionSort configures option order mode for grouped option presentation.

func (*Parser) SetOptionTypeOrder

func (p *Parser) SetOptionTypeOrder(order []OptionTypeClass) error

SetOptionTypeOrder customizes type rank used by OptionSortByType.

func (*Parser) SetSeeAlso added in v0.6.0

func (p *Parser) SetSeeAlso(refs ...string)

SetSeeAlso sets the SEE ALSO cross-reference entries rendered in all documentation formats. In man pages each entry should follow the man page convention, e.g. "grep(1)".

func (*Parser) SetTagListDelimiter

func (p *Parser) SetTagListDelimiter(delimiter rune) error

SetTagListDelimiter sets delimiter for list-based struct tags such as defaults/choices/aliases and rescans attached groups/commands.

func (*Parser) SetTagPrefix

func (p *Parser) SetTagPrefix(prefix string) error

SetTagPrefix configures a common prefix for all struct tags used by the parser. It rescans already attached top-level groups and commands.

func (*Parser) SetVersion

func (p *Parser) SetVersion(version string)

SetVersion sets parser-level version override.

func (*Parser) SetVersionAuthor added in v0.6.0

func (p *Parser) SetVersionAuthor(author string)

SetVersionAuthor sets the application author string shown in version output.

func (*Parser) SetVersionBugsURL added in v0.6.0

func (p *Parser) SetVersionBugsURL(url string)

SetVersionBugsURL sets the bug-tracker URL shown in version output.

func (*Parser) SetVersionCommit

func (p *Parser) SetVersionCommit(revision string)

SetVersionCommit sets parser-level VCS revision override.

func (*Parser) SetVersionFields

func (p *Parser) SetVersionFields(fields VersionFields)

SetVersionFields configures fields rendered by built-in version output.

func (*Parser) SetVersionInfo

func (p *Parser) SetVersionInfo(info VersionInfo)

SetVersionInfo sets parser-level version metadata overrides.

func (*Parser) SetVersionLicense added in v0.6.0

func (p *Parser) SetVersionLicense(license string)

SetVersionLicense sets the application license identifier shown in version output.

func (*Parser) SetVersionShort added in v0.6.0

func (p *Parser) SetVersionShort(short bool)

SetVersionShort configures the built-in --version/-v flag to print only the bare version string (equivalent to running the version --short command).

func (*Parser) SetVersionTarget

func (p *Parser) SetVersionTarget(goos string, goarch string)

SetVersionTarget sets parser-level GOOS/GOARCH overrides.

func (*Parser) SetVersionTime

func (p *Parser) SetVersionTime(t time.Time)

SetVersionTime sets parser-level VCS revision time override.

func (*Parser) SetVersionURL

func (p *Parser) SetVersionURL(url string)

SetVersionURL sets parser-level repository URL override.

func (*Parser) Validate

func (p *Parser) Validate() error

Validate re-runs parser-level metadata checks after programmatic mutations. It applies Configurer hooks and then validates duplicate flag names.

func (*Parser) VersionInfo

func (p *Parser) VersionInfo() VersionInfo

VersionInfo returns detected build metadata merged with parser-level overrides.

func (*Parser) WriteAutoCompletion

func (p *Parser) WriteAutoCompletion(w io.Writer) error

WriteAutoCompletion writes a shell completion script using detected shell. Unsupported/unknown shell environments fallback to bash format.

func (*Parser) WriteBanner added in v0.4.0

func (p *Parser) WriteBanner(writer io.Writer)

WriteBanner writes the configured banner text to writer as a raw block.

func (*Parser) WriteCompletion

func (p *Parser) WriteCompletion(w io.Writer, shell CompletionShell) error

WriteCompletion writes a shell completion script for the parser command name.

func (*Parser) WriteDoc

func (p *Parser) WriteDoc(w io.Writer, format DocFormat, opts ...DocOption) error

WriteDoc renders parser documentation in the selected format.

func (*Parser) WriteHelp

func (p *Parser) WriteHelp(writer io.Writer)

WriteHelp writes a help message containing all the possible options and their descriptions to the provided writer. Note that the HelpFlag parser option provides a convenient way to add a -h/--help option group to the command line parser which will automatically show the help messages using this method.

func (*Parser) WriteHelpWithOptions added in v0.5.0

func (p *Parser) WriteHelpWithOptions(writer io.Writer, opts HelpRenderOptions)

WriteHelpWithOptions writes help output applying per-call render overrides. It does not mutate the parser; all overrides are rolled back before it returns.

func (*Parser) WriteManPage

func (p *Parser) WriteManPage(w io.Writer)

WriteManPage writes a basic man page in groff format to the specified writer.

func (*Parser) WriteNamedCompletion

func (p *Parser) WriteNamedCompletion(w io.Writer, shell CompletionShell, commandName string) error

WriteNamedCompletion writes a shell completion script for commandName.

func (*Parser) WriteVersion

func (p *Parser) WriteVersion(w io.Writer, fields VersionFields)

WriteVersion writes version/build metadata in human-readable format.

type RenderStyle

type RenderStyle uint8

RenderStyle controls how flags and environment variables are rendered in help and documentation output.

const (
	// RenderStyleAuto uses the current default behavior.
	RenderStyleAuto RenderStyle = iota
	// RenderStylePOSIX renders POSIX-style output (--flag, $ENV).
	RenderStylePOSIX
	// RenderStyleWindows renders Windows-style output (/flag, %ENV%).
	RenderStyleWindows
	// RenderStyleShell detects shell style from environment variables.
	RenderStyleShell
)

func DetectShellStyle

func DetectShellStyle() RenderStyle

DetectShellStyle returns detected shell rendering style.

type SplitArgument

type SplitArgument interface {
	// String returns the option's value as a string, and a boolean indicating
	// if the option was present.
	Value() (string, bool)
}

SplitArgument represents the argument value of an option that was passed using an argument separator.

type TTYInfo

type TTYInfo struct {
	// Stdin reports whether os.Stdin is a tty.
	Stdin bool
	// Stdout reports whether os.Stdout is a tty.
	Stdout bool
	// Stderr reports whether os.Stderr is a tty.
	Stderr bool
}

TTYInfo describes tty availability for standard streams.

func DetectTTY

func DetectTTY() TTYInfo

DetectTTY reports tty state for stdin/stdout/stderr in one call.

type Unmarshaler

type Unmarshaler interface {
	// UnmarshalFlag unmarshals a string value representation to the flag
	// value (which therefore needs to be a pointer receiver).
	UnmarshalFlag(value string) error
}

Unmarshaler is the interface implemented by types that can unmarshal a flag argument to themselves. The provided value is directly passed from the command line.

type Usage

type Usage interface {
	// Usage is called for commands to allow customized printing of command
	// usage in the generated help message.
	Usage() string
}

Usage is an interface which can be implemented to show a custom usage string in the help message shown for a command.

type ValueValidator

type ValueValidator interface {
	// IsValidValue returns an error if the provided string value is valid for
	// the flag.
	IsValidValue(value string) error
}

ValueValidator is the interface implemented by types that can validate a flag argument themselves. The provided value is directly passed from the command line.

type VersionFields

type VersionFields uint

VersionFields configures which metadata fields are rendered by WriteVersion.

const (
	// VersionFieldFile is executable path/name (`os.Args[0]`).
	VersionFieldFile VersionFields = 1 << iota
	// VersionFieldVersion is module/application version.
	VersionFieldVersion
	// VersionFieldCommit is VCS revision (commit SHA).
	VersionFieldCommit
	// VersionFieldBuilt is VCS revision time.
	VersionFieldBuilt
	// VersionFieldURL is repository URL.
	VersionFieldURL
	// VersionFieldPath is main package path from build info.
	VersionFieldPath
	// VersionFieldModule is main module path from build info.
	VersionFieldModule
	// VersionFieldModified is dirty tree marker from build info.
	VersionFieldModified
	// VersionFieldGoVersion is Go toolchain version used for build.
	VersionFieldGoVersion
	// VersionFieldTarget is build target in GOOS/GOARCH form.
	VersionFieldTarget
	// VersionFieldLicense is the application license identifier.
	// Not auto-detected; set via SetVersionLicense.
	VersionFieldLicense
	// VersionFieldAuthor is the application author string.
	// Not auto-detected; set via SetVersionAuthor.
	VersionFieldAuthor
	// VersionFieldBugsURL is the bug-tracker URL.
	// Not auto-detected; set via SetVersionBugsURL.
	VersionFieldBugsURL
)

type VersionInfo

type VersionInfo struct {
	// RevisionTime is VCS revision time in UTC when available.
	RevisionTime time.Time
	// File is executable path/name (usually os.Args[0]).
	File string
	// Path is the main package path of the running binary.
	Path string
	// ModulePath is the main module path.
	ModulePath string
	// Version is the module version.
	Version string
	// Revision is VCS revision (commit SHA).
	Revision string
	// GoVersion is the Go toolchain version used for build.
	GoVersion string
	// URL is repository URL inferred from module path unless overridden.
	URL string
	// GOOS is build target operating system.
	GOOS string
	// GOARCH is build target architecture.
	GOARCH string
	// License is the application license identifier (e.g. "MIT", "Apache-2.0").
	// Not auto-detected; set via SetVersionLicense.
	License string
	// Author is the application author string.
	// Not auto-detected; set via SetVersionAuthor.
	Author string
	// BugsURL is the bug-tracker URL.
	// Not auto-detected; set via SetVersionBugsURL.
	BugsURL string
	// Modified reports whether source tree was dirty at build time.
	Modified bool
}

VersionInfo represents build/version metadata of the running binary.

func ReadVersionInfo

func ReadVersionInfo() VersionInfo

ReadVersionInfo reads build metadata of the running binary.

Directories

Path Synopsis
examples
advanced command
Package main demonstrates advanced parser features.
Package main demonstrates advanced parser features.
basic command
Package main demonstrates flags usage with subcommands.
Package main demonstrates flags usage with subcommands.
custom-flag-tags command
Package main demonstrates custom flag tag mapping.
Package main demonstrates custom flag tag mapping.
i18n command
Package main demonstrates full i18n wiring for flags and app messages.
Package main demonstrates full i18n wiring for flags and app messages.

Jump to

Keyboard shortcuts

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