Help us shape the future of Go! Take the 2026 Go Developer Survey

cli

package module
v0.3.0 Latest Latest
Warning

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

Go to latest
Published: Oct 21, 2026 License: MIT Imports: 29 Imported by: 0

README

PkgGoDev Continuous Integration Coverage Status

cli4g

Typed command-line applications for Go: flags, arguments, subcommands, environment values, automatic help, shell completion, and invocation-owned resources.

Install

Go 1.27.0+ is required.

go get github.com/echocat/cli4g

Quick start

package main

import (
    "context"
    "fmt"
    "os"

    cli "github.com/echocat/cli4g"
)

type options struct {
    Name     string `argument:"name" required:"true"`
    Greeting string `flag:"greeting" short:"g" default:"Hello"`
}

func main() {
    cli.NewApplication[options]("greet", "Greet someone.").
		WithHandler(greet).
		MustCreateParseAndExecute(context.Background(), nil, os.Args[1:]...)
}

func greet(_ context.Context, opts options) error {
	_, err := fmt.Printf("%s, %s!\n", opts.Greeting, opts.Name)
	return err
}
greet Ada                 # Hello, Ada!
greet -g Hey Ada          # Hey, Ada!
greet --help

The default error handler exits with 2 for input errors, 130 for cancellation, or 1 for other failures. For embedding, disable it with WithErrorHandlerEnabled(false).

Why cli4g?

  • Typed options: struct tags define inputs; handlers receive typed values.
  • Ordered lifecycle: parsing resolves and validates all selected options before initialization; handlers follow successful initialization.
  • Owned resources and cleanup: ParseAndExecute closes invocation-owned resources from child to parent, on success and returned errors—including partial initialization failures.
  • Reusable definitions: compile once, then parse independent invocations repeatedly or concurrently.
  • Profiles: select compatible flag, argument, and command variants for each parse.
  • Consistent inputs: explicit CLI/environment/default precedence and validation rules.
  • Extensible values: custom codecs support application-specific types and resources.
  • Efficient reuse: competitive runtime and allocation costs in the measured workloads.

Comparison at a glance

Qualitative ratings for the compared versions: ★★★ strong · ★★☆ moderate/partial · ★☆☆ limited · — no native support.

Capability cli4g urfave/cli Cobra Kong Go flag
Struct-tag option binding ★★★ — — ★★★ —
Definition simplicity (measured adapters)[^complexity] ★★★ ★★★ ★☆☆ ★★★ ★☆☆
Command trees and automatic help ★★★ ★★★ ★★★ ★★★ —
Custom value types ★★★ ★★★ ★★★ ★★★ ★★★
Lifecycle and resource cleanup ★★★ ★★☆ ★★☆ ★★☆ —
Compile once, isolated concurrent parses ★★★ — — — —
Per-parse schema profiles ★★★ — — — —
Shell completion ★★★ ★★★ ★★★ — —
Setup/compile + first invocation speed[^performance] ★★☆ ★★☆ ★★★ ★☆☆ ★★★
Parse/execute speed on reuse[^performance] ★★★ ★★☆ ★★★ ★☆☆ ★★★

Isolated parses keep each invocation's values independent. Resource cleanup includes rollback after partial initialization failures; hooks alone need application-managed ownership.

[^complexity]: Based on the benchmark adapters' cognitive complexity; lower is better: cli4g 1, urfave/cli 0, Cobra 14, Kong 3, Go flag 11–14. Includes handlers, reuse/reset, cleanup, and required helper methods; measures control flow rather than overall API ergonomics.

[^performance]: Based on the measured root/subcommand workloads. Setup is OneShot: definition creation/compilation plus one parse/execute and cleanup. Reuse is Reuse/100 and Reuse/10000, including amortized setup and cleanup. Native binding modes differ; Go flag is a minimal baseline with application-written command dispatch.

See benchmarks and methodology for timings, allocations, code size, and cognitive complexity.

Documentation

License

License · Contribute

Documentation

Overview

Package cli builds command-line applications with typed options, subcommands, flags, arguments, environment values, automatic help, and shell completion.

Start with NewApplication, add a handler with ApplicationRequirement.WithHandler, and run ApplicationRequirement.MustCreateParseAndExecute from main. For caller-managed errors, use ApplicationRequirement.WithErrorHandlerEnabled and ApplicationRequirement.CreateParseAndExecute.

Builder constructors

NewApplication, NewSimpleApplication, NewCommand, and NewSimpleCommand accept optional name and description strings:

app := NewSimpleApplication("app", "Example application.")
command := NewSimpleCommand("run", "Run", "the application.")
app.WithCommand(command)

NewFlag and NewArgument accept the same optional strings after their codec. The first string is the primary name; all subsequent strings form the description, joined with one space between each part. Additional strings are never aliases: add flag/command aliases with WithAliases. WithName and WithDescription can still override constructor metadata. With no strings, configure the name later; Create validates the completed definition.

Options and bindings

Use exported fields in a struct or pointer-to-struct options type:

type Options struct {
    Name    string   `argument:"name" required:"true"`
    Port    uint32   `flag:"port" short:"p" env:"PORT" default:"8080"`
    Labels  []string `flag:"label"`
    Verbose bool     `flag:"verbose" short:"v"`
}

Supported tags:

  • flag|argument=<NAME>: name an input; `|` separates flag aliases
  • short=<RUNE>: names single-rune aliases
  • description=<STRING>: displays more information for help
  • placeholder=<STRING>: define how the placeholder is displayed in help
  • env=<NAME>: names environment sources; `|` separates fallback names, in order
  • default=<VALUE>: supplies a single input token
  • required=<true|false>: demands explicit input
  • type=<NAME>: selects a named codec registered with ApplicationRequirement.WithCodec
  • visible=<true|false>: If `false`, hides a flag from default help
  • profile=<NAME>: selects profiles for an input; `|` separates alternatives

Builders offer the same inputs. Bind them explicitly with FlagRequirement.WithField or ArgumentRequirement.WithField; names alone do not bind fields. Explicit bindings override tags on that field. Tagged T or *T fields also automatically adapt codec.Value (Set/String) and encoding.TextMarshaler/TextUnmarshaler implementations on *T. Their zero value must be ready for Set/UnmarshalText. Explicit/registered codecs take precedence; codec.Value wins when both interfaces apply. Text defaults remain input strings, and UnmarshalText runs only when resolving an invocation's fresh value.

The enum:"auto|always|never" tag restricts a string/string-based field to literal choices and publishes them in help. It selects a field-local codec and cannot be combined with type. For typed alternatives, descriptions, or custom parsing, register codec.NewEnum, codec.NewMarshallerEnum, or codec.NewValueEnum instead. Custom codecs can publish their complete valid set through codec.Enum[R].

Input rules

  • Flags accept `--name=value`, `--name value`, short flags, and short clusters.
  • Bare bool flags mean true; use `--verbose=false` for false.
  • Slice flags collect one element per occurrence, preserving order and duplicates.
  • Slice arguments collect remaining values and must be last.
  • Map flags collect one key=value pair per occurrence; duplicate keys are errors.
  • Map arguments collect remaining pairs and must be last. Map helpers use string keys.
  • Use `--` before positional values starting with `-`, including negative numbers.
  • Subcommands are selected before the first positional value; flags are inherited.

Flag precedence is CLI, environment, declared default, options factory, zero. Arguments omit the environment step. CLI slices and maps replace defaults/factory values. Inputs are not shell-split or CSV-split. Required inputs cannot have defaults; factory values do not satisfy them. Required parent arguments cannot precede subcommands. See FlagRequirement, ArgumentRequirement, and ParseOpts.

Commands and parent options

Add typed commands with NewCommand and ApplicationRequirement.WithCommand. An application or command without its own handler requires a subcommand when it has active children. An incomplete path is a validation error before options creation; the default error handler shows the target's help and exits with 2. Explicit --help exits successfully. A node with its own handler can be invoked directly, and a node without active children can be used for parsing alone. A child can borrow an exported struct pointer using parent:"application" or parent:"matchingType". MatchingType picks the nearest selected ancestor of the exact Go type. Borrowed options remain parent-owned; never close them in the child. Anonymous parent fields must not promote Validate, Initialize, or Close methods. Use ApplicationFromContext, CommandFromContext, or Command.OptionsFrom to read the current typed options. NewApplication defaults to seven subcommand levels. WithMaxCommandDepth sets an explicit uint8 limit; zero permits only the application. Create checks all definitions, including inactive profiles. Sibling counts are not limited. Parse scratch capacity follows the actual compiled depth and token count, rather than reserving the configured maximum for every invocation.

Profiles

Assign inputs with profile:"A|B" or FlagRequirement.WithProfiles and ArgumentRequirement.WithProfiles; use CommandRequirement.WithProfiles for commands. ParseOpts.Profiles is the only profile-selection mechanism. A definition without assignments is always active within its active parent; otherwise any selected matching profile activates it once. Child commands do not activate ancestors: a B child under an A parent requires both A and B.

Create rejects conflicting profile-free or overlapping-profile definitions. Disjoint variants may use the same name with different types and defaults; selecting a conflicting combination is a parse error, even with --help or no input for that definition. Unknown profiles also fail before scanning tokens. Inactive definitions do not participate in help, defaults, environment lookup, required checks, decoding, or resource acquisition. Active positional arguments consume inputs in declaration order without gaps; Argument(index) retains the stable complete-definition index, not the filtered input position.

Application.Profiles lists all known profiles alphabetically, including commands and descendants; Application.ContainsProfile checks exact names. Container Flags and Commands list every variant. Flag, ShortFlag and Command find only profile-free definitions; their OfProfile counterparts find explicit assignments without fallback. FindCommandOfProfile provides typed path access. Invocations expose the values and help metadata of their own selected schema, allowing concurrent parses with different selections on the same application. Invocation.Profiles and Invocation.ContainsProfile expose the invocation's selected profiles. ProfilesFromContext and ContextContainsProfile make this selection available throughout parsing and execution, including factories, decoding, help, and error callbacks.

Shell completion

ApplicationRequirement.WithCompletion is an opt-in shortcut. True assigns the current DefaultCompletionCommand and DefaultCompletionRequestCommandName; false clears both configuration fields, including custom values. There is no additional enabled state and Create never fills empty values from defaults. The standard engine derives suggestions from the existing CLI definition. Users install a native adapter once, without editing their shell configuration:

tool completion install bash
tool completion install fish
tool completion install nu
tool completion install powershell
tool completion install zsh

Bash 4.4+ uses the bash-completion package's on-demand loader. Nushell 0.114+ uses its user autoload directory on the next interactive startup. PowerShell 5.1+ registers a native argument completer through static dot-source blocks in the installed pwsh/powershell hosts' CurrentUserAllHosts profiles. The installer discovers those paths without loading profiles, preserves existing profile content and encoding, and writes a UTF-8-with-BOM adapter below the first profile's cli4g-completions directory. Both Windows PowerShell and PowerShell 7 are configured when installed; install again after adding another host. Existing execution policies apply. No application process runs when the adapter is loaded. Source the installed file (dot-source it in PowerShell) to activate it in an existing session. For packaging, supply a directory after the shell name or use Application.CompletionScript to obtain an adapter without installing it. A shell subcommand also prints it to stdout:

tool completion bash

Bash quotes suggestions as literal arguments, including values containing dollar signs, backticks, quotes and whitespace. This applies to native path suggestions as well. Readline still controls menus and word replacement; it does not expand suggestion values or treat non-path suggestions as directories. Simple single/double quotes are supported; completion inside an ANSI-C quoted word is suppressed because the request lexer does not decode its escapes. After an adapter implementation update, rerun the install command and source the generated file (or start a new shell). Ordinary application schema updates do not require reinstalling adapters.

Nushell's command-wide completion input, verified with Nu 0.114.1, stops at the cursor. Dependencies must therefore precede the value being completed:

tool --context cluster-b --namespace cl<Tab>

Completing an earlier argument preserves later arguments in the editor, but those later arguments are not visible to the provider. For example, completing --namespace before a later --context cannot use that context; an available environment/default dependency is used instead, or the dependency is absent. The adapter does not reconstruct missing input from commandline/get-cursor, whose REPL state can be stale during completion, and does not modify global keybindings to capture the buffer. This is a native Nu input limitation, not a restriction of Application.Complete or its protocol: callers supplying words after the cursor retain the full dependency context.

An explicit PowerShell installation directory writes only the adapter and does not edit profiles. PowerShell sends literal AST values and UTF-8 byte cursor offsets through an ASCII-safe Base64/JSON transport, including on Windows PowerShell 5.1's legacy native pipeline. Tokens after the cursor remain available for dependencies. Variables and expressions are not evaluated to collect values. Candidates include descriptions and use literal quoting, including legacy native argument escaping. PowerShell removes even a quoted scalar --% during native argument binding, so this literal value uses the fixed expression @('--%'). Its singleton array passes exactly one native argument without enabling verbatim handling of later arguments. The collector recognizes only that exact generated array form as literal --%; other expressions remain unevaluated dependency data. Paths normally use PowerShell's filename completer; literal Unix colon filenames use filesystem enumeration because the provider interprets colons as drives. Candidate order is preserved. The user's PSReadLine binding determines whitespace insertion; the adapter does not change that binding. See Application.InstallCompletion and CompletionProtocolVersion for details.

Zsh 5.8+ uses its native compinit/fpath autoloading. The default installer writes _Name below XDG_DATA_HOME/zsh/site-functions (otherwise ~/.local/share/zsh/site-functions), and appends a static block to .zshrc in Zsh's startup directory. That directory is discovered from the installed zsh, including non-exported ZDOTDIR settings in .zshenv. Discovery runs only during installation. The block extends fpath, initializes compinit if needed, and registers an autoload function; it starts neither the application nor the adapter at shell startup. Existing user content, widgets and completion styles are preserved. Explicit directories write only the autoload file for packaging. Source that file after compinit for an existing session. Run installation again after relocating the startup directory.

The Zsh adapter uses native words and cursor prefix/suffix fragments, including unfinished quotes and arguments after the cursor. It never evaluates expressions while collecting dependency values. Candidates carry descriptions; compadd provides literal quoting and NoSpace/KeepOrder, and _files handles native paths. ZLE settings control whether completion operates inside a word (COMPLETE_IN_WORD) and how menu selection inserts spaces. The adapter retains those settings.

Fish 3.6+ autoloads Name.fish from its user completion directory, normally XDG_CONFIG_HOME/fish/completions or ~/.config/fish/completions. The installer discovers __fish_config_dir with fish --no-config, only during installation. It leaves config.fish and universal variables untouched. Source the returned file to refresh an existing session that already loaded command completions. Explicit directories support packaging and custom fish_complete_path entries. Loading the adapter starts no application process; only Name's completion definitions are replaced, with no changes to global widgets or other commands.

Each Fish query transmits the complete current process and its cursor prefix, preserving empty/multiline arguments, simple quotes/escapes, and arguments after the cursor. Variables, globs and substitutions remain literal dependency data; they are never evaluated by the collector. Fish quotes inserted candidates, displays descriptions, completes paths natively, and preserves KeepOrder (the engine sorts other candidate results). Values use NUL-framed records; tabs in candidate values are omitted because Fish reserves the tab for descriptions, and multiline descriptions are displayed on one line. Fish controls whitespace: it omits spaces after punctuation such as "=" and "/", but its public completion API cannot force NoSpace on arbitrary values. Fish also retains native word- suffix matching when completing inside a token. See Application.CompletionScript and CompletionProtocolVersion for the adapter and transport contracts.

ApplicationRequirement.CompletionCommand is an ordinary CommandRequirementLike. Nil means absent. Create compiles it alongside Commands without modifying the builder list or shared default. It uses the same parsing, inherited inputs, validation, initialization, execution, cleanup, profiles, help and depth limits as every other command. Parent required flags also apply; required positional parent arguments cannot coexist with subcommands. Commands/Command and typed FindCommand expose the actual compiled command, not a metadata substitute.

DefaultCompletionCommand is a replaceable, preconfigured command requirement. NewCompletionCommand creates a fresh version for per-application changes:

WithCompletion(true).
    WithCompletionCommand(NewCompletionCommand().WithName("shells"))

Supply any custom CommandRequirement through WithCompletionCommand instead. CompletionApplicationFromContext gives ordinary custom handlers access to the renderer, installer and direct completion API without knowing the root options type. Configure global defaults before use, without concurrent modification; already compiled applications keep independent definitions.

ApplicationRequirement.CompletionRequestCommandName independently configures the special adapter entry. Empty disables it. WithCompletion(true) assigns the current replaceable DefaultCompletionRequestCommandName (initially "__complete"). This name is not registered as a Command and never appears in Commands(), help or suggestions. It must not collide with any root command/alias, including inactive profiles. Keep it stable across upgrades, or regenerate adapters/provide a compatibility entry point when changing it. Public command changes do not affect installed adapters; the wire protocol is independent of either name.

Adapters contain no flags, commands, enum snapshots, or version-specific binary paths. At completion time they query the currently selected executable through CompletionProtocolVersion; replacing the binary therefore updates suggestions automatically. Sourcing an adapter starts no application process. Each query starts one process; startup code and Go init functions remain the application's responsibility. Query callbacks receive CompletionQueryTimeout as a cooperative deadline. cli4g does not maintain a background service or persistent result cache.

Commands, aliases, visible flags, enum values, bools, and file inputs are completed automatically. Noncumulative flags already used are omitted from name suggestions. Slice codecs delegate to their element codec, and map codecs delegate the value after key=. codec.Completer adds context-dependent values, such as namespaces selected by --kubeconfig and --context. Its input contains canonical flag occurrence maps, arguments by name and position, command scopes, active profiles, and the current word/cursor target. Neither name completion nor metadata inspection invokes value completers. Providers return unquoted tokens and optional descriptions; shell adapters own quoting and display. The regular options structs and command definitions are the single CLI schema; the built-in shell entry point constructs the completion context automatically. To attach a function to an existing codec, use codec.WithCompletionHandler:

WithCodec(codec.WithCompletionHandler(codec.NewString(), completeNamespaces), "namespace")

A type:"namespace" tag selects that codec for the regular field. No custom codec wrapper type or ToRaw implementation is needed. For builder-defined inputs, FlagRequirement.WithCompletionHandler and ArgumentRequirement.WithCompletionHandler customize one flag/argument without changing its parsing codec. Their handler runs first; Handled=false delegates to the codec, then enum/bool/path defaults. See CompletionHandler.

Application.Complete is the direct Go API. It accepts a CompletionRequest and ParseOpts, tolerates unknown and incomplete input, and never constructs options or runs their lifecycle. Raw CLI tokens remain available even if they would not decode. Known flags delimit missing required values for recovery; literal option-looking values can be supplied inline. Other complete arguments after the cursor remain visible when supplied by the adapter/caller. codec.CompletionInput.Effective lazily reads dependencies with CLI > environment > declared-default precedence and identifies their source. Factory-only values are unavailable. Defaults and other inputs are not resolved to runtime resources. Shell expressions/substitutions are not executed to discover dependency values.

Direct API errors are returned without invoking the application's error handler. Adapter queries turn failures into empty answers so terminal editing remains usable. Providers doing I/O must honor cancellation and close their own request resources. A provider-side in-memory cache does not span per-query processes; persistent caches must account for all configuration/context dependencies.

Only a nonempty configured request name is recognized specially in the first token by Parse and ParseAndExecute. Parse returns a metadata-only invocation; Execute serves the query using context streams, without constructing, validating or initializing ordinary options or running business handlers. Use -- before a literal request-name root argument. Standard --help retains its usual bypass behavior for the ordinary public command. The direct Complete API remains available regardless of either configuration field.

Lifecycle and errors

Application.Parse resolves inputs, then validates and initializes options. Invocation.Execute runs handlers from application to selected leaf. Always close a successful Invocation, then its Application. Application.ParseAndExecute manages invocation cleanup for you. Pointer options retain field assignments; struct callbacks receive copies. See Validatable, Initializable, and ApplicationRequirement.WithCloseHandler.

Mark invalid user input with NewValidationError or NewValidationErrorf. Other errors remain operational. DefaultErrorHandler writes to context stderr and exits with 2 for invalid input, 130 for cancellation, or 1 for other errors. Disable responses when embedding the library: os.Exit does not run caller defers. Built-in codec failures describe the required value without echoing the input. Use NewValidationError("an integer expected", cause) to retain a diagnostic cause without appending its text. Error displays only the message; errors.Is and errors.As still traverse the causes. Unmarked codec/validation failures receive neutral messages and retain their original classification. Warning: author-supplied ValidationError messages are displayed verbatim and must not contain input or confidential data. NewValidationErrorf with %w does include the cause text; prefer separate messages and causes for sensitive input. ParseAndExecute prepares standard streams once for the entire managed operation. The invocation and profile metadata share one immutable context overlay; early parse contexts retain their own profile snapshot.

Context streams

Supply borrowed streams with ContextWithStdio(ctx, stdin, stdout, stderr). Consumers use StdioOfContext, StdinOfContext, StdoutOfContext or StderrOfContext. Print, Printf and Println write to context stdout; their Err* counterparts write to context stderr. Missing output is a no-op. NewApplication enables process-stdio fallback when no streams are set; disable it with ApplicationRequirement.WithFallbackToStdio. Explicit streams always take precedence, including nil stdin/stdout, and are never closed by the library. Nil stderr uses stdout; pass io.Discard to suppress stderr. Without context streams or fallback, the getters return nil. Pass the same context to Parse and Execute when calling them separately: file aliases resolve during Parse and cannot be replaced later by Execute. Built-in help/error handlers use context stderr, or io.Discard when missing. Their WithOutput methods can select an explicit writer instead.

Help and files

--help/-h is enabled by default and reserves those names. Help stops scanning immediately, skips options creation, and runs only the help handler. Earlier syntax errors and invalid displayed defaults still fail. Customize with ApplicationRequirement.WithHelpHandler and NewTemplatedHelpHandler. Argument value labels preserve the declared name and case: <userName>. Flag values use --flag=<value>; the generated value name is the final lowercased word, splitting at '.', '-', '_' and case boundaries (log.colorMode -> <mode>). Explicit placeholder tags or WithPlaceholder text keep their case and take precedence; surrounding <...> are added once. Optional arguments use [<name>], variadic values <name>..., and optional single flag values --flag[=<value>]. Template output is automatically aligned and word-wrapped. Tabs separate columns; blank lines separate sections, and nested indentation gets its own column widths. Terminal width is read from the selected output for each help rendering; files, pipes and other unsuccessful queries fall back to 80. TemplatedHelpHandlerRequirement.WithWidth selects a fixed width; TemplatedHelpHandlerRequirement.WithFormatting disables layout for exact template output. Width counts Unicode code points, not terminal cell widths; unbreakable words/labels may exceed it. CRLF is normalized to LF by formatting.

File tags fileMode:"read|write|readWrite" and allowSpecial:"true" configure *os.File inputs. Invocations own codec-opened handles. Write modes create missing files but do not truncate existing files. With allowStdio:"true", "-"/"stdin" in read mode borrow context stdin, and "-"/"stdout" in write mode borrow context stdout. These file inputs require non-nil *os.File streams; arbitrary readers and writers can be used directly through the context helpers. Invocations never close these streams. Use ./stdin, ./stdout or ./- for literal paths with opt-in enabled. Use the codec package for explicit append/truncate policies, dates, adapters, and custom value types.

Index

Examples

Constants

View Source
const CompletionProtocolVersion = 1

CompletionProtocolVersion identifies the stable adapter protocol. Its decimal representation follows the configured hidden request command (by default "__complete"). Version 1 has these transports:

  • __complete 1 bash POINT LINE CURRENT: POINT is a byte offset into the Bash input LINE. CURRENT is Bash's current word after COMP_WORDBREAKS. Simple shell quotes/escapes and command separators are recognized without evaluating expansions, substitutions or shell code. Output is NUL-delimited: "1", path mode (0 none, 1 files, 2 directories), NoSpace (0/1), KeepOrder (0/1), path insertion prefix, path search prefix, Readline replacement prefix to remove from composed path suggestions, then candidate values. All strings are unquoted; the adapter handles Readline word breaks and native paths.
  • __complete 1 nu: stdin contains exactly one JSON CompletionRequest, limited to 1 MiB. An optional raw=true additionally removes simple Nu literal quoting from span tokens; it never evaluates expressions. stdout is a JSON codec.CompletionResult. Input excludes the executable. The Nu 0.114.1 adapter receives only arguments before the cursor; dependency flags must precede the value being completed. The protocol itself accepts later words when supplied by a caller.
  • __complete 1 powershell: the same JSON request/result as nu, without raw token normalization, each wrapped in standard Base64. The decoded request is limited to 1 MiB. ASCII-only transport preserves Unicode even with Windows PowerShell 5.1's legacy native-pipeline encoding. The adapter sends literal AST values, keeps arguments after the cursor, and converts UTF-16 cursor positions to UTF-8 byte offsets without evaluating expressions.
  • __complete 1 zsh WORD PREFIX WORDS...: WORD is the zero-based current word index; WORDS excludes the executable but includes the full current word and tokens after the cursor. PREFIX is its unquoted cursor prefix, whose UTF-8 byte length is the offset. Output is NUL-delimited: "1", path mode (0 none, 1 files, 2 directories), NoSpace (0/1), KeepOrder (0/1), FilePrefix, FileInput, then alternating candidate values and descriptions. Zsh handles quoting and native paths. Empty words are preserved as native process arguments.
  • __complete 1 fish PREFIX LINE: LINE is Fish's complete current process; PREFIX is its raw portion before the cursor. Both include commandline's final printing newline, which the receiver removes exactly once. This preserves actual trailing newlines and derives UTF-8 byte offsets directly. Simple Fish quotes/escapes are decoded without evaluating expressions. Output uses the same NUL fields as zsh. Fish omits candidates containing tabs, which its completion value/description interface cannot represent.

New transports may be added without changing existing transports. Query errors become authoritative empty responses with no diagnostics; direct Complete callers retain errors. Adapters should invoke the currently selected binary, never a path/version captured at installation, and only on completion requests.

View Source
const CompletionQueryTimeout = 500 * time.Millisecond

CompletionQueryTimeout is the cooperative deadline applied to shell queries. Direct Complete callers choose their own deadline. Network clients and custom completers must honor cancellation; Go cannot forcibly stop an arbitrary user callback. Startup and code run before cli4g are outside this budget.

View Source
const DefaultApplicationHelpTemplate = `` /* 432-byte string literal not displayed */

DefaultApplicationHelpTemplate renders complete application help.

View Source
const DefaultArgumentHelpTemplate = `` /* 292-byte string literal not displayed */

DefaultArgumentHelpTemplate renders one positional argument.

View Source
const DefaultCommandEntryHelpTemplate = `  {{.Label}}	{{.Description}}
`

DefaultCommandEntryHelpTemplate renders one available command.

View Source
const DefaultCommandHelpTemplate = DefaultApplicationHelpTemplate

DefaultCommandHelpTemplate renders complete selected-command help.

View Source
const DefaultFlagHelpTemplate = `` /* 344-byte string literal not displayed */

DefaultFlagHelpTemplate renders one own or inherited flag.

View Source
const DefaultUsageHelpTemplate = `Usage:
  {{.Usage}}
`

DefaultUsageHelpTemplate renders invocation syntax.

Variables

View Source
var (
	ErrInvocationNotReady = errors.New("invocation is not initialized")
	ErrInvocationClosed   = errors.New("invocation is already closed")
)
View Source
var DefaultCompletionRequestCommandName = "__complete"

DefaultCompletionRequestCommandName is the special protocol entry selected by WithCompletion(true). Replace it before configuring applications, without concurrent modification. Empty disables the request entry. Installed adapters depend on the captured name, independently of the public command.

View Source
var ErrApplicationClosed = errors.New("application is closed")
View Source
var ErrValidation = codec.ErrValidation

ErrValidation is the codec package's shared invalid-input sentinel.

Functions

func ApplicationFromContext

func ApplicationFromContext[O any](ctx context.Context) (O, bool)

ApplicationFromContext returns the current root options, without cloning or resolving anything. Missing invocation/options or a wrong type returns false. Reference fields share data with the invocation; struct options are copied.

func CommandFromContext

func CommandFromContext[O any](ctx context.Context, path ...string) (O, bool)

CommandFromContext returns the current command's options when path is empty. An explicit path starts at the application and must identify a command selected in this invocation. It follows the selected stack, including profile-specific variants and ancestors. Aliases are accepted; no options are created by this getter.

func ContextContainsProfile added in v0.2.0

func ContextContainsProfile(ctx context.Context, profile string) bool

ContextContainsProfile reports whether profile was selected for the current parse or invocation. Missing context data returns false. Names are exact and case-sensitive; profile-free definitions do not add implicit selections.

func ContextWithStdio added in v0.1.3

func ContextWithStdio(ctx context.Context, stdin io.Reader, stdout, stderr io.Writer) context.Context

ContextWithStdio supplies borrowed streams. Nil stderr uses stdout; explicit context streams suppress process-stdio fallback, including nil stdin/stdout.

func ErrPrint added in v0.1.3

func ErrPrint(ctx context.Context, args ...any) error

ErrPrint writes to context stderr like fmt.Print. Missing output is a no-op.

func ErrPrintf added in v0.1.3

func ErrPrintf(ctx context.Context, format string, args ...any) error

ErrPrintf writes to context stderr like fmt.Printf. Missing output is a no-op.

func ErrPrintln added in v0.1.3

func ErrPrintln(ctx context.Context, args ...any) error

ErrPrintln writes to context stderr like fmt.Println. Missing output is a no-op.

func FlagFromContext

func FlagFromContext[V any](ctx context.Context, name string) (V, bool)

FlagFromContext returns the existing decoded value, including declared defaults and environment inputs. Factory-only fields are available through options. A present typed nil, empty string, false or zero remains found=true.

func IsValidationError

func IsValidationError(err error) bool

IsValidationError recognizes the shared sentinel through wrapping and errors.Join.

func NewValidationError

func NewValidationError(message string, causes ...error) error

NewValidationError marks invalid input with a message and diagnostic causes. Error displays only message; errors.Is and errors.As can inspect the causes. Warning: message is displayed verbatim. Authors must not include passwords, supplied input values, or other confidential data.

func NewValidationErrorf

func NewValidationErrorf(format string, args ...any) error

NewValidationErrorf formats an input failure, preserving causes supplied with %w. Warning: %w also displays the cause text. Use NewValidationError with a separate message and causes to avoid exposing input or other confidential data.

Example
package main

import (
	"fmt"

	cli "github.com/echocat/cli4g"
)

func main() {
	err := cli.NewValidationErrorf("port must be positive")
	fmt.Println(cli.IsValidationError(err))
	fmt.Println(err)
}
Output:
true
port must be positive

func Print added in v0.1.3

func Print(ctx context.Context, args ...any) error

Print writes to context stdout like fmt.Print. Missing output is a no-op.

func Printf added in v0.1.3

func Printf(ctx context.Context, format string, args ...any) error

Printf writes to context stdout like fmt.Printf. Missing output is a no-op.

func Println added in v0.1.3

func Println(ctx context.Context, args ...any) error

Println writes to context stdout like fmt.Println. Missing output is a no-op.

func ProfilesFromContext added in v0.2.0

func ProfilesFromContext(ctx context.Context) (iter.Seq[string], bool)

ProfilesFromContext returns the selected profiles of the current parse or invocation, alphabetically and without duplicates. It is available throughout parsing, including options factories and decoding, and in lifecycle, help, execution, and error callbacks. A parse with no selected profiles returns an empty sequence and true. Missing context data returns an empty sequence and false. Parse errors expose the requested selection, including unknown names.

func StderrOfContext added in v0.1.3

func StderrOfContext(ctx context.Context) io.Writer

StderrOfContext returns the operation's stderr without implicit fallback.

func StdinOfContext added in v0.1.3

func StdinOfContext(ctx context.Context) io.Reader

StdinOfContext returns the operation's stdin without implicit fallback.

func StdioOfContext added in v0.1.3

func StdioOfContext(ctx context.Context) (io.Reader, io.Writer, io.Writer)

StdioOfContext returns stdin, stdout and stderr without implicit process fallback.

func StdoutOfContext added in v0.1.3

func StdoutOfContext(ctx context.Context) io.Writer

StdoutOfContext returns the operation's stdout without implicit fallback.

Types

type Application

type Application[O any] struct {
	// contains filtered or unexported fields
}

Application is a reusable CLI definition with options of type O. Obtain it from ApplicationRequirement.Create; close invocations before Application.Close. Concurrent parses require concurrent-safe user callbacks.

func (Application) Argument

func (this Application) Argument(index int) (*Argument[any, any], bool)

Argument returns the definition at index, whether or not an invocation has a value for it. Invocation.Argument uses this same definition index.

func (Application) Arguments

func (this Application) Arguments() iter.Seq[*Argument[any, any]]

func (*Application[O]) Close

func (this *Application[O]) Close() error

Close prevents further parsing and execution, including through commands. Close all invocations first. Repeated calls are safe; metadata stays readable.

func (*Application[O]) CloseOptions

func (this *Application[O]) CloseOptions(options O) error

CloseOptions runs the close callback and options' Close method, including for partially initialized caller-owned options.

func (Application) Command

func (this Application) Command(name string) (CommandLike, bool)

Command finds only commands without profile assignments.

func (Application) CommandOfProfile added in v0.2.0

func (this Application) CommandOfProfile(name, profile string) (CommandLike, bool)

CommandOfProfile finds a command explicitly assigned to profile, by name or alias. It does not fall back to commands without profile assignments.

func (Application) Commands

func (this Application) Commands() iter.Seq[CommandLike]

func (*Application[O]) Complete added in v0.3.0

func (this *Application[O]) Complete(ctx context.Context, opts *ParseOpts, request CompletionRequest) (codec.CompletionResult, error)

Complete provides context-aware suggestions without creating, parsing, validating, initializing, or executing application options. It uses the active schema selected by opts, including inherited flags and path-specific codecs. Unknown or incomplete input is retained best-effort, not reported as an input error. Schema/profile errors, invalid coordinates and provider errors return directly, without invoking the application's error handler.

Codecs may implement codec.Completer. They receive explicit input maps, named and ordered arguments, command scopes, the target, and lazy environment/default access through codec.CompletionInput.Effective. Enum, bool, file and collection codecs work automatically. Name completion never invokes value completers. An explicit flag/argument CompletionHandler takes precedence over its codec; Handled=false delegates to the next completion source. Suggestions are case-sensitive prefix matches, deduplicated and sorted unless KeepOrder is requested. Candidates are whole, unquoted replacement words. The caller owns ctx's deadline; provider callbacks must honor cancellation. Calls are independent and concurrent-safe when user callbacks are safe.

Example
package main

import (
	"context"
	"fmt"

	cli "github.com/echocat/cli4g"
	"github.com/echocat/cli4g/codec"
)

// A real implementation could ask a Kubernetes client using the same ctx.
func namespaceSuggestions(ctx context.Context, input codec.CompletionInput) (codec.CompletionResult, error) {
	cluster, _, err := input.Effective.Flag(ctx, "context")
	if err != nil {
		return codec.CompletionResult{}, err
	}
	name := "default"
	if len(cluster.Values) > 0 {
		name = cluster.Values[len(cluster.Values)-1]
	}
	// Explicit raw occurrences are also available as input.Flags["context"].
	// input.Arguments and input.Positionals describe the selected command's args.
	return codec.CompletionResult{
		Handled: true,
		Candidates: []codec.CompletionCandidate{
			{Value: name + "-apps", Description: "Application namespace."},
			{Value: name + "-system", Description: "System namespace."},
		},
	}, ctx.Err()
}

func main() {
	app := cli.NewApplication[struct {
		Context   string `flag:"context" default:"development"`
		Namespace string `flag:"namespace" type:"namespace"`
	}]("tool").WithCompletion(true).
		WithCodec(codec.WithCompletionHandler(codec.NewString(), namespaceSuggestions), "namespace").MustCreate()
	defer func() { _ = app.Close() }()

	// A cursor can precede other dependency flags. No options are initialized.
	result, err := app.Complete(context.Background(), nil, cli.CompletionRequest{
		Words: []string{"--namespace", "pro", "--context", "production"},
		Word:  1, Offset: 3,
	})
	if err != nil {
		panic(err)
	}
	for _, candidate := range result.Candidates {
		fmt.Println(candidate.Value, "—", candidate.Description)
	}
}
Output:
production-apps — Application namespace.
production-system — System namespace.

func (*Application[O]) CompletionCommand added in v0.3.0

func (this *Application[O]) CompletionCommand() CommandLike

CompletionCommand returns the ordinary compiled command configured through ApplicationRequirement.CompletionCommand, or nil when none was configured. It is the same definition returned by Commands/Command and remains readable after Close, like all other command metadata.

func (*Application[O]) CompletionCommandName added in v0.3.0

func (this *Application[O]) CompletionCommandName() string

CompletionCommandName returns the configured command's primary name, or empty when absent. The name belongs to the command definition, not a separate setting.

func (*Application[O]) CompletionRequestCommandName added in v0.3.0

func (this *Application[O]) CompletionRequestCommandName() string

CompletionRequestCommandName returns the captured special request name. Empty means disabled. No implicit default is substituted by Create.

func (*Application[O]) CompletionScript added in v0.3.0

func (this *Application[O]) CompletionScript(shell CompletionShell) (string, error)

CompletionScript generates a small, schema-independent adapter for Name. It does not run the application at shell startup. Completion requests consult the current executable using the captured CompletionRequestCommandName. A binary update needs no adapter regeneration while protocol v1 is supported. Configure that entry directly or use WithCompletion(true). An empty request name returns an error rather than producing an unusable adapter.

Bash users can source the script; bash-completion can load an installed script on demand. Nushell users can source it or use its exported extern definition; InstallCompletion writes an autoload script. The Nu adapter declares only a free-form external signature, so changing flags/commands never leaves a stale signature. It preserves native execution and does not replace the user's global external completer. Its parameter accepts both legacy span lists and newer named place records. It quotes literal candidates and preserves native Nu path quoting; Nu controls whitespace insertion. Nu 0.114.1 supplies only the command prefix before the cursor: dependency flags must precede the value being completed. Later arguments remain in the editor but are unavailable to the provider. The adapter does not read commandline/get-cursor, whose REPL state can be stale during completion, or change global keybindings to capture a full buffer. This shell limitation does not restrict Complete callers supplying all input words.

Bash honors NoSpace and KeepOrder. Bash explicitly quotes provider values and native paths as literal arguments; Readline does not reinterpret suggestions as filenames or shell expansions. Simple unfinished single/double quotes and Readline word breaks are retained. Completion inside an ANSI-C quoted word is suppressed rather than treating its backslash escapes as simple single-quote syntax.

PowerShell registers a native argument completer, including the .exe spelling. Dot-source the script or use InstallCompletion for persistent profile loading. Literal AST strings and escapes are decoded without evaluating variables, expressions or substitutions. Arguments after the cursor remain available to context-aware providers. Candidates are quoted as literal native arguments and carry descriptions; path completion uses PowerShell's own filename completer (filesystem enumeration for literal Unix colon paths). The reserved literal --% uses a fixed singleton-array expression so native binding does not drop it or change later arguments. That exact generated AST form is decoded as literal data in subsequent requests, without evaluation. Returned order is retained; the user's PSReadLine completion binding controls space insertion, so NoSpace does not change that binding. Scripts use UTF-8 with a BOM for Windows PowerShell 5.1 and an ASCII-only request/response transport.

Zsh uses compinit/fpath autoloading or can source the adapter after compinit. Its native tokenizer supplies words and cursor prefixes; simple quoting is removed without evaluating expressions. All argument words, including those after the cursor, are preserved. compadd quotes candidates, shows descriptions, and honors NoSpace/KeepOrder; _files provides native path completion. No global widgets, styles, aliases or external completers are replaced.

Fish autoloads Name.fish when the command is first completed, or users can source the adapter. It replaces only Name's completion definitions. Each query sends the complete current process and its cursor prefix; simple Fish quoting and escapes are decoded without evaluating substitutions, variables or globs. Empty/multiline arguments and tokens after the cursor are retained. Fish quotes literal candidates, displays descriptions, preserves the engine's sorted or KeepOrder result, and completes paths natively. Fish controls space insertion: punctuation such as "=" or "/" suppresses a space, but its public completion API cannot force NoSpace for arbitrary values. Its native suffix matching may reject suggestions that conflict with text after the cursor inside the same token. Candidate tabs cannot be represented by Fish's value/description interface and are omitted; multiline values use NUL-framed records, and descriptions are rendered on one line. Other shells' transport formats are independent.

Bash recognizes simple quotes, escapes, and separators but deliberately does not evaluate shell substitutions or expansions while collecting dependency values. Applications requiring already-expanded values may call Complete with their own tokenized CompletionRequest. Names containing NUL/newlines are rejected.

func (*Application[O]) ContainsProfile added in v0.2.0

func (this *Application[O]) ContainsProfile(profile string) bool

ContainsProfile reports whether an exact, case-sensitive profile is known.

func (*Application[O]) Description

func (this *Application[O]) Description() string

Description returns the help description.

func (*Application[O]) Execute

func (this *Application[O]) Execute(ctx context.Context, options O) error

Execute runs the application handler with caller-owned options. It does not parse, validate, initialize, or close those options. Use Application.ParseAndExecute for the complete CLI lifecycle.

func (Application) Flag

func (this Application) Flag(name string) (*Flag[any, any], bool)

Flag finds only flags without profile assignments, by name or alias.

func (Application) FlagOfProfile added in v0.2.0

func (this Application) FlagOfProfile(name, profile string) (*Flag[any, any], bool)

FlagOfProfile finds an explicitly assigned flag, with no profile-free fallback.

func (Application) Flags

func (this Application) Flags() iter.Seq[*Flag[any, any]]

func (*Application[O]) Initialize

func (this *Application[O]) Initialize(ctx context.Context, options O) error

Initialize runs options methods and callbacks like Parse. Use pointer options when assignments must be retained by the caller; struct arguments are copies.

func (*Application[O]) InstallCompletion added in v0.3.0

func (this *Application[O]) InstallCompletion(ctx context.Context, shell CompletionShell, directory string) (string, error)

InstallCompletion installs an adapter and returns its path. Empty directory chooses Bash's first BASH_COMPLETION_USER_DIR (otherwise XDG_DATA_HOME or ~/.local/share, then bash-completion/completions), or asks the installed nu for its first user-autoload directory. The Nu discovery process runs only during installation. Supply directory explicitly for packaging or custom shell homes.

The operation is idempotent, uses an atomic replacement where supported by the OS, and refuses to overwrite a file without cli4g's generated header. It creates directories with 0755 subject to the umask and sets scripts to 0644. It does not modify .bashrc/config.nu or install bash-completion itself. An existing bash-completion loader can discover the file at the next completion; Nu autoloads it on its next interactive startup. Source the returned file for the current session. Files contain no application schema or user input values. Call this again to update the adapter implementation, not for ordinary binary updates. The ordinary standard install command uses its invocation's context streams.

For PowerShell, an empty directory discovers the CurrentUserAllHosts profiles of installed pwsh and powershell hosts (without loading profiles), writes one adapter below the first profile's cli4g-completions directory, and appends an idempotent, static dot-source block to each discovered profile. Existing profile bytes and UTF-8/UTF-16 encoding are preserved; no application executable runs at shell startup. Both installed Windows PowerShell and PowerShell hosts are configured. New hosts need another installation. A nonempty directory writes only the .ps1 adapter, leaving profiles untouched for packaging or manual dot-sourcing. Installation respects the host's existing execution policy and requires no administrator rights.

Zsh installs _Name under XDG_DATA_HOME/zsh/site-functions (otherwise ~/.local/share/zsh/site-functions). The installed zsh discovers ZDOTDIR/HOME by reading its normal noninteractive startup files, including .zshenv, only during installation. An idempotent block is appended to .zshrc there: it extends fpath, runs compinit only if compdef is unavailable, and registers the autoload function. Application and adapter code do not execute during shell startup. Existing user content and completion styles are preserved. An explicit directory writes only the autoload file, for a packager's fpath or manual setup. Source it after compinit to activate it in an existing session.

Fish installs Name.fish in the installed fish's user configuration directory (__fish_config_dir/completions, normally XDG_CONFIG_HOME/fish/completions or ~/.config/fish/completions). Discovery runs with --no-config only during installation. Fish loads the file on demand; config.fish and universal variables are not modified. An explicit directory needs no installed fish and supports packaging/custom fish_complete_path entries. Source the file for an existing session whose command completions were already loaded.

func (*Application[O]) MaxCommandDepth added in v0.2.1

func (this *Application[O]) MaxCommandDepth() uint8

MaxCommandDepth returns the captured subcommand nesting limit; the application itself has depth 0. The metadata remains available after Close.

func (*Application[O]) MustParse

func (this *Application[O]) MustParse(ctx context.Context, opts *ParseOpts, vs ...string) *Invocation[O]

MustParse calls Application.Parse and panics on a returned error.

func (*Application[O]) MustParseAndExecute

func (this *Application[O]) MustParseAndExecute(ctx context.Context, opts *ParseOpts, vs ...string)

MustParseAndExecute calls Application.ParseAndExecute and panics on a returned error.

func (*Application[O]) Name

func (this *Application[O]) Name() string

Name returns the application's command-line name.

func (*Application[O]) Names

func (this *Application[O]) Names() []string

Names returns a new slice containing Application.Name.

func (Application) OptionsType

func (this Application) OptionsType() reflect.Type

func (*Application[O]) Parse

func (this *Application[O]) Parse(ctx context.Context, opts *ParseOpts, vs ...string) (_ *Invocation[O], err error)

Parse decodes vs, resolves values, validates options, and initializes them. Always close a successful Invocation, even when it is not executed. Failure cleans up and returns nil; the configured ErrorHandler may exit. Use ApplicationRequirement.WithErrorHandlerEnabled for caller-managed errors.

A true --help/-h stops scanning and skips options creation and initialization. A handlerless target with active subcommands requires a subcommand; otherwise Parse returns a validation error before creating options or resolving inputs. Nil opts uses the OS environment; nil ctx uses context.Background. Callbacks must honor cancellation. The definition supports repeated and concurrent parsing; each invocation owns its options and resources. Direct Execute calls from parse hooks share this operation's error boundary. Context streams are available throughout parsing and the options lifecycle. File aliases resolve now; pass the same stream context to Execute. A configured completion request name in the first token instead creates a metadata-only invocation without constructing options. The public completion command uses the ordinary lifecycle. Use -- before a literal request-name value.

Example
package main

import (
	"context"
	"fmt"

	cli "github.com/echocat/cli4g"
)

func main() {
	app := cli.NewSimpleApplication("labels").
		WithErrorHandlerEnabled(false).
		WithStringSliceFlag("label").
		MustCreate()
	defer func() {
		if err := app.Close(); err != nil {
			panic(err)
		}
	}()
	invocation, err := app.Parse(context.Background(), nil, "--label=blue", "--label=green")
	if err != nil {
		panic(err)
	}
	defer func() {
		if err := invocation.Close(); err != nil {
			panic(err)
		}
	}()
	_, labels := invocation.Flag("label")
	fmt.Println(labels)
}
Output:
[blue green]

func (*Application[O]) ParseAndExecute

func (this *Application[O]) ParseAndExecute(ctx context.Context, opts *ParseOpts, vs ...string) (err error)

ParseAndExecute parses, executes, and closes an invocation. The application remains reusable until Application.Close.

func (*Application[O]) Profiles added in v0.2.0

func (this *Application[O]) Profiles() iter.Seq[string]

Profiles lists all known profiles, including assignments on commands and their inputs, exactly once in alphabetical order. It is independent of Parse calls.

func (Application) ShortFlag

func (this Application) ShortFlag(short rune) (*Flag[any, any], bool)

ShortFlag finds only flags without profile assignments.

func (Application) ShortFlagOfProfile added in v0.2.0

func (this Application) ShortFlagOfProfile(short rune, profile string) (*Flag[any, any], bool)

ShortFlagOfProfile finds an explicitly assigned flag by its short alias.

func (*Application[O]) Validate

func (this *Application[O]) Validate(ctx context.Context, options O) error

Validate runs the options' Validate method followed by the configured callback.

type ApplicationRequirement

type ApplicationRequirement[O any] struct {
	Name        string
	Description string
	// Help enables automatic --help/-h throughout the command tree. Constructors
	// enable it by default; a zero-valued requirement has it disabled.
	Help bool
	// CompletionCommand is an optional ordinary root command, compiled alongside
	// Commands. Nil means absent; Create never substitutes a default. Configure it
	// directly or use WithCompletion(true) to select DefaultCompletionCommand.
	CompletionCommand CommandRequirementLike
	// CompletionRequestCommandName independently enables the special adapter entry
	// point. Empty disables it; Create never substitutes a default. Keep a configured
	// name stable across binary updates. This entry bypasses the options lifecycle.
	CompletionRequestCommandName string
	HelpHandler                  HelpHandler
	ErrorHandler                 ErrorHandler

	// FallbackToStdio supplies process stdin/stdout/stderr only when no stream
	// configuration exists in the operation's context. Constructors enable it by default;
	// a zero-valued requirement has it disabled.
	FallbackToStdio bool
	// MaxCommandDepth limits user-defined subcommand levels below the application (depth 0).
	// Zero permits only the application; constructors default to 7. Create checks
	// every definition, including inactive profiles, and snapshots the limit.
	MaxCommandDepth uint8

	Commands  []CommandRequirementLike
	Codecs    []codec.Registration
	Flags     []FlagRequirementLike
	Arguments []ArgumentRequirementLike

	CreateOptionsHandler func(context.Context) (O, error)
	ValidateHandler      func(context.Context, O) error
	InitializeHandler    func(context.Context, O) error
	Handler              func(context.Context, O) error
	CloseHandler         func(O) error
	// contains filtered or unexported fields
}

ApplicationRequirement configures options, inputs, commands, and handlers. Call ApplicationRequirement.Create to obtain an independent Application. Use pointer options when callbacks need to retain field assignments. Without a Handler, active commands require selecting a command or --help.

func NewApplication

func NewApplication[O any](nameAndDescription ...string) *ApplicationRequirement[O]

NewApplication starts a CLI builder with automatic --help/-h enabled. O must be a struct or pointer to a struct; exported tags define inputs. By default, input and execution errors use DefaultErrorHandler, and missing context streams fall back to process stdin/stdout/stderr. MaxCommandDepth is 7. Completion is opt-in through ApplicationRequirement.WithCompletion. The first optional string sets the name; further strings form the description, joined with spaces. With no strings, configure the name later; Create validates the completed builder.

Example
package main

import (
	"context"
	"fmt"

	cli "github.com/echocat/cli4g"
	"github.com/echocat/cli4g/codec"
)

func main() {
	type options struct {
		Name     string `argument:"name" required:"true"`
		Greeting string `flag:"greeting" short:"g" default:"Hello"`
	}
	cli.NewApplication[options]("greet", "Greet someone.").
		WithHandler(func(ctx context.Context, opts options) error {
			_, err := fmt.Fprintf(codec.StdoutOfContext(ctx), "%s, %s!\n", opts.Greeting, opts.Name)
			return err
		}).MustCreateParseAndExecute(context.Background(), nil, "Ada")
}
Output:
Hello, Ada!

func NewSimpleApplication

func NewSimpleApplication(nameAndDescription ...string) *ApplicationRequirement[NoOptions]

NewSimpleApplication starts a builder without an options struct. Read unbound values through Invocation.Flag and Invocation.Argument. Optional strings set the name and description as in NewApplication.

func (*ApplicationRequirement[O]) AddArgument added in v0.1.1

func (this *ApplicationRequirement[O]) AddArgument(v ...ArgumentRequirementLike)

func (*ApplicationRequirement[O]) AddCodec added in v0.1.1

func (this *ApplicationRequirement[O]) AddCodec(v any, names ...string)

func (*ApplicationRequirement[O]) AddCommand added in v0.1.1

func (this *ApplicationRequirement[O]) AddCommand(v ...CommandRequirementLike)

func (*ApplicationRequirement[O]) AddFlag added in v0.1.1

func (this *ApplicationRequirement[O]) AddFlag(v ...FlagRequirementLike)

func (*ApplicationRequirement[O]) Create

func (r *ApplicationRequirement[O]) Create() (_ *Application[O], err error)

Create compiles an independent read-only snapshot of the requirements. Requirements must not be modified concurrently with Create. Containers with subcommands cannot declare required positional arguments, because subcommands are recognized only before the first positional value.

func (*ApplicationRequirement[O]) CreateParseAndExecute

func (r *ApplicationRequirement[O]) CreateParseAndExecute(ctx context.Context, opts *ParseOpts, vs ...string) (err error)

CreateParseAndExecute manages compilation, parsing, execution and cleanup. Execution and completion-cleanup errors reach the error handler once, after cleanup. Configuration errors return directly without invoking a handler.

func (*ApplicationRequirement[O]) MustCreate

func (r *ApplicationRequirement[O]) MustCreate() *Application[O]

MustCreate compiles the application and panics on invalid configuration.

func (*ApplicationRequirement[O]) MustCreateParseAndExecute

func (r *ApplicationRequirement[O]) MustCreateParseAndExecute(ctx context.Context, opts *ParseOpts, vs ...string)

MustCreateParseAndExecute is the panic-on-returned-error variant. Standard handlers exit for ordinary parse/execution failures; invalid schemas panic. With returning or disabled handlers, their errors also cause a panic.

func (*ApplicationRequirement[O]) OptionsType

func (this *ApplicationRequirement[O]) OptionsType() reflect.Type

func (*ApplicationRequirement[O]) SetArguments

func (this *ApplicationRequirement[O]) SetArguments(v []ArgumentRequirementLike)

func (*ApplicationRequirement[O]) SetCloseHandler

func (this *ApplicationRequirement[O]) SetCloseHandler(v func(O) error)

func (*ApplicationRequirement[O]) SetCodecs

func (this *ApplicationRequirement[O]) SetCodecs(v []codec.Registration)

func (*ApplicationRequirement[O]) SetCommands

func (this *ApplicationRequirement[O]) SetCommands(v []CommandRequirementLike)

func (*ApplicationRequirement[O]) SetCompletion added in v0.3.0

func (this *ApplicationRequirement[O]) SetCompletion(v bool)

SetCompletion is the setter counterpart of WithCompletion.

func (*ApplicationRequirement[O]) SetCompletionCommand added in v0.3.0

func (this *ApplicationRequirement[O]) SetCompletionCommand(v CommandRequirementLike)

SetCompletionCommand is the setter counterpart of WithCompletionCommand.

func (*ApplicationRequirement[O]) SetCompletionRequestCommandName added in v0.3.0

func (this *ApplicationRequirement[O]) SetCompletionRequestCommandName(v string)

SetCompletionRequestCommandName is the setter counterpart of WithCompletionRequestCommandName.

func (*ApplicationRequirement[O]) SetCreateOptionsHandler

func (this *ApplicationRequirement[O]) SetCreateOptionsHandler(v func(context.Context) (O, error))

func (*ApplicationRequirement[O]) SetDescription

func (this *ApplicationRequirement[O]) SetDescription(v string)

func (*ApplicationRequirement[O]) SetErrorHandler

func (this *ApplicationRequirement[O]) SetErrorHandler(v ErrorHandler)

func (*ApplicationRequirement[O]) SetErrorHandlerEnabled

func (this *ApplicationRequirement[O]) SetErrorHandlerEnabled(v bool)

func (*ApplicationRequirement[O]) SetFallbackToStdio added in v0.1.3

func (this *ApplicationRequirement[O]) SetFallbackToStdio(v bool)

func (*ApplicationRequirement[O]) SetFlags

func (this *ApplicationRequirement[O]) SetFlags(v []FlagRequirementLike)

func (*ApplicationRequirement[O]) SetHandler

func (this *ApplicationRequirement[O]) SetHandler(v func(context.Context, O) error)

func (*ApplicationRequirement[O]) SetHelp

func (this *ApplicationRequirement[O]) SetHelp(v bool)

func (*ApplicationRequirement[O]) SetHelpHandler

func (this *ApplicationRequirement[O]) SetHelpHandler(v HelpHandler)

func (*ApplicationRequirement[O]) SetInitializeHandler

func (this *ApplicationRequirement[O]) SetInitializeHandler(v func(context.Context, O) error)

func (*ApplicationRequirement[O]) SetMaxCommandDepth added in v0.2.1

func (this *ApplicationRequirement[O]) SetMaxCommandDepth(v uint8)

func (*ApplicationRequirement[O]) SetName

func (this *ApplicationRequirement[O]) SetName(v string)

func (*ApplicationRequirement[O]) SetValidateHandler

func (this *ApplicationRequirement[O]) SetValidateHandler(v func(context.Context, O) error)

func (*ApplicationRequirement[O]) WithArgument

WithArgument adds positional arguments in order. Variadic arguments must be last. Bind options fields with ArgumentRequirement.WithField.

func (*ApplicationRequirement[O]) WithBoolArgument

func (this *ApplicationRequirement[O]) WithBoolArgument(name string, configure ...func(*ArgumentRequirement[bool, bool])) *ApplicationRequirement[O]

WithBoolArgument adds a standard bool argument. Like all typed argument helpers, it sets the name before applying callbacks in order. Fields bind only via WithField. Bool arguments consume one explicit input value.

func (*ApplicationRequirement[O]) WithBoolFlag

func (this *ApplicationRequirement[O]) WithBoolFlag(name string, configure ...func(*FlagRequirement[bool, bool])) *ApplicationRequirement[O]

WithBoolFlag adds a standard bool flag. Like all typed flag helpers, it sets the name before applying callbacks in order. Fields bind only via WithField.

func (*ApplicationRequirement[O]) WithBoolMapArgument added in v0.1.2

func (this *ApplicationRequirement[O]) WithBoolMapArgument(name string, configure ...func(*ArgumentRequirement[map[string]bool, map[string]bool])) *ApplicationRequirement[O]

WithBoolMapArgument adds a final variadic map[string]bool argument. Map arguments accept key=value pairs and reject duplicate keys.

func (*ApplicationRequirement[O]) WithBoolMapFlag added in v0.1.2

func (this *ApplicationRequirement[O]) WithBoolMapFlag(name string, configure ...func(*FlagRequirement[map[string]bool, map[string]bool])) *ApplicationRequirement[O]

WithBoolMapFlag adds a repeatable map[string]bool flag. Map helpers accept one key=value pair per occurrence and reject duplicate keys. Bind via WithField.

func (*ApplicationRequirement[O]) WithBoolSliceArgument

func (this *ApplicationRequirement[O]) WithBoolSliceArgument(name string, configure ...func(*ArgumentRequirement[[]bool, []bool])) *ApplicationRequirement[O]

WithBoolSliceArgument adds a standard variadic []bool argument. Like all standard slice arguments, it must be the final argument in its container.

func (*ApplicationRequirement[O]) WithBoolSliceFlag

func (this *ApplicationRequirement[O]) WithBoolSliceFlag(name string, configure ...func(*FlagRequirement[[]bool, []bool])) *ApplicationRequirement[O]

WithBoolSliceFlag adds a standard []bool flag. Slice helpers accept one value per occurrence and retain the standard codec's aggregation/default semantics.

func (*ApplicationRequirement[O]) WithCloseHandler

func (this *ApplicationRequirement[O]) WithCloseHandler(v func(O) error) *ApplicationRequirement[O]

WithCloseHandler provides cleanup for every created options instance, even after failed decoding, validation, or partial initialization. It must tolerate partially populated options. Options implementing io.Closer are also closed.

func (*ApplicationRequirement[O]) WithCodec

func (this *ApplicationRequirement[O]) WithCodec(v any, names ...string) *ApplicationRequirement[O]

WithCodec accepts an immutable codec.Codec[V, R]. Create validates and snapshots the codec; names bind it to matching options type tags.

func (*ApplicationRequirement[O]) WithCommand

WithCommand adds subcommands. Different commands may use different options types.

func (*ApplicationRequirement[O]) WithCompletion added in v0.3.0

func (this *ApplicationRequirement[O]) WithCompletion(v bool) *ApplicationRequirement[O]

WithCompletion is a shortcut for configuring the public command and special request entry. True assigns the current DefaultCompletionCommand and DefaultCompletionRequestCommandName; false clears both, including custom values. Call this before individual overrides. There is no separate enabled state, and neither value is implicitly restored during Create. The direct Complete API remains available independently of both settings.

The public command is an ordinary command: parent input requirements, lifecycle, profiles, help and depth limits apply normally. Only the request entry bypasses parsing/validation/initialization. The standard handler derives suggestions from the existing CLI schema and optional flag/argument/codec completion handlers.

func (*ApplicationRequirement[O]) WithCompletionCommand added in v0.3.0

func (this *ApplicationRequirement[O]) WithCompletionCommand(v CommandRequirementLike) *ApplicationRequirement[O]

WithCompletionCommand configures an ordinary public management command. Nil removes it. Use NewCompletionCommand().WithName("shells") to customize the standard command independently, or supply any CommandRequirement with your own options and handlers. Its name belongs to that command, not a separate setting. The request entry is unaffected. Create compiles the command normally without modifying the requirement or adding it permanently to Commands.

func (*ApplicationRequirement[O]) WithCompletionRequestCommandName added in v0.3.0

func (this *ApplicationRequirement[O]) WithCompletionRequestCommandName(v string) *ApplicationRequirement[O]

WithCompletionRequestCommandName names the hidden adapter request command. Empty disables it. True in WithCompletion selects the current default variable. Generated adapters use the captured name, so choose it before installation and retain it across upgrades. It must be a single command word, distinct from all root commands/aliases, including inactive profiles. This out-of-band entry is not registered as a command and is absent from Commands(), help and suggestions.

func (*ApplicationRequirement[O]) WithComplex64Argument

func (this *ApplicationRequirement[O]) WithComplex64Argument(name string, configure ...func(*ArgumentRequirement[complex64, complex64])) *ApplicationRequirement[O]

func (*ApplicationRequirement[O]) WithComplex64Flag

func (this *ApplicationRequirement[O]) WithComplex64Flag(name string, configure ...func(*FlagRequirement[complex64, complex64])) *ApplicationRequirement[O]

func (*ApplicationRequirement[O]) WithComplex64MapArgument added in v0.1.2

func (this *ApplicationRequirement[O]) WithComplex64MapArgument(name string, configure ...func(*ArgumentRequirement[map[string]complex64, map[string]complex64])) *ApplicationRequirement[O]

func (*ApplicationRequirement[O]) WithComplex64MapFlag added in v0.1.2

func (this *ApplicationRequirement[O]) WithComplex64MapFlag(name string, configure ...func(*FlagRequirement[map[string]complex64, map[string]complex64])) *ApplicationRequirement[O]

func (*ApplicationRequirement[O]) WithComplex64SliceArgument

func (this *ApplicationRequirement[O]) WithComplex64SliceArgument(name string, configure ...func(*ArgumentRequirement[[]complex64, []complex64])) *ApplicationRequirement[O]

func (*ApplicationRequirement[O]) WithComplex64SliceFlag

func (this *ApplicationRequirement[O]) WithComplex64SliceFlag(name string, configure ...func(*FlagRequirement[[]complex64, []complex64])) *ApplicationRequirement[O]

func (*ApplicationRequirement[O]) WithComplex128Argument

func (this *ApplicationRequirement[O]) WithComplex128Argument(name string, configure ...func(*ArgumentRequirement[complex128, complex128])) *ApplicationRequirement[O]

func (*ApplicationRequirement[O]) WithComplex128Flag

func (this *ApplicationRequirement[O]) WithComplex128Flag(name string, configure ...func(*FlagRequirement[complex128, complex128])) *ApplicationRequirement[O]

func (*ApplicationRequirement[O]) WithComplex128MapArgument added in v0.1.2

func (this *ApplicationRequirement[O]) WithComplex128MapArgument(name string, configure ...func(*ArgumentRequirement[map[string]complex128, map[string]complex128])) *ApplicationRequirement[O]

func (*ApplicationRequirement[O]) WithComplex128MapFlag added in v0.1.2

func (this *ApplicationRequirement[O]) WithComplex128MapFlag(name string, configure ...func(*FlagRequirement[map[string]complex128, map[string]complex128])) *ApplicationRequirement[O]

func (*ApplicationRequirement[O]) WithComplex128SliceArgument

func (this *ApplicationRequirement[O]) WithComplex128SliceArgument(name string, configure ...func(*ArgumentRequirement[[]complex128, []complex128])) *ApplicationRequirement[O]

func (*ApplicationRequirement[O]) WithComplex128SliceFlag

func (this *ApplicationRequirement[O]) WithComplex128SliceFlag(name string, configure ...func(*FlagRequirement[[]complex128, []complex128])) *ApplicationRequirement[O]

func (*ApplicationRequirement[O]) WithCreateOptionsHandler

func (this *ApplicationRequirement[O]) WithCreateOptionsHandler(v func(context.Context) (O, error)) *ApplicationRequirement[O]

WithCreateOptionsHandler supplies fresh options before input decoding. The concurrent-safe factory must return non-nil pointer options. Returned options are cleaned up even on error; unreturned resources remain caller-owned. Factory values do not satisfy required inputs. Initialize resources separately.

func (*ApplicationRequirement[O]) WithDateArgument

func (this *ApplicationRequirement[O]) WithDateArgument(name string, configure ...func(*ArgumentRequirement[time.Time, time.Time])) *ApplicationRequirement[O]

WithDateArgument adds a date-only argument; see codec.NewDate.

func (*ApplicationRequirement[O]) WithDateFlag

func (this *ApplicationRequirement[O]) WithDateFlag(name string, configure ...func(*FlagRequirement[time.Time, time.Time])) *ApplicationRequirement[O]

WithDateFlag adds a date-only flag; see codec.NewDate.

func (*ApplicationRequirement[O]) WithDateMapArgument added in v0.1.2

func (this *ApplicationRequirement[O]) WithDateMapArgument(name string, configure ...func(*ArgumentRequirement[map[string]time.Time, map[string]time.Time])) *ApplicationRequirement[O]

func (*ApplicationRequirement[O]) WithDateMapFlag added in v0.1.2

func (this *ApplicationRequirement[O]) WithDateMapFlag(name string, configure ...func(*FlagRequirement[map[string]time.Time, map[string]time.Time])) *ApplicationRequirement[O]

func (*ApplicationRequirement[O]) WithDateSliceArgument

func (this *ApplicationRequirement[O]) WithDateSliceArgument(name string, configure ...func(*ArgumentRequirement[[]time.Time, []time.Time])) *ApplicationRequirement[O]

WithDateSliceArgument adds variadic dates; see codec.NewDateSlice. It must be last.

func (*ApplicationRequirement[O]) WithDateSliceFlag

func (this *ApplicationRequirement[O]) WithDateSliceFlag(name string, configure ...func(*FlagRequirement[[]time.Time, []time.Time])) *ApplicationRequirement[O]

WithDateSliceFlag adds a repeatable date-only flag; see codec.NewDateSlice.

func (*ApplicationRequirement[O]) WithDateTimeArgument

func (this *ApplicationRequirement[O]) WithDateTimeArgument(name string, configure ...func(*ArgumentRequirement[time.Time, time.Time])) *ApplicationRequirement[O]

WithDateTimeArgument adds a timestamp argument; see codec.NewDateTime.

func (*ApplicationRequirement[O]) WithDateTimeFlag

func (this *ApplicationRequirement[O]) WithDateTimeFlag(name string, configure ...func(*FlagRequirement[time.Time, time.Time])) *ApplicationRequirement[O]

WithDateTimeFlag adds a timestamp flag; see codec.NewDateTime.

func (*ApplicationRequirement[O]) WithDateTimeMapArgument added in v0.1.2

func (this *ApplicationRequirement[O]) WithDateTimeMapArgument(name string, configure ...func(*ArgumentRequirement[map[string]time.Time, map[string]time.Time])) *ApplicationRequirement[O]

func (*ApplicationRequirement[O]) WithDateTimeMapFlag added in v0.1.2

func (this *ApplicationRequirement[O]) WithDateTimeMapFlag(name string, configure ...func(*FlagRequirement[map[string]time.Time, map[string]time.Time])) *ApplicationRequirement[O]

func (*ApplicationRequirement[O]) WithDateTimeSliceArgument

func (this *ApplicationRequirement[O]) WithDateTimeSliceArgument(name string, configure ...func(*ArgumentRequirement[[]time.Time, []time.Time])) *ApplicationRequirement[O]

WithDateTimeSliceArgument adds variadic timestamps; see codec.NewDateTimeSlice. It must be last.

func (*ApplicationRequirement[O]) WithDateTimeSliceFlag

func (this *ApplicationRequirement[O]) WithDateTimeSliceFlag(name string, configure ...func(*FlagRequirement[[]time.Time, []time.Time])) *ApplicationRequirement[O]

WithDateTimeSliceFlag adds a repeatable timestamp flag; see codec.NewDateTimeSlice.

func (*ApplicationRequirement[O]) WithDescription

func (this *ApplicationRequirement[O]) WithDescription(v string) *ApplicationRequirement[O]

func (*ApplicationRequirement[O]) WithDurationArgument

func (this *ApplicationRequirement[O]) WithDurationArgument(name string, configure ...func(*ArgumentRequirement[time.Duration, time.Duration])) *ApplicationRequirement[O]

WithDurationArgument adds a duration argument; use -- before negative values.

func (*ApplicationRequirement[O]) WithDurationFlag

func (this *ApplicationRequirement[O]) WithDurationFlag(name string, configure ...func(*FlagRequirement[time.Duration, time.Duration])) *ApplicationRequirement[O]

WithDurationFlag adds a flag accepting Go duration syntax; see codec.NewDuration.

func (*ApplicationRequirement[O]) WithDurationMapArgument added in v0.1.2

func (this *ApplicationRequirement[O]) WithDurationMapArgument(name string, configure ...func(*ArgumentRequirement[map[string]time.Duration, map[string]time.Duration])) *ApplicationRequirement[O]

func (*ApplicationRequirement[O]) WithDurationMapFlag added in v0.1.2

func (this *ApplicationRequirement[O]) WithDurationMapFlag(name string, configure ...func(*FlagRequirement[map[string]time.Duration, map[string]time.Duration])) *ApplicationRequirement[O]

func (*ApplicationRequirement[O]) WithDurationSliceArgument

func (this *ApplicationRequirement[O]) WithDurationSliceArgument(name string, configure ...func(*ArgumentRequirement[[]time.Duration, []time.Duration])) *ApplicationRequirement[O]

WithDurationSliceArgument adds variadic durations; it must be last.

func (*ApplicationRequirement[O]) WithDurationSliceFlag

func (this *ApplicationRequirement[O]) WithDurationSliceFlag(name string, configure ...func(*FlagRequirement[[]time.Duration, []time.Duration])) *ApplicationRequirement[O]

WithDurationSliceFlag adds a repeatable duration flag; see codec.NewDurationSlice.

func (*ApplicationRequirement[O]) WithErrorHandler

func (this *ApplicationRequirement[O]) WithErrorHandler(v ErrorHandler) *ApplicationRequirement[O]

WithErrorHandler replaces DefaultErrorHandler for input and operational errors. The handler runs after cleanup. A non-nil return replaces the error; nil preserves it. ErrValidation identifies input failures regardless of their phase.

func (*ApplicationRequirement[O]) WithErrorHandlerEnabled

func (this *ApplicationRequirement[O]) WithErrorHandlerEnabled(v bool) *ApplicationRequirement[O]

WithErrorHandlerEnabled controls this application's error response independently of the global default. Enabled is the default, including on zero requirements. A nil handler selects DefaultErrorHandler; disabling returns errors normally.

func (*ApplicationRequirement[O]) WithFallbackToStdio added in v0.1.3

func (this *ApplicationRequirement[O]) WithFallbackToStdio(v bool) *ApplicationRequirement[O]

WithFallbackToStdio controls fallback to process stdin/stdout/stderr when the context has no streams. NewApplication enables it by default. Explicit streams from codec.ContextWithStdio, including nil streams, always take precedence.

func (*ApplicationRequirement[O]) WithFileArgument

func (this *ApplicationRequirement[O]) WithFileArgument(name string, configure ...func(*ArgumentRequirement[*os.File, codec.FileRequirement])) *ApplicationRequirement[O]

WithFileArgument adds a read-only file argument; defaults use codec.FileRequirement.

func (*ApplicationRequirement[O]) WithFileFlag

func (this *ApplicationRequirement[O]) WithFileFlag(name string, configure ...func(*FlagRequirement[*os.File, codec.FileRequirement])) *ApplicationRequirement[O]

WithFileFlag adds a read-only file flag. Defaults use codec.FileRequirement; handles are invocation-owned. Select write policy with FlagRequirement.WithCodec.

func (*ApplicationRequirement[O]) WithFileMapArgument added in v0.1.2

func (this *ApplicationRequirement[O]) WithFileMapArgument(name string, configure ...func(*ArgumentRequirement[map[string]*os.File, map[string]codec.FileRequirement])) *ApplicationRequirement[O]

func (*ApplicationRequirement[O]) WithFileMapFlag added in v0.1.2

func (this *ApplicationRequirement[O]) WithFileMapFlag(name string, configure ...func(*FlagRequirement[map[string]*os.File, map[string]codec.FileRequirement])) *ApplicationRequirement[O]

func (*ApplicationRequirement[O]) WithFileSliceArgument

func (this *ApplicationRequirement[O]) WithFileSliceArgument(name string, configure ...func(*ArgumentRequirement[[]*os.File, []codec.FileRequirement])) *ApplicationRequirement[O]

WithFileSliceArgument adds variadic read-only files; it must be last.

func (*ApplicationRequirement[O]) WithFileSliceFlag

func (this *ApplicationRequirement[O]) WithFileSliceFlag(name string, configure ...func(*FlagRequirement[[]*os.File, []codec.FileRequirement])) *ApplicationRequirement[O]

WithFileSliceFlag adds a repeatable read-only file flag; see codec.NewSlice.

func (*ApplicationRequirement[O]) WithFlag

WithFlag adds explicit flags. Bind options fields with FlagRequirement.WithField.

func (*ApplicationRequirement[O]) WithFloat32Argument

func (this *ApplicationRequirement[O]) WithFloat32Argument(name string, configure ...func(*ArgumentRequirement[float32, float32])) *ApplicationRequirement[O]

func (*ApplicationRequirement[O]) WithFloat32Flag

func (this *ApplicationRequirement[O]) WithFloat32Flag(name string, configure ...func(*FlagRequirement[float32, float32])) *ApplicationRequirement[O]

func (*ApplicationRequirement[O]) WithFloat32MapArgument added in v0.1.2

func (this *ApplicationRequirement[O]) WithFloat32MapArgument(name string, configure ...func(*ArgumentRequirement[map[string]float32, map[string]float32])) *ApplicationRequirement[O]

func (*ApplicationRequirement[O]) WithFloat32MapFlag added in v0.1.2

func (this *ApplicationRequirement[O]) WithFloat32MapFlag(name string, configure ...func(*FlagRequirement[map[string]float32, map[string]float32])) *ApplicationRequirement[O]

func (*ApplicationRequirement[O]) WithFloat32SliceArgument

func (this *ApplicationRequirement[O]) WithFloat32SliceArgument(name string, configure ...func(*ArgumentRequirement[[]float32, []float32])) *ApplicationRequirement[O]

func (*ApplicationRequirement[O]) WithFloat32SliceFlag

func (this *ApplicationRequirement[O]) WithFloat32SliceFlag(name string, configure ...func(*FlagRequirement[[]float32, []float32])) *ApplicationRequirement[O]

func (*ApplicationRequirement[O]) WithFloat64Argument

func (this *ApplicationRequirement[O]) WithFloat64Argument(name string, configure ...func(*ArgumentRequirement[float64, float64])) *ApplicationRequirement[O]

func (*ApplicationRequirement[O]) WithFloat64Flag

func (this *ApplicationRequirement[O]) WithFloat64Flag(name string, configure ...func(*FlagRequirement[float64, float64])) *ApplicationRequirement[O]

func (*ApplicationRequirement[O]) WithFloat64MapArgument added in v0.1.2

func (this *ApplicationRequirement[O]) WithFloat64MapArgument(name string, configure ...func(*ArgumentRequirement[map[string]float64, map[string]float64])) *ApplicationRequirement[O]

func (*ApplicationRequirement[O]) WithFloat64MapFlag added in v0.1.2

func (this *ApplicationRequirement[O]) WithFloat64MapFlag(name string, configure ...func(*FlagRequirement[map[string]float64, map[string]float64])) *ApplicationRequirement[O]

func (*ApplicationRequirement[O]) WithFloat64SliceArgument

func (this *ApplicationRequirement[O]) WithFloat64SliceArgument(name string, configure ...func(*ArgumentRequirement[[]float64, []float64])) *ApplicationRequirement[O]

func (*ApplicationRequirement[O]) WithFloat64SliceFlag

func (this *ApplicationRequirement[O]) WithFloat64SliceFlag(name string, configure ...func(*FlagRequirement[[]float64, []float64])) *ApplicationRequirement[O]

func (*ApplicationRequirement[O]) WithHandler

func (this *ApplicationRequirement[O]) WithHandler(v func(context.Context, O) error) *ApplicationRequirement[O]

WithHandler receives this application's typed options. During invocation execution, InvocationFromContext and ContainerFromContext expose the complete invocation and the currently executing container.

func (*ApplicationRequirement[O]) WithHelp

func (this *ApplicationRequirement[O]) WithHelp(v bool) *ApplicationRequirement[O]

WithHelp enables or completely disables automatic help recognition and name reservation throughout the application, including every subcommand.

func (*ApplicationRequirement[O]) WithHelpHandler

func (this *ApplicationRequirement[O]) WithHelpHandler(v HelpHandler) *ApplicationRequirement[O]

WithHelpHandler replaces DefaultHelpHandler. Execute invokes it only for a help invocation; normal handlers and the options lifecycle are skipped.

func (*ApplicationRequirement[O]) WithInitializeHandler

func (this *ApplicationRequirement[O]) WithInitializeHandler(v func(context.Context, O) error) *ApplicationRequirement[O]

WithInitializeHandler prepares validated options after their Initialize method. Use pointer options to retain assignments. Release retained resources through ApplicationRequirement.WithCloseHandler or options' Close, including partial failures.

func (*ApplicationRequirement[O]) WithInt8Argument

func (this *ApplicationRequirement[O]) WithInt8Argument(name string, configure ...func(*ArgumentRequirement[int8, int8])) *ApplicationRequirement[O]

func (*ApplicationRequirement[O]) WithInt8Flag

func (this *ApplicationRequirement[O]) WithInt8Flag(name string, configure ...func(*FlagRequirement[int8, int8])) *ApplicationRequirement[O]

func (*ApplicationRequirement[O]) WithInt8MapArgument added in v0.1.2

func (this *ApplicationRequirement[O]) WithInt8MapArgument(name string, configure ...func(*ArgumentRequirement[map[string]int8, map[string]int8])) *ApplicationRequirement[O]

func (*ApplicationRequirement[O]) WithInt8MapFlag added in v0.1.2

func (this *ApplicationRequirement[O]) WithInt8MapFlag(name string, configure ...func(*FlagRequirement[map[string]int8, map[string]int8])) *ApplicationRequirement[O]

func (*ApplicationRequirement[O]) WithInt8SliceArgument

func (this *ApplicationRequirement[O]) WithInt8SliceArgument(name string, configure ...func(*ArgumentRequirement[[]int8, []int8])) *ApplicationRequirement[O]

func (*ApplicationRequirement[O]) WithInt8SliceFlag

func (this *ApplicationRequirement[O]) WithInt8SliceFlag(name string, configure ...func(*FlagRequirement[[]int8, []int8])) *ApplicationRequirement[O]

func (*ApplicationRequirement[O]) WithInt16Argument

func (this *ApplicationRequirement[O]) WithInt16Argument(name string, configure ...func(*ArgumentRequirement[int16, int16])) *ApplicationRequirement[O]

func (*ApplicationRequirement[O]) WithInt16Flag

func (this *ApplicationRequirement[O]) WithInt16Flag(name string, configure ...func(*FlagRequirement[int16, int16])) *ApplicationRequirement[O]

func (*ApplicationRequirement[O]) WithInt16MapArgument added in v0.1.2

func (this *ApplicationRequirement[O]) WithInt16MapArgument(name string, configure ...func(*ArgumentRequirement[map[string]int16, map[string]int16])) *ApplicationRequirement[O]

func (*ApplicationRequirement[O]) WithInt16MapFlag added in v0.1.2

func (this *ApplicationRequirement[O]) WithInt16MapFlag(name string, configure ...func(*FlagRequirement[map[string]int16, map[string]int16])) *ApplicationRequirement[O]

func (*ApplicationRequirement[O]) WithInt16SliceArgument

func (this *ApplicationRequirement[O]) WithInt16SliceArgument(name string, configure ...func(*ArgumentRequirement[[]int16, []int16])) *ApplicationRequirement[O]

func (*ApplicationRequirement[O]) WithInt16SliceFlag

func (this *ApplicationRequirement[O]) WithInt16SliceFlag(name string, configure ...func(*FlagRequirement[[]int16, []int16])) *ApplicationRequirement[O]

func (*ApplicationRequirement[O]) WithInt32Argument

func (this *ApplicationRequirement[O]) WithInt32Argument(name string, configure ...func(*ArgumentRequirement[int32, int32])) *ApplicationRequirement[O]

func (*ApplicationRequirement[O]) WithInt32Flag

func (this *ApplicationRequirement[O]) WithInt32Flag(name string, configure ...func(*FlagRequirement[int32, int32])) *ApplicationRequirement[O]

func (*ApplicationRequirement[O]) WithInt32MapArgument added in v0.1.2

func (this *ApplicationRequirement[O]) WithInt32MapArgument(name string, configure ...func(*ArgumentRequirement[map[string]int32, map[string]int32])) *ApplicationRequirement[O]

func (*ApplicationRequirement[O]) WithInt32MapFlag added in v0.1.2

func (this *ApplicationRequirement[O]) WithInt32MapFlag(name string, configure ...func(*FlagRequirement[map[string]int32, map[string]int32])) *ApplicationRequirement[O]

func (*ApplicationRequirement[O]) WithInt32SliceArgument

func (this *ApplicationRequirement[O]) WithInt32SliceArgument(name string, configure ...func(*ArgumentRequirement[[]int32, []int32])) *ApplicationRequirement[O]

func (*ApplicationRequirement[O]) WithInt32SliceFlag

func (this *ApplicationRequirement[O]) WithInt32SliceFlag(name string, configure ...func(*FlagRequirement[[]int32, []int32])) *ApplicationRequirement[O]

func (*ApplicationRequirement[O]) WithInt64Argument

func (this *ApplicationRequirement[O]) WithInt64Argument(name string, configure ...func(*ArgumentRequirement[int64, int64])) *ApplicationRequirement[O]

func (*ApplicationRequirement[O]) WithInt64Flag

func (this *ApplicationRequirement[O]) WithInt64Flag(name string, configure ...func(*FlagRequirement[int64, int64])) *ApplicationRequirement[O]

func (*ApplicationRequirement[O]) WithInt64MapArgument added in v0.1.2

func (this *ApplicationRequirement[O]) WithInt64MapArgument(name string, configure ...func(*ArgumentRequirement[map[string]int64, map[string]int64])) *ApplicationRequirement[O]

func (*ApplicationRequirement[O]) WithInt64MapFlag added in v0.1.2

func (this *ApplicationRequirement[O]) WithInt64MapFlag(name string, configure ...func(*FlagRequirement[map[string]int64, map[string]int64])) *ApplicationRequirement[O]

func (*ApplicationRequirement[O]) WithInt64SliceArgument

func (this *ApplicationRequirement[O]) WithInt64SliceArgument(name string, configure ...func(*ArgumentRequirement[[]int64, []int64])) *ApplicationRequirement[O]

func (*ApplicationRequirement[O]) WithInt64SliceFlag

func (this *ApplicationRequirement[O]) WithInt64SliceFlag(name string, configure ...func(*FlagRequirement[[]int64, []int64])) *ApplicationRequirement[O]

func (*ApplicationRequirement[O]) WithIntArgument

func (this *ApplicationRequirement[O]) WithIntArgument(name string, configure ...func(*ArgumentRequirement[int, int])) *ApplicationRequirement[O]

func (*ApplicationRequirement[O]) WithIntFlag

func (this *ApplicationRequirement[O]) WithIntFlag(name string, configure ...func(*FlagRequirement[int, int])) *ApplicationRequirement[O]

func (*ApplicationRequirement[O]) WithIntMapArgument added in v0.1.2

func (this *ApplicationRequirement[O]) WithIntMapArgument(name string, configure ...func(*ArgumentRequirement[map[string]int, map[string]int])) *ApplicationRequirement[O]

func (*ApplicationRequirement[O]) WithIntMapFlag added in v0.1.2

func (this *ApplicationRequirement[O]) WithIntMapFlag(name string, configure ...func(*FlagRequirement[map[string]int, map[string]int])) *ApplicationRequirement[O]

func (*ApplicationRequirement[O]) WithIntSliceArgument

func (this *ApplicationRequirement[O]) WithIntSliceArgument(name string, configure ...func(*ArgumentRequirement[[]int, []int])) *ApplicationRequirement[O]

func (*ApplicationRequirement[O]) WithIntSliceFlag

func (this *ApplicationRequirement[O]) WithIntSliceFlag(name string, configure ...func(*FlagRequirement[[]int, []int])) *ApplicationRequirement[O]

func (*ApplicationRequirement[O]) WithMarshallerArgument

func (this *ApplicationRequirement[O]) WithMarshallerArgument[T encoding.TextMarshaler, TP interface {
	*T
	encoding.TextUnmarshaler
}](name string, configure ...func(*ArgumentRequirement[T, string])) *ApplicationRequirement[O]

func (*ApplicationRequirement[O]) WithMarshallerFlag

func (this *ApplicationRequirement[O]) WithMarshallerFlag[T encoding.TextMarshaler, TP interface {
	*T
	encoding.TextUnmarshaler
}](name string, configure ...func(*FlagRequirement[T, string])) *ApplicationRequirement[O]

func (*ApplicationRequirement[O]) WithMarshallerMapArgument added in v0.1.2

func (this *ApplicationRequirement[O]) WithMarshallerMapArgument[T encoding.TextMarshaler, TP interface {
	*T
	encoding.TextUnmarshaler
}](name string, configure ...func(*ArgumentRequirement[map[string]T, map[string]string])) *ApplicationRequirement[O]

func (*ApplicationRequirement[O]) WithMarshallerMapFlag added in v0.1.2

func (this *ApplicationRequirement[O]) WithMarshallerMapFlag[T encoding.TextMarshaler, TP interface {
	*T
	encoding.TextUnmarshaler
}](name string, configure ...func(*FlagRequirement[map[string]T, map[string]string])) *ApplicationRequirement[O]

func (*ApplicationRequirement[O]) WithMarshallerPArgument

func (this *ApplicationRequirement[O]) WithMarshallerPArgument[T interface {
	encoding.TextMarshaler
	encoding.TextUnmarshaler
}](name string, factory func() T, configure ...func(*ArgumentRequirement[T, string])) *ApplicationRequirement[O]

func (*ApplicationRequirement[O]) WithMarshallerPFlag

func (this *ApplicationRequirement[O]) WithMarshallerPFlag[T interface {
	encoding.TextMarshaler
	encoding.TextUnmarshaler
}](name string, factory func() T, configure ...func(*FlagRequirement[T, string])) *ApplicationRequirement[O]

func (*ApplicationRequirement[O]) WithMarshallerPMapArgument added in v0.1.2

func (this *ApplicationRequirement[O]) WithMarshallerPMapArgument[T interface {
	encoding.TextMarshaler
	encoding.TextUnmarshaler
}](name string, factory func() T, configure ...func(*ArgumentRequirement[map[string]T, map[string]string])) *ApplicationRequirement[O]

func (*ApplicationRequirement[O]) WithMarshallerPMapFlag added in v0.1.2

func (this *ApplicationRequirement[O]) WithMarshallerPMapFlag[T interface {
	encoding.TextMarshaler
	encoding.TextUnmarshaler
}](name string, factory func() T, configure ...func(*FlagRequirement[map[string]T, map[string]string])) *ApplicationRequirement[O]

func (*ApplicationRequirement[O]) WithMarshallerPSliceArgument

func (this *ApplicationRequirement[O]) WithMarshallerPSliceArgument[T interface {
	encoding.TextMarshaler
	encoding.TextUnmarshaler
}](name string, factory func() T, configure ...func(*ArgumentRequirement[[]T, []string])) *ApplicationRequirement[O]

func (*ApplicationRequirement[O]) WithMarshallerPSliceFlag

func (this *ApplicationRequirement[O]) WithMarshallerPSliceFlag[T interface {
	encoding.TextMarshaler
	encoding.TextUnmarshaler
}](name string, factory func() T, configure ...func(*FlagRequirement[[]T, []string])) *ApplicationRequirement[O]

func (*ApplicationRequirement[O]) WithMarshallerSliceArgument

func (this *ApplicationRequirement[O]) WithMarshallerSliceArgument[T encoding.TextMarshaler, TP interface {
	*T
	encoding.TextUnmarshaler
}](name string, configure ...func(*ArgumentRequirement[[]T, []string])) *ApplicationRequirement[O]

func (*ApplicationRequirement[O]) WithMarshallerSliceFlag

func (this *ApplicationRequirement[O]) WithMarshallerSliceFlag[T encoding.TextMarshaler, TP interface {
	*T
	encoding.TextUnmarshaler
}](name string, configure ...func(*FlagRequirement[[]T, []string])) *ApplicationRequirement[O]

func (*ApplicationRequirement[O]) WithMaxCommandDepth added in v0.2.1

func (this *ApplicationRequirement[O]) WithMaxCommandDepth(v uint8) *ApplicationRequirement[O]

WithMaxCommandDepth limits subcommand nesting. Zero allows only the application. The number of sibling commands is not limited. Create rejects deeper paths.

func (*ApplicationRequirement[O]) WithName

func (this *ApplicationRequirement[O]) WithName(v string) *ApplicationRequirement[O]

func (*ApplicationRequirement[O]) WithStringArgument

func (this *ApplicationRequirement[O]) WithStringArgument(name string, configure ...func(*ArgumentRequirement[string, string])) *ApplicationRequirement[O]

WithStringArgument adds a positional string; bind options with ArgumentRequirement.WithField.

func (*ApplicationRequirement[O]) WithStringFlag

func (this *ApplicationRequirement[O]) WithStringFlag(name string, configure ...func(*FlagRequirement[string, string])) *ApplicationRequirement[O]

WithStringFlag adds a string flag; bind options with FlagRequirement.WithField.

func (*ApplicationRequirement[O]) WithStringMapArgument added in v0.1.2

func (this *ApplicationRequirement[O]) WithStringMapArgument(name string, configure ...func(*ArgumentRequirement[map[string]string, map[string]string])) *ApplicationRequirement[O]

func (*ApplicationRequirement[O]) WithStringMapFlag added in v0.1.2

func (this *ApplicationRequirement[O]) WithStringMapFlag(name string, configure ...func(*FlagRequirement[map[string]string, map[string]string])) *ApplicationRequirement[O]

WithStringMapFlag adds a repeatable map[string]string flag.

func (*ApplicationRequirement[O]) WithStringSliceArgument

func (this *ApplicationRequirement[O]) WithStringSliceArgument(name string, configure ...func(*ArgumentRequirement[[]string, []string])) *ApplicationRequirement[O]

WithStringSliceArgument adds a variadic string argument; it must be last.

func (*ApplicationRequirement[O]) WithStringSliceFlag

func (this *ApplicationRequirement[O]) WithStringSliceFlag(name string, configure ...func(*FlagRequirement[[]string, []string])) *ApplicationRequirement[O]

WithStringSliceFlag adds a repeatable string flag, one element per occurrence.

func (*ApplicationRequirement[O]) WithUint8Argument

func (this *ApplicationRequirement[O]) WithUint8Argument(name string, configure ...func(*ArgumentRequirement[uint8, uint8])) *ApplicationRequirement[O]

func (*ApplicationRequirement[O]) WithUint8Flag

func (this *ApplicationRequirement[O]) WithUint8Flag(name string, configure ...func(*FlagRequirement[uint8, uint8])) *ApplicationRequirement[O]

func (*ApplicationRequirement[O]) WithUint8MapArgument added in v0.1.2

func (this *ApplicationRequirement[O]) WithUint8MapArgument(name string, configure ...func(*ArgumentRequirement[map[string]uint8, map[string]uint8])) *ApplicationRequirement[O]

func (*ApplicationRequirement[O]) WithUint8MapFlag added in v0.1.2

func (this *ApplicationRequirement[O]) WithUint8MapFlag(name string, configure ...func(*FlagRequirement[map[string]uint8, map[string]uint8])) *ApplicationRequirement[O]

func (*ApplicationRequirement[O]) WithUint8SliceArgument

func (this *ApplicationRequirement[O]) WithUint8SliceArgument(name string, configure ...func(*ArgumentRequirement[[]uint8, []uint8])) *ApplicationRequirement[O]

func (*ApplicationRequirement[O]) WithUint8SliceFlag

func (this *ApplicationRequirement[O]) WithUint8SliceFlag(name string, configure ...func(*FlagRequirement[[]uint8, []uint8])) *ApplicationRequirement[O]

func (*ApplicationRequirement[O]) WithUint16Argument

func (this *ApplicationRequirement[O]) WithUint16Argument(name string, configure ...func(*ArgumentRequirement[uint16, uint16])) *ApplicationRequirement[O]

func (*ApplicationRequirement[O]) WithUint16Flag

func (this *ApplicationRequirement[O]) WithUint16Flag(name string, configure ...func(*FlagRequirement[uint16, uint16])) *ApplicationRequirement[O]

func (*ApplicationRequirement[O]) WithUint16MapArgument added in v0.1.2

func (this *ApplicationRequirement[O]) WithUint16MapArgument(name string, configure ...func(*ArgumentRequirement[map[string]uint16, map[string]uint16])) *ApplicationRequirement[O]

func (*ApplicationRequirement[O]) WithUint16MapFlag added in v0.1.2

func (this *ApplicationRequirement[O]) WithUint16MapFlag(name string, configure ...func(*FlagRequirement[map[string]uint16, map[string]uint16])) *ApplicationRequirement[O]

func (*ApplicationRequirement[O]) WithUint16SliceArgument

func (this *ApplicationRequirement[O]) WithUint16SliceArgument(name string, configure ...func(*ArgumentRequirement[[]uint16, []uint16])) *ApplicationRequirement[O]

func (*ApplicationRequirement[O]) WithUint16SliceFlag

func (this *ApplicationRequirement[O]) WithUint16SliceFlag(name string, configure ...func(*FlagRequirement[[]uint16, []uint16])) *ApplicationRequirement[O]

func (*ApplicationRequirement[O]) WithUint32Argument

func (this *ApplicationRequirement[O]) WithUint32Argument(name string, configure ...func(*ArgumentRequirement[uint32, uint32])) *ApplicationRequirement[O]

func (*ApplicationRequirement[O]) WithUint32Flag

func (this *ApplicationRequirement[O]) WithUint32Flag(name string, configure ...func(*FlagRequirement[uint32, uint32])) *ApplicationRequirement[O]

func (*ApplicationRequirement[O]) WithUint32MapArgument added in v0.1.2

func (this *ApplicationRequirement[O]) WithUint32MapArgument(name string, configure ...func(*ArgumentRequirement[map[string]uint32, map[string]uint32])) *ApplicationRequirement[O]

func (*ApplicationRequirement[O]) WithUint32MapFlag added in v0.1.2

func (this *ApplicationRequirement[O]) WithUint32MapFlag(name string, configure ...func(*FlagRequirement[map[string]uint32, map[string]uint32])) *ApplicationRequirement[O]

func (*ApplicationRequirement[O]) WithUint32SliceArgument

func (this *ApplicationRequirement[O]) WithUint32SliceArgument(name string, configure ...func(*ArgumentRequirement[[]uint32, []uint32])) *ApplicationRequirement[O]

func (*ApplicationRequirement[O]) WithUint32SliceFlag

func (this *ApplicationRequirement[O]) WithUint32SliceFlag(name string, configure ...func(*FlagRequirement[[]uint32, []uint32])) *ApplicationRequirement[O]

func (*ApplicationRequirement[O]) WithUint64Argument

func (this *ApplicationRequirement[O]) WithUint64Argument(name string, configure ...func(*ArgumentRequirement[uint64, uint64])) *ApplicationRequirement[O]

func (*ApplicationRequirement[O]) WithUint64Flag

func (this *ApplicationRequirement[O]) WithUint64Flag(name string, configure ...func(*FlagRequirement[uint64, uint64])) *ApplicationRequirement[O]

func (*ApplicationRequirement[O]) WithUint64MapArgument added in v0.1.2

func (this *ApplicationRequirement[O]) WithUint64MapArgument(name string, configure ...func(*ArgumentRequirement[map[string]uint64, map[string]uint64])) *ApplicationRequirement[O]

func (*ApplicationRequirement[O]) WithUint64MapFlag added in v0.1.2

func (this *ApplicationRequirement[O]) WithUint64MapFlag(name string, configure ...func(*FlagRequirement[map[string]uint64, map[string]uint64])) *ApplicationRequirement[O]

func (*ApplicationRequirement[O]) WithUint64SliceArgument

func (this *ApplicationRequirement[O]) WithUint64SliceArgument(name string, configure ...func(*ArgumentRequirement[[]uint64, []uint64])) *ApplicationRequirement[O]

func (*ApplicationRequirement[O]) WithUint64SliceFlag

func (this *ApplicationRequirement[O]) WithUint64SliceFlag(name string, configure ...func(*FlagRequirement[[]uint64, []uint64])) *ApplicationRequirement[O]

func (*ApplicationRequirement[O]) WithUintArgument

func (this *ApplicationRequirement[O]) WithUintArgument(name string, configure ...func(*ArgumentRequirement[uint, uint])) *ApplicationRequirement[O]

func (*ApplicationRequirement[O]) WithUintFlag

func (this *ApplicationRequirement[O]) WithUintFlag(name string, configure ...func(*FlagRequirement[uint, uint])) *ApplicationRequirement[O]

func (*ApplicationRequirement[O]) WithUintMapArgument added in v0.1.2

func (this *ApplicationRequirement[O]) WithUintMapArgument(name string, configure ...func(*ArgumentRequirement[map[string]uint, map[string]uint])) *ApplicationRequirement[O]

func (*ApplicationRequirement[O]) WithUintMapFlag added in v0.1.2

func (this *ApplicationRequirement[O]) WithUintMapFlag(name string, configure ...func(*FlagRequirement[map[string]uint, map[string]uint])) *ApplicationRequirement[O]

func (*ApplicationRequirement[O]) WithUintSliceArgument

func (this *ApplicationRequirement[O]) WithUintSliceArgument(name string, configure ...func(*ArgumentRequirement[[]uint, []uint])) *ApplicationRequirement[O]

func (*ApplicationRequirement[O]) WithUintSliceFlag

func (this *ApplicationRequirement[O]) WithUintSliceFlag(name string, configure ...func(*FlagRequirement[[]uint, []uint])) *ApplicationRequirement[O]

func (*ApplicationRequirement[O]) WithUintptrArgument

func (this *ApplicationRequirement[O]) WithUintptrArgument(name string, configure ...func(*ArgumentRequirement[uintptr, uintptr])) *ApplicationRequirement[O]

func (*ApplicationRequirement[O]) WithUintptrFlag

func (this *ApplicationRequirement[O]) WithUintptrFlag(name string, configure ...func(*FlagRequirement[uintptr, uintptr])) *ApplicationRequirement[O]

func (*ApplicationRequirement[O]) WithUintptrMapArgument added in v0.1.2

func (this *ApplicationRequirement[O]) WithUintptrMapArgument(name string, configure ...func(*ArgumentRequirement[map[string]uintptr, map[string]uintptr])) *ApplicationRequirement[O]

func (*ApplicationRequirement[O]) WithUintptrMapFlag added in v0.1.2

func (this *ApplicationRequirement[O]) WithUintptrMapFlag(name string, configure ...func(*FlagRequirement[map[string]uintptr, map[string]uintptr])) *ApplicationRequirement[O]

func (*ApplicationRequirement[O]) WithUintptrSliceArgument

func (this *ApplicationRequirement[O]) WithUintptrSliceArgument(name string, configure ...func(*ArgumentRequirement[[]uintptr, []uintptr])) *ApplicationRequirement[O]

func (*ApplicationRequirement[O]) WithUintptrSliceFlag

func (this *ApplicationRequirement[O]) WithUintptrSliceFlag(name string, configure ...func(*FlagRequirement[[]uintptr, []uintptr])) *ApplicationRequirement[O]

func (*ApplicationRequirement[O]) WithValidateHandler

func (this *ApplicationRequirement[O]) WithValidateHandler(v func(context.Context, O) error) *ApplicationRequirement[O]

WithValidateHandler checks fully decoded options after their Validate method and before any initializer runs. It must not mutate options or acquire resources. Mark invalid input with NewValidationErrorf; unmarked failures remain operational.

func (*ApplicationRequirement[O]) WithValueArgument

func (this *ApplicationRequirement[O]) WithValueArgument[T any, TP interface {
	*T
	codec.Value
}](name string, configure ...func(*ArgumentRequirement[T, []string])) *ApplicationRequirement[O]

WithValueArgument adds a positional Set/String value argument.

func (*ApplicationRequirement[O]) WithValueFlag

func (this *ApplicationRequirement[O]) WithValueFlag[T any, TP interface {
	*T
	codec.Value
}](name string, configure ...func(*FlagRequirement[T, []string])) *ApplicationRequirement[O]

WithValueFlag adds a Set/String value flag, keeping T as the field/value type.

func (*ApplicationRequirement[O]) WithValueMapArgument added in v0.1.2

func (this *ApplicationRequirement[O]) WithValueMapArgument[T any, TP interface {
	*T
	codec.Value
}](name string, configure ...func(*ArgumentRequirement[map[string]T, map[string][]string])) *ApplicationRequirement[O]

func (*ApplicationRequirement[O]) WithValueMapFlag added in v0.1.2

func (this *ApplicationRequirement[O]) WithValueMapFlag[T any, TP interface {
	*T
	codec.Value
}](name string, configure ...func(*FlagRequirement[map[string]T, map[string][]string])) *ApplicationRequirement[O]

func (*ApplicationRequirement[O]) WithValuePArgument

func (this *ApplicationRequirement[O]) WithValuePArgument[T codec.Value](name string, factory func() T, configure ...func(*ArgumentRequirement[T, []string])) *ApplicationRequirement[O]

WithValuePArgument adds a positional value with a fresh pointer factory.

func (*ApplicationRequirement[O]) WithValuePFlag

func (this *ApplicationRequirement[O]) WithValuePFlag[T codec.Value](name string, factory func() T, configure ...func(*FlagRequirement[T, []string])) *ApplicationRequirement[O]

WithValuePFlag adds a Set/String flag with a fresh pointer factory.

func (*ApplicationRequirement[O]) WithValuePMapArgument added in v0.1.2

func (this *ApplicationRequirement[O]) WithValuePMapArgument[T codec.Value](name string, factory func() T, configure ...func(*ArgumentRequirement[map[string]T, map[string][]string])) *ApplicationRequirement[O]

func (*ApplicationRequirement[O]) WithValuePMapFlag added in v0.1.2

func (this *ApplicationRequirement[O]) WithValuePMapFlag[T codec.Value](name string, factory func() T, configure ...func(*FlagRequirement[map[string]T, map[string][]string])) *ApplicationRequirement[O]

func (*ApplicationRequirement[O]) WithValuePSliceArgument

func (this *ApplicationRequirement[O]) WithValuePSliceArgument[T codec.Value](name string, factory func() T, configure ...func(*ArgumentRequirement[[]T, [][]string])) *ApplicationRequirement[O]

WithValuePSliceArgument adds a final variadic slice of factory-created pointers.

func (*ApplicationRequirement[O]) WithValuePSliceFlag

func (this *ApplicationRequirement[O]) WithValuePSliceFlag[T codec.Value](name string, factory func() T, configure ...func(*FlagRequirement[[]T, [][]string])) *ApplicationRequirement[O]

WithValuePSliceFlag adds a repeated slice flag of factory-created pointers.

func (*ApplicationRequirement[O]) WithValueSliceArgument

func (this *ApplicationRequirement[O]) WithValueSliceArgument[T any, TP interface {
	*T
	codec.Value
}](name string, configure ...func(*ArgumentRequirement[[]T, [][]string])) *ApplicationRequirement[O]

WithValueSliceArgument adds a final variadic slice of Set/String values.

func (*ApplicationRequirement[O]) WithValueSliceFlag

func (this *ApplicationRequirement[O]) WithValueSliceFlag[T any, TP interface {
	*T
	codec.Value
}](name string, configure ...func(*FlagRequirement[[]T, [][]string])) *ApplicationRequirement[O]

WithValueSliceFlag adds a standard repeated slice flag of Set/String values.

type Argument

type Argument[V, R any] struct {
	// contains filtered or unexported fields
}

Argument describes a positional input. Use Invocation.Argument for parsed V and Argument.Default for its resource-free default R.

func (*Argument[V, R]) Codec

func (this *Argument[V, R]) Codec() codec.Codec[V, R]

func (*Argument[V, R]) CompletionHandler added in v0.3.0

func (this *Argument[V, R]) CompletionHandler() CompletionHandler

CompletionHandler returns the explicitly configured argument handler, or nil when value completion uses only the codec and standard handler. Codec returns the effective codec, including the captured argument override.

func (*Argument[V, R]) Default

func (this *Argument[V, R]) Default(ctx context.Context) (value R, found bool, err error)

Default returns an independent resource-free requirement R, never a runtime V.

func (*Argument[V, R]) Description

func (this *Argument[V, R]) Description() string

func (*Argument[V, R]) FormatDefault

func (this *Argument[V, R]) FormatDefault(ctx context.Context) ([]string, bool, error)

FormatDefault returns help-safe default text without resolving resources.

func (*Argument[V, R]) HasDefault

func (this *Argument[V, R]) HasDefault() bool

func (*Argument[V, R]) IsRequired

func (this *Argument[V, R]) IsRequired() bool

func (*Argument[V, R]) Name

func (this *Argument[V, R]) Name() string

func (*Argument[V, R]) Placeholder

func (this *Argument[V, R]) Placeholder() string

func (*Argument[V, R]) Profiles added in v0.2.0

func (this *Argument[V, R]) Profiles() []string

Profiles returns a copy of the explicit profile assignments; empty means always active.

func (*Argument[V, R]) ValueType

func (this *Argument[V, R]) ValueType() reflect.Type

type ArgumentRequirement

type ArgumentRequirement[V, R any] struct {
	Name string
	// Profiles activates this definition when any listed profile is selected.
	// An empty list makes it active for every parse.
	Profiles    []string
	Description string
	Required    bool
	Placeholder string
	Codec       codec.Codec[V, R]
	// CompletionHandler optionally overrides value suggestions for this argument.
	// Returning Handled=false delegates to the codec and automatic completion.
	CompletionHandler CompletionHandler
	// CodecFactory supplies a codec at Create when Codec is nil. It configures
	// schema only; it must not acquire invocation resources.
	CodecFactory func() (codec.Codec[V, R], error)
	Field        []string
	// contains filtered or unexported fields
}

ArgumentRequirement configures a positional value V with input requirements R. Slice arguments must be last. Required arguments cannot have defaults or belong to a container with subcommands. Bool arguments require explicit input. See ArgumentRequirement.WithField and ArgumentRequirement.WithDefault. Explicit arguments retain registration order; field bindings replacing tags keep their tagged slots in mixed definitions. Other builder arguments come first.

func NewArgument

func NewArgument[V, R any](codec codec.Codec[V, R], nameAndDescription ...string) *ArgumentRequirement[V, R]

NewArgument starts a positional argument using codec. The first optional string sets the name; further strings form the description, joined with spaces. With no strings, configure the name later; Create validates the completed builder.

Example
package main

import (
	"context"
	"fmt"

	cli "github.com/echocat/cli4g"
	"github.com/echocat/cli4g/codec"
)

func main() {
	argument := cli.NewArgument(codec.NewString(), "name", "Name", "to greet.").
		WithRequired(true)
	app := cli.NewSimpleApplication("greet").
		WithArgument(argument).
		MustCreate()
	defer func() {
		if err := app.Close(); err != nil {
			panic(err)
		}
	}()
	invocation := app.MustParse(context.Background(), nil, "Ada")
	defer func() {
		if err := invocation.Close(); err != nil {
			panic(err)
		}
	}()
	_, value := invocation.Argument(0)
	fmt.Println(value)
}
Output:
Ada

func (*ArgumentRequirement[V, R]) SetCodec

func (this *ArgumentRequirement[V, R]) SetCodec(v codec.Codec[V, R])

func (*ArgumentRequirement[V, R]) SetCodecFactory

func (this *ArgumentRequirement[V, R]) SetCodecFactory(v func() (codec.Codec[V, R], error))

func (*ArgumentRequirement[V, R]) SetCompletionHandler added in v0.3.0

func (this *ArgumentRequirement[V, R]) SetCompletionHandler(v CompletionHandler)

SetCompletionHandler is the setter counterpart of WithCompletionHandler.

func (*ArgumentRequirement[V, R]) SetDefault

func (this *ArgumentRequirement[V, R]) SetDefault(v R)

func (*ArgumentRequirement[V, R]) SetDefaultStr

func (this *ArgumentRequirement[V, R]) SetDefaultStr(v ...string)

func (*ArgumentRequirement[V, R]) SetDescription

func (this *ArgumentRequirement[V, R]) SetDescription(v string)

func (*ArgumentRequirement[V, R]) SetField

func (this *ArgumentRequirement[V, R]) SetField(v []string) *ArgumentRequirement[V, R]

func (*ArgumentRequirement[V, R]) SetName

func (this *ArgumentRequirement[V, R]) SetName(v string)

func (*ArgumentRequirement[V, R]) SetPlaceholder

func (this *ArgumentRequirement[V, R]) SetPlaceholder(v string)

func (*ArgumentRequirement[V, R]) SetProfiles added in v0.2.0

func (this *ArgumentRequirement[V, R]) SetProfiles(v []string)

func (*ArgumentRequirement[V, R]) SetRequired

func (this *ArgumentRequirement[V, R]) SetRequired(v bool)

func (*ArgumentRequirement[V, R]) WithCodec

func (this *ArgumentRequirement[V, R]) WithCodec(v codec.Codec[V, R]) *ArgumentRequirement[V, R]

WithCodec replaces the decoder and clears ArgumentRequirement.WithCodecFactory.

func (*ArgumentRequirement[V, R]) WithCodecFactory

func (this *ArgumentRequirement[V, R]) WithCodecFactory(v func() (codec.Codec[V, R], error)) *ArgumentRequirement[V, R]

WithCodecFactory configures the decoder during Create and replaces ArgumentRequirement.WithCodec. The factory must not acquire runtime resources; configuration errors fail Create.

func (*ArgumentRequirement[V, R]) WithCompletionHandler added in v0.3.0

func (this *ArgumentRequirement[V, R]) WithCompletionHandler(v CompletionHandler) *ArgumentRequirement[V, R]

WithCompletionHandler sets a context-aware value handler for this argument without changing its parsing codec or CLI syntax. It takes precedence over the codec completer; Handled=false delegates. A nil handler restores codec/automatic completion. Create captures the callback; it must be concurrent-safe.

func (*ArgumentRequirement[V, R]) WithDefault

func (this *ArgumentRequirement[V, R]) WithDefault(v R) *ArgumentRequirement[V, R]

WithDefault sets a resource-free typed default R for an omitted optional argument. R may differ from V; each parse receives an independent copy.

func (*ArgumentRequirement[V, R]) WithDefaultStr

func (this *ArgumentRequirement[V, R]) WithDefaultStr(v ...string) *ArgumentRequirement[V, R]

WithDefaultStr sets a complete codec input without shell or CSV splitting. Either default setter replaces the previously configured default.

func (*ArgumentRequirement[V, R]) WithDescription

func (this *ArgumentRequirement[V, R]) WithDescription(v string) *ArgumentRequirement[V, R]

func (*ArgumentRequirement[V, R]) WithField

func (this *ArgumentRequirement[V, R]) WithField(v ...string) *ArgumentRequirement[V, R]

WithField binds V to an exported options field; v is its nested field path. Explicit binding overrides that field's tags; an input name alone does not bind.

func (*ArgumentRequirement[V, R]) WithName

func (this *ArgumentRequirement[V, R]) WithName(v string) *ArgumentRequirement[V, R]

func (*ArgumentRequirement[V, R]) WithPlaceholder

func (this *ArgumentRequirement[V, R]) WithPlaceholder(v string) *ArgumentRequirement[V, R]

WithPlaceholder sets help value text, preserving its case. The default uses the complete argument name. Help encloses the text in <...> unless already enclosed; optionality and arity are shown outside those brackets.

func (*ArgumentRequirement[V, R]) WithProfiles added in v0.2.0

func (this *ArgumentRequirement[V, R]) WithProfiles(v ...string) *ArgumentRequirement[V, R]

WithProfiles replaces the profile selection. No profiles means always active.

func (*ArgumentRequirement[V, R]) WithRequired

func (this *ArgumentRequirement[V, R]) WithRequired(v bool) *ArgumentRequirement[V, R]

WithRequired demands a positional value. Defaults and factory values cannot satisfy it; containers with subcommands cannot declare required arguments.

type ArgumentRequirementLike

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

ArgumentRequirementLike allows differently typed arguments in one builder. It is implemented by ArgumentRequirement, not by callers.

type Command

type Command[O any] struct {
	// contains filtered or unexported fields
}

Command is a typed command definition belonging to an Application. Build it with NewCommand. Read selected options with Command.OptionsFrom.

func FindCommand

func FindCommand[O any](container Container, path ...string) (*Command[O], bool)

FindCommand resolves a command path and verifies its options type once. The returned handle provides typed access to that command's invocation options.

func FindCommandOfProfile added in v0.2.0

func FindCommandOfProfile[O any](container Container, profile string, path ...string) (*Command[O], bool)

FindCommandOfProfile resolves a path for one profile and verifies its leaf options type. Explicit assignments are preferred; profile-free commands are also traversed. It does not activate ancestors assigned to other profiles.

func (Command) Argument

func (this Command) Argument(index int) (*Argument[any, any], bool)

Argument returns the definition at index, whether or not an invocation has a value for it. Invocation.Argument uses this same definition index.

func (Command) Arguments

func (this Command) Arguments() iter.Seq[*Argument[any, any]]

func (*Command[O]) Close

func (c *Command[O]) Close(options O) error

Close runs the close callback and options' Close method, including partial state.

func (Command) Command

func (this Command) Command(name string) (CommandLike, bool)

Command finds only commands without profile assignments.

func (Command) CommandOfProfile added in v0.2.0

func (this Command) CommandOfProfile(name, profile string) (CommandLike, bool)

CommandOfProfile finds a command explicitly assigned to profile, by name or alias. It does not fall back to commands without profile assignments.

func (Command) Commands

func (this Command) Commands() iter.Seq[CommandLike]

func (*Command[O]) Description

func (c *Command[O]) Description() string

Description returns the help description.

func (*Command[O]) Execute

func (c *Command[O]) Execute(ctx context.Context, options O) error

Execute runs this command's handler with caller-owned options. It does not parse, validate, initialize, or close those options.

func (Command) Flag

func (this Command) Flag(name string) (*Flag[any, any], bool)

Flag finds only flags without profile assignments, by name or alias.

func (Command) FlagOfProfile added in v0.2.0

func (this Command) FlagOfProfile(name, profile string) (*Flag[any, any], bool)

FlagOfProfile finds an explicitly assigned flag, with no profile-free fallback.

func (Command) Flags

func (this Command) Flags() iter.Seq[*Flag[any, any]]

func (*Command[O]) Initialize

func (c *Command[O]) Initialize(ctx context.Context, options O) error

Initialize runs options methods and callbacks. Use pointer options to retain mutations in the caller's instance; struct arguments follow Go value semantics.

func (*Command[O]) IsVisible added in v0.1.2

func (c *Command[O]) IsVisible() bool

IsVisible reports whether the command appears in help listings.

func (*Command[O]) Name

func (c *Command[O]) Name() string

Name returns the primary command name.

func (*Command[O]) Names

func (c *Command[O]) Names() []string

Names returns a new slice containing the primary name and aliases.

func (*Command[O]) OptionsFrom

func (c *Command[O]) OptionsFrom(invocation InvocationLike) (O, bool)

OptionsFrom reads this command's options from an invocation. Unselected commands and help invocations return false. Structs are copied; pointers and reference fields share invocation-owned data.

func (Command) OptionsType

func (this Command) OptionsType() reflect.Type

func (*Command[O]) Profiles added in v0.2.0

func (c *Command[O]) Profiles() []string

Profiles returns a copy of the explicit profile assignments. Empty means the command is active whenever its parent is active.

func (Command) ShortFlag

func (this Command) ShortFlag(short rune) (*Flag[any, any], bool)

ShortFlag finds only flags without profile assignments.

func (Command) ShortFlagOfProfile added in v0.2.0

func (this Command) ShortFlagOfProfile(short rune, profile string) (*Flag[any, any], bool)

ShortFlagOfProfile finds an explicitly assigned flag by its short alias.

func (*Command[O]) Validate

func (c *Command[O]) Validate(ctx context.Context, options O) error

Validate runs the options' Validate method followed by the configured callback.

type CommandLike

type CommandLike interface {
	Container
	IsVisible() bool
	Profiles() []string
	// contains filtered or unexported methods
}

CommandLike allows commands with different options types in one command tree.

type CommandRequirement

type CommandRequirement[O any] struct {
	// Names contains the primary name followed by aliases.
	Names []string
	// Profiles activates this command when any listed profile is selected and
	// its parent is active. An empty list only requires an active parent.
	Profiles []string

	Description string
	Visible     bool

	Commands  []CommandRequirementLike
	Codecs    []codec.Registration
	Flags     []FlagRequirementLike
	Arguments []ArgumentRequirementLike

	CreateOptionsHandler func(context.Context) (O, error)
	ValidateHandler      func(context.Context, O) error
	InitializeHandler    func(context.Context, O) error
	Handler              func(context.Context, O) error
	CloseHandler         func(O) error
}

CommandRequirement configures a command's names, options, inputs, and handlers. Struct callbacks receive copies; use pointer options to retain assignments. Without a Handler, active subcommands make this a command group: direct CLI invocation requires a subcommand or --help. An ancestor's handler does not satisfy this requirement.

func NewCommand

func NewCommand[O any](nameAndDescription ...string) *CommandRequirement[O]

NewCommand starts a visible command builder with struct or pointer-to-struct options O. Attach it using ApplicationRequirement.WithCommand or CommandRequirement.WithCommand. The first optional string sets the name; further strings form the description, joined with spaces. Add aliases with CommandRequirement.WithAliases. With no strings, configure the name later; Create validates the completed builder.

Example
package main

import (
	"context"
	"fmt"

	cli "github.com/echocat/cli4g"
	"github.com/echocat/cli4g/codec"
)

func main() {
	type options struct {
		Name string `argument:"name" default:"Ada"`
	}
	command := cli.NewCommand[options]("hello", "Greet", "someone.").
		WithHandler(func(ctx context.Context, opts options) error {
			_, err := fmt.Fprintln(codec.StdoutOfContext(ctx), "Hello, "+opts.Name+"!")
			return err
		})
	cli.NewSimpleApplication("app").
		WithCommand(command).
		MustCreateParseAndExecute(context.Background(), nil, "hello", "Grace")
}
Output:
Hello, Grace!

func NewCompletionCommand added in v0.3.0

func NewCompletionCommand() *CommandRequirement[NoOptions]

NewCompletionCommand builds a fresh, ordinary command tree named "completion". It supports "completion <bash|fish|nu|powershell|zsh>" and "completion install <bash|fish|nu|powershell|zsh> [directory]". WithName, WithAliases, handlers and all other ordinary CommandRequirement configuration are available. Parent requirements, parsing, profiles, initialization, execution, cleanup and depth limits apply normally. Only the independently configured request entry bypasses that lifecycle.

The command accesses the application's completion API through CompletionApplicationFromContext, which custom management commands may also use.

func NewSimpleCommand

func NewSimpleCommand(nameAndDescription ...string) *CommandRequirement[NoOptions]

NewSimpleCommand starts a command without an options struct. Optional strings set the name and description as in NewCommand.

func (*CommandRequirement[O]) AddArgument added in v0.1.1

func (this *CommandRequirement[O]) AddArgument(v ...ArgumentRequirementLike)

func (*CommandRequirement[O]) AddCodec added in v0.1.1

func (this *CommandRequirement[O]) AddCodec(v any, names ...string)

func (*CommandRequirement[O]) AddCommand added in v0.1.1

func (this *CommandRequirement[O]) AddCommand(v ...CommandRequirementLike)

func (*CommandRequirement[O]) AddFlag added in v0.1.1

func (this *CommandRequirement[O]) AddFlag(v ...FlagRequirementLike)

func (*CommandRequirement[O]) OptionsType

func (this *CommandRequirement[O]) OptionsType() reflect.Type

func (*CommandRequirement[O]) SetArguments

func (this *CommandRequirement[O]) SetArguments(v []ArgumentRequirementLike)

func (*CommandRequirement[O]) SetCloseHandler

func (this *CommandRequirement[O]) SetCloseHandler(v func(O) error)

func (*CommandRequirement[O]) SetCodecs

func (this *CommandRequirement[O]) SetCodecs(v []codec.Registration)

func (*CommandRequirement[O]) SetCommands

func (this *CommandRequirement[O]) SetCommands(v []CommandRequirementLike)

func (*CommandRequirement[O]) SetCreateOptionsHandler

func (this *CommandRequirement[O]) SetCreateOptionsHandler(v func(context.Context) (O, error))

func (*CommandRequirement[O]) SetDescription

func (this *CommandRequirement[O]) SetDescription(v string)

func (*CommandRequirement[O]) SetFlags

func (this *CommandRequirement[O]) SetFlags(v []FlagRequirementLike)

func (*CommandRequirement[O]) SetHandler

func (this *CommandRequirement[O]) SetHandler(v func(context.Context, O) error)

func (*CommandRequirement[O]) SetInitializeHandler

func (this *CommandRequirement[O]) SetInitializeHandler(v func(context.Context, O) error)

func (*CommandRequirement[O]) SetNames

func (this *CommandRequirement[O]) SetNames(v []string)

func (*CommandRequirement[O]) SetProfiles added in v0.2.0

func (this *CommandRequirement[O]) SetProfiles(v []string)

func (*CommandRequirement[O]) SetValidateHandler

func (this *CommandRequirement[O]) SetValidateHandler(v func(context.Context, O) error)

func (*CommandRequirement[O]) SetVisible added in v0.1.2

func (this *CommandRequirement[O]) SetVisible(v bool)

func (*CommandRequirement[O]) WithAliases

func (this *CommandRequirement[O]) WithAliases(v ...string) *CommandRequirement[O]

func (*CommandRequirement[O]) WithArgument

func (this *CommandRequirement[O]) WithArgument(v ...ArgumentRequirementLike) *CommandRequirement[O]

func (*CommandRequirement[O]) WithBoolArgument

func (this *CommandRequirement[O]) WithBoolArgument(name string, configure ...func(*ArgumentRequirement[bool, bool])) *CommandRequirement[O]

WithBoolArgument adds a standard bool argument. Like all typed argument helpers, it sets the name before applying callbacks in order. Fields bind only via WithField. Bool arguments consume one explicit input value.

func (*CommandRequirement[O]) WithBoolFlag

func (this *CommandRequirement[O]) WithBoolFlag(name string, configure ...func(*FlagRequirement[bool, bool])) *CommandRequirement[O]

WithBoolFlag adds a standard bool flag. Like all typed flag helpers, it sets the name before applying callbacks in order. Fields bind only via WithField.

func (*CommandRequirement[O]) WithBoolMapArgument added in v0.1.2

func (this *CommandRequirement[O]) WithBoolMapArgument(name string, configure ...func(*ArgumentRequirement[map[string]bool, map[string]bool])) *CommandRequirement[O]

WithBoolMapArgument adds a final variadic map[string]bool argument. Map arguments accept key=value pairs and reject duplicate keys.

func (*CommandRequirement[O]) WithBoolMapFlag added in v0.1.2

func (this *CommandRequirement[O]) WithBoolMapFlag(name string, configure ...func(*FlagRequirement[map[string]bool, map[string]bool])) *CommandRequirement[O]

WithBoolMapFlag adds a repeatable map[string]bool flag. Map helpers accept one key=value pair per occurrence and reject duplicate keys. Bind via WithField.

func (*CommandRequirement[O]) WithBoolSliceArgument

func (this *CommandRequirement[O]) WithBoolSliceArgument(name string, configure ...func(*ArgumentRequirement[[]bool, []bool])) *CommandRequirement[O]

WithBoolSliceArgument adds a standard variadic []bool argument. Like all standard slice arguments, it must be the final argument in its container.

func (*CommandRequirement[O]) WithBoolSliceFlag

func (this *CommandRequirement[O]) WithBoolSliceFlag(name string, configure ...func(*FlagRequirement[[]bool, []bool])) *CommandRequirement[O]

WithBoolSliceFlag adds a standard []bool flag. Slice helpers accept one value per occurrence and retain the standard codec's aggregation/default semantics.

func (*CommandRequirement[O]) WithCloseHandler

func (this *CommandRequirement[O]) WithCloseHandler(v func(O) error) *CommandRequirement[O]

WithCloseHandler provides cleanup for every created options instance, even after failed decoding, validation, or partial initialization. It must tolerate partially populated options. Options implementing io.Closer are also closed.

func (*CommandRequirement[O]) WithCodec

func (this *CommandRequirement[O]) WithCodec(v any, names ...string) *CommandRequirement[O]

WithCodec accepts an immutable codec.Codec[V, R]; Create validates it.

func (*CommandRequirement[O]) WithCommand

func (this *CommandRequirement[O]) WithCommand(v ...CommandRequirementLike) *CommandRequirement[O]

func (*CommandRequirement[O]) WithComplex64Argument

func (this *CommandRequirement[O]) WithComplex64Argument(name string, configure ...func(*ArgumentRequirement[complex64, complex64])) *CommandRequirement[O]

func (*CommandRequirement[O]) WithComplex64Flag

func (this *CommandRequirement[O]) WithComplex64Flag(name string, configure ...func(*FlagRequirement[complex64, complex64])) *CommandRequirement[O]

func (*CommandRequirement[O]) WithComplex64MapArgument added in v0.1.2

func (this *CommandRequirement[O]) WithComplex64MapArgument(name string, configure ...func(*ArgumentRequirement[map[string]complex64, map[string]complex64])) *CommandRequirement[O]

func (*CommandRequirement[O]) WithComplex64MapFlag added in v0.1.2

func (this *CommandRequirement[O]) WithComplex64MapFlag(name string, configure ...func(*FlagRequirement[map[string]complex64, map[string]complex64])) *CommandRequirement[O]

func (*CommandRequirement[O]) WithComplex64SliceArgument

func (this *CommandRequirement[O]) WithComplex64SliceArgument(name string, configure ...func(*ArgumentRequirement[[]complex64, []complex64])) *CommandRequirement[O]

func (*CommandRequirement[O]) WithComplex64SliceFlag

func (this *CommandRequirement[O]) WithComplex64SliceFlag(name string, configure ...func(*FlagRequirement[[]complex64, []complex64])) *CommandRequirement[O]

func (*CommandRequirement[O]) WithComplex128Argument

func (this *CommandRequirement[O]) WithComplex128Argument(name string, configure ...func(*ArgumentRequirement[complex128, complex128])) *CommandRequirement[O]

func (*CommandRequirement[O]) WithComplex128Flag

func (this *CommandRequirement[O]) WithComplex128Flag(name string, configure ...func(*FlagRequirement[complex128, complex128])) *CommandRequirement[O]

func (*CommandRequirement[O]) WithComplex128MapArgument added in v0.1.2

func (this *CommandRequirement[O]) WithComplex128MapArgument(name string, configure ...func(*ArgumentRequirement[map[string]complex128, map[string]complex128])) *CommandRequirement[O]

func (*CommandRequirement[O]) WithComplex128MapFlag added in v0.1.2

func (this *CommandRequirement[O]) WithComplex128MapFlag(name string, configure ...func(*FlagRequirement[map[string]complex128, map[string]complex128])) *CommandRequirement[O]

func (*CommandRequirement[O]) WithComplex128SliceArgument

func (this *CommandRequirement[O]) WithComplex128SliceArgument(name string, configure ...func(*ArgumentRequirement[[]complex128, []complex128])) *CommandRequirement[O]

func (*CommandRequirement[O]) WithComplex128SliceFlag

func (this *CommandRequirement[O]) WithComplex128SliceFlag(name string, configure ...func(*FlagRequirement[[]complex128, []complex128])) *CommandRequirement[O]

func (*CommandRequirement[O]) WithCreateOptionsHandler

func (this *CommandRequirement[O]) WithCreateOptionsHandler(v func(context.Context) (O, error)) *CommandRequirement[O]

WithCreateOptionsHandler supplies this command's invocation-owned options before decoding. It runs only for selected commands and must return fresh mutable state. Non-nil returned options are owned even on error; nil pointers are invalid. Factory values do not satisfy Required. Resources not returned remain the factory's responsibility; acquire resources in Initialize.

func (*CommandRequirement[O]) WithDateArgument

func (this *CommandRequirement[O]) WithDateArgument(name string, configure ...func(*ArgumentRequirement[time.Time, time.Time])) *CommandRequirement[O]

WithDateArgument adds a date-only argument; see codec.NewDate.

func (*CommandRequirement[O]) WithDateFlag

func (this *CommandRequirement[O]) WithDateFlag(name string, configure ...func(*FlagRequirement[time.Time, time.Time])) *CommandRequirement[O]

WithDateFlag adds a date-only flag; see codec.NewDate.

func (*CommandRequirement[O]) WithDateMapArgument added in v0.1.2

func (this *CommandRequirement[O]) WithDateMapArgument(name string, configure ...func(*ArgumentRequirement[map[string]time.Time, map[string]time.Time])) *CommandRequirement[O]

func (*CommandRequirement[O]) WithDateMapFlag added in v0.1.2

func (this *CommandRequirement[O]) WithDateMapFlag(name string, configure ...func(*FlagRequirement[map[string]time.Time, map[string]time.Time])) *CommandRequirement[O]

func (*CommandRequirement[O]) WithDateSliceArgument

func (this *CommandRequirement[O]) WithDateSliceArgument(name string, configure ...func(*ArgumentRequirement[[]time.Time, []time.Time])) *CommandRequirement[O]

WithDateSliceArgument adds variadic dates; see codec.NewDateSlice. It must be last.

func (*CommandRequirement[O]) WithDateSliceFlag

func (this *CommandRequirement[O]) WithDateSliceFlag(name string, configure ...func(*FlagRequirement[[]time.Time, []time.Time])) *CommandRequirement[O]

WithDateSliceFlag adds a repeatable date-only flag; see codec.NewDateSlice.

func (*CommandRequirement[O]) WithDateTimeArgument

func (this *CommandRequirement[O]) WithDateTimeArgument(name string, configure ...func(*ArgumentRequirement[time.Time, time.Time])) *CommandRequirement[O]

WithDateTimeArgument adds a timestamp argument; see codec.NewDateTime.

func (*CommandRequirement[O]) WithDateTimeFlag

func (this *CommandRequirement[O]) WithDateTimeFlag(name string, configure ...func(*FlagRequirement[time.Time, time.Time])) *CommandRequirement[O]

WithDateTimeFlag adds a timestamp flag; see codec.NewDateTime.

func (*CommandRequirement[O]) WithDateTimeMapArgument added in v0.1.2

func (this *CommandRequirement[O]) WithDateTimeMapArgument(name string, configure ...func(*ArgumentRequirement[map[string]time.Time, map[string]time.Time])) *CommandRequirement[O]

func (*CommandRequirement[O]) WithDateTimeMapFlag added in v0.1.2

func (this *CommandRequirement[O]) WithDateTimeMapFlag(name string, configure ...func(*FlagRequirement[map[string]time.Time, map[string]time.Time])) *CommandRequirement[O]

func (*CommandRequirement[O]) WithDateTimeSliceArgument

func (this *CommandRequirement[O]) WithDateTimeSliceArgument(name string, configure ...func(*ArgumentRequirement[[]time.Time, []time.Time])) *CommandRequirement[O]

WithDateTimeSliceArgument adds variadic timestamps; see codec.NewDateTimeSlice. It must be last.

func (*CommandRequirement[O]) WithDateTimeSliceFlag

func (this *CommandRequirement[O]) WithDateTimeSliceFlag(name string, configure ...func(*FlagRequirement[[]time.Time, []time.Time])) *CommandRequirement[O]

WithDateTimeSliceFlag adds a repeatable timestamp flag; see codec.NewDateTimeSlice.

func (*CommandRequirement[O]) WithDescription

func (this *CommandRequirement[O]) WithDescription(v string) *CommandRequirement[O]

func (*CommandRequirement[O]) WithDurationArgument

func (this *CommandRequirement[O]) WithDurationArgument(name string, configure ...func(*ArgumentRequirement[time.Duration, time.Duration])) *CommandRequirement[O]

WithDurationArgument adds a duration argument; use -- before negative values.

func (*CommandRequirement[O]) WithDurationFlag

func (this *CommandRequirement[O]) WithDurationFlag(name string, configure ...func(*FlagRequirement[time.Duration, time.Duration])) *CommandRequirement[O]

WithDurationFlag adds a flag accepting Go duration syntax; see codec.NewDuration.

func (*CommandRequirement[O]) WithDurationMapArgument added in v0.1.2

func (this *CommandRequirement[O]) WithDurationMapArgument(name string, configure ...func(*ArgumentRequirement[map[string]time.Duration, map[string]time.Duration])) *CommandRequirement[O]

func (*CommandRequirement[O]) WithDurationMapFlag added in v0.1.2

func (this *CommandRequirement[O]) WithDurationMapFlag(name string, configure ...func(*FlagRequirement[map[string]time.Duration, map[string]time.Duration])) *CommandRequirement[O]

func (*CommandRequirement[O]) WithDurationSliceArgument

func (this *CommandRequirement[O]) WithDurationSliceArgument(name string, configure ...func(*ArgumentRequirement[[]time.Duration, []time.Duration])) *CommandRequirement[O]

WithDurationSliceArgument adds variadic durations; it must be last.

func (*CommandRequirement[O]) WithDurationSliceFlag

func (this *CommandRequirement[O]) WithDurationSliceFlag(name string, configure ...func(*FlagRequirement[[]time.Duration, []time.Duration])) *CommandRequirement[O]

WithDurationSliceFlag adds a repeatable duration flag; see codec.NewDurationSlice.

func (*CommandRequirement[O]) WithFileArgument

func (this *CommandRequirement[O]) WithFileArgument(name string, configure ...func(*ArgumentRequirement[*os.File, codec.FileRequirement])) *CommandRequirement[O]

WithFileArgument adds a read-only file argument; defaults use codec.FileRequirement.

func (*CommandRequirement[O]) WithFileFlag

func (this *CommandRequirement[O]) WithFileFlag(name string, configure ...func(*FlagRequirement[*os.File, codec.FileRequirement])) *CommandRequirement[O]

WithFileFlag adds a read-only file flag. Defaults use codec.FileRequirement; handles are invocation-owned. Select write policy with FlagRequirement.WithCodec.

func (*CommandRequirement[O]) WithFileMapArgument added in v0.1.2

func (this *CommandRequirement[O]) WithFileMapArgument(name string, configure ...func(*ArgumentRequirement[map[string]*os.File, map[string]codec.FileRequirement])) *CommandRequirement[O]

func (*CommandRequirement[O]) WithFileMapFlag added in v0.1.2

func (this *CommandRequirement[O]) WithFileMapFlag(name string, configure ...func(*FlagRequirement[map[string]*os.File, map[string]codec.FileRequirement])) *CommandRequirement[O]

func (*CommandRequirement[O]) WithFileSliceArgument

func (this *CommandRequirement[O]) WithFileSliceArgument(name string, configure ...func(*ArgumentRequirement[[]*os.File, []codec.FileRequirement])) *CommandRequirement[O]

WithFileSliceArgument adds variadic read-only files; it must be last.

func (*CommandRequirement[O]) WithFileSliceFlag

func (this *CommandRequirement[O]) WithFileSliceFlag(name string, configure ...func(*FlagRequirement[[]*os.File, []codec.FileRequirement])) *CommandRequirement[O]

WithFileSliceFlag adds a repeatable read-only file flag; see codec.NewSlice.

func (*CommandRequirement[O]) WithFlag

func (this *CommandRequirement[O]) WithFlag(v ...FlagRequirementLike) *CommandRequirement[O]

func (*CommandRequirement[O]) WithFloat32Argument

func (this *CommandRequirement[O]) WithFloat32Argument(name string, configure ...func(*ArgumentRequirement[float32, float32])) *CommandRequirement[O]

func (*CommandRequirement[O]) WithFloat32Flag

func (this *CommandRequirement[O]) WithFloat32Flag(name string, configure ...func(*FlagRequirement[float32, float32])) *CommandRequirement[O]

func (*CommandRequirement[O]) WithFloat32MapArgument added in v0.1.2

func (this *CommandRequirement[O]) WithFloat32MapArgument(name string, configure ...func(*ArgumentRequirement[map[string]float32, map[string]float32])) *CommandRequirement[O]

func (*CommandRequirement[O]) WithFloat32MapFlag added in v0.1.2

func (this *CommandRequirement[O]) WithFloat32MapFlag(name string, configure ...func(*FlagRequirement[map[string]float32, map[string]float32])) *CommandRequirement[O]

func (*CommandRequirement[O]) WithFloat32SliceArgument

func (this *CommandRequirement[O]) WithFloat32SliceArgument(name string, configure ...func(*ArgumentRequirement[[]float32, []float32])) *CommandRequirement[O]

func (*CommandRequirement[O]) WithFloat32SliceFlag

func (this *CommandRequirement[O]) WithFloat32SliceFlag(name string, configure ...func(*FlagRequirement[[]float32, []float32])) *CommandRequirement[O]

func (*CommandRequirement[O]) WithFloat64Argument

func (this *CommandRequirement[O]) WithFloat64Argument(name string, configure ...func(*ArgumentRequirement[float64, float64])) *CommandRequirement[O]

func (*CommandRequirement[O]) WithFloat64Flag

func (this *CommandRequirement[O]) WithFloat64Flag(name string, configure ...func(*FlagRequirement[float64, float64])) *CommandRequirement[O]

func (*CommandRequirement[O]) WithFloat64MapArgument added in v0.1.2

func (this *CommandRequirement[O]) WithFloat64MapArgument(name string, configure ...func(*ArgumentRequirement[map[string]float64, map[string]float64])) *CommandRequirement[O]

func (*CommandRequirement[O]) WithFloat64MapFlag added in v0.1.2

func (this *CommandRequirement[O]) WithFloat64MapFlag(name string, configure ...func(*FlagRequirement[map[string]float64, map[string]float64])) *CommandRequirement[O]

func (*CommandRequirement[O]) WithFloat64SliceArgument

func (this *CommandRequirement[O]) WithFloat64SliceArgument(name string, configure ...func(*ArgumentRequirement[[]float64, []float64])) *CommandRequirement[O]

func (*CommandRequirement[O]) WithFloat64SliceFlag

func (this *CommandRequirement[O]) WithFloat64SliceFlag(name string, configure ...func(*FlagRequirement[[]float64, []float64])) *CommandRequirement[O]

func (*CommandRequirement[O]) WithHandler

func (this *CommandRequirement[O]) WithHandler(v func(context.Context, O) error) *CommandRequirement[O]

WithHandler receives this command's typed options. During invocation execution, InvocationFromContext and ContainerFromContext expose the complete invocation and the currently executing container.

func (*CommandRequirement[O]) WithInitializeHandler

func (this *CommandRequirement[O]) WithInitializeHandler(v func(context.Context, O) error) *CommandRequirement[O]

WithInitializeHandler runs after every selected scope has been decoded and validated. Resources retained by owned options are closed on any later error; other partial resources remain the handler's responsibility. Use pointer options when the handler needs to attach resources or change fields on the owned instance; assignments to struct copies are not retained.

func (*CommandRequirement[O]) WithInt8Argument

func (this *CommandRequirement[O]) WithInt8Argument(name string, configure ...func(*ArgumentRequirement[int8, int8])) *CommandRequirement[O]

func (*CommandRequirement[O]) WithInt8Flag

func (this *CommandRequirement[O]) WithInt8Flag(name string, configure ...func(*FlagRequirement[int8, int8])) *CommandRequirement[O]

func (*CommandRequirement[O]) WithInt8MapArgument added in v0.1.2

func (this *CommandRequirement[O]) WithInt8MapArgument(name string, configure ...func(*ArgumentRequirement[map[string]int8, map[string]int8])) *CommandRequirement[O]

func (*CommandRequirement[O]) WithInt8MapFlag added in v0.1.2

func (this *CommandRequirement[O]) WithInt8MapFlag(name string, configure ...func(*FlagRequirement[map[string]int8, map[string]int8])) *CommandRequirement[O]

func (*CommandRequirement[O]) WithInt8SliceArgument

func (this *CommandRequirement[O]) WithInt8SliceArgument(name string, configure ...func(*ArgumentRequirement[[]int8, []int8])) *CommandRequirement[O]

func (*CommandRequirement[O]) WithInt8SliceFlag

func (this *CommandRequirement[O]) WithInt8SliceFlag(name string, configure ...func(*FlagRequirement[[]int8, []int8])) *CommandRequirement[O]

func (*CommandRequirement[O]) WithInt16Argument

func (this *CommandRequirement[O]) WithInt16Argument(name string, configure ...func(*ArgumentRequirement[int16, int16])) *CommandRequirement[O]

func (*CommandRequirement[O]) WithInt16Flag

func (this *CommandRequirement[O]) WithInt16Flag(name string, configure ...func(*FlagRequirement[int16, int16])) *CommandRequirement[O]

func (*CommandRequirement[O]) WithInt16MapArgument added in v0.1.2

func (this *CommandRequirement[O]) WithInt16MapArgument(name string, configure ...func(*ArgumentRequirement[map[string]int16, map[string]int16])) *CommandRequirement[O]

func (*CommandRequirement[O]) WithInt16MapFlag added in v0.1.2

func (this *CommandRequirement[O]) WithInt16MapFlag(name string, configure ...func(*FlagRequirement[map[string]int16, map[string]int16])) *CommandRequirement[O]

func (*CommandRequirement[O]) WithInt16SliceArgument

func (this *CommandRequirement[O]) WithInt16SliceArgument(name string, configure ...func(*ArgumentRequirement[[]int16, []int16])) *CommandRequirement[O]

func (*CommandRequirement[O]) WithInt16SliceFlag

func (this *CommandRequirement[O]) WithInt16SliceFlag(name string, configure ...func(*FlagRequirement[[]int16, []int16])) *CommandRequirement[O]

func (*CommandRequirement[O]) WithInt32Argument

func (this *CommandRequirement[O]) WithInt32Argument(name string, configure ...func(*ArgumentRequirement[int32, int32])) *CommandRequirement[O]

func (*CommandRequirement[O]) WithInt32Flag

func (this *CommandRequirement[O]) WithInt32Flag(name string, configure ...func(*FlagRequirement[int32, int32])) *CommandRequirement[O]

func (*CommandRequirement[O]) WithInt32MapArgument added in v0.1.2

func (this *CommandRequirement[O]) WithInt32MapArgument(name string, configure ...func(*ArgumentRequirement[map[string]int32, map[string]int32])) *CommandRequirement[O]

func (*CommandRequirement[O]) WithInt32MapFlag added in v0.1.2

func (this *CommandRequirement[O]) WithInt32MapFlag(name string, configure ...func(*FlagRequirement[map[string]int32, map[string]int32])) *CommandRequirement[O]

func (*CommandRequirement[O]) WithInt32SliceArgument

func (this *CommandRequirement[O]) WithInt32SliceArgument(name string, configure ...func(*ArgumentRequirement[[]int32, []int32])) *CommandRequirement[O]

func (*CommandRequirement[O]) WithInt32SliceFlag

func (this *CommandRequirement[O]) WithInt32SliceFlag(name string, configure ...func(*FlagRequirement[[]int32, []int32])) *CommandRequirement[O]

func (*CommandRequirement[O]) WithInt64Argument

func (this *CommandRequirement[O]) WithInt64Argument(name string, configure ...func(*ArgumentRequirement[int64, int64])) *CommandRequirement[O]

func (*CommandRequirement[O]) WithInt64Flag

func (this *CommandRequirement[O]) WithInt64Flag(name string, configure ...func(*FlagRequirement[int64, int64])) *CommandRequirement[O]

func (*CommandRequirement[O]) WithInt64MapArgument added in v0.1.2

func (this *CommandRequirement[O]) WithInt64MapArgument(name string, configure ...func(*ArgumentRequirement[map[string]int64, map[string]int64])) *CommandRequirement[O]

func (*CommandRequirement[O]) WithInt64MapFlag added in v0.1.2

func (this *CommandRequirement[O]) WithInt64MapFlag(name string, configure ...func(*FlagRequirement[map[string]int64, map[string]int64])) *CommandRequirement[O]

func (*CommandRequirement[O]) WithInt64SliceArgument

func (this *CommandRequirement[O]) WithInt64SliceArgument(name string, configure ...func(*ArgumentRequirement[[]int64, []int64])) *CommandRequirement[O]

func (*CommandRequirement[O]) WithInt64SliceFlag

func (this *CommandRequirement[O]) WithInt64SliceFlag(name string, configure ...func(*FlagRequirement[[]int64, []int64])) *CommandRequirement[O]

func (*CommandRequirement[O]) WithIntArgument

func (this *CommandRequirement[O]) WithIntArgument(name string, configure ...func(*ArgumentRequirement[int, int])) *CommandRequirement[O]

func (*CommandRequirement[O]) WithIntFlag

func (this *CommandRequirement[O]) WithIntFlag(name string, configure ...func(*FlagRequirement[int, int])) *CommandRequirement[O]

func (*CommandRequirement[O]) WithIntMapArgument added in v0.1.2

func (this *CommandRequirement[O]) WithIntMapArgument(name string, configure ...func(*ArgumentRequirement[map[string]int, map[string]int])) *CommandRequirement[O]

func (*CommandRequirement[O]) WithIntMapFlag added in v0.1.2

func (this *CommandRequirement[O]) WithIntMapFlag(name string, configure ...func(*FlagRequirement[map[string]int, map[string]int])) *CommandRequirement[O]

func (*CommandRequirement[O]) WithIntSliceArgument

func (this *CommandRequirement[O]) WithIntSliceArgument(name string, configure ...func(*ArgumentRequirement[[]int, []int])) *CommandRequirement[O]

func (*CommandRequirement[O]) WithIntSliceFlag

func (this *CommandRequirement[O]) WithIntSliceFlag(name string, configure ...func(*FlagRequirement[[]int, []int])) *CommandRequirement[O]

func (*CommandRequirement[O]) WithMarshallerArgument

func (this *CommandRequirement[O]) WithMarshallerArgument[
	T encoding.TextMarshaler,
	TP interface {
		*T
		encoding.TextUnmarshaler
	},
](name string, configure ...func(*ArgumentRequirement[T, string])) *CommandRequirement[O]

func (*CommandRequirement[O]) WithMarshallerFlag

func (this *CommandRequirement[O]) WithMarshallerFlag[
	T encoding.TextMarshaler,
	TP interface {
		*T
		encoding.TextUnmarshaler
	},
](name string, configure ...func(*FlagRequirement[T, string])) *CommandRequirement[O]

func (*CommandRequirement[O]) WithMarshallerMapArgument added in v0.1.2

func (this *CommandRequirement[O]) WithMarshallerMapArgument[T encoding.TextMarshaler, TP interface {
	*T
	encoding.TextUnmarshaler
}](name string, configure ...func(*ArgumentRequirement[map[string]T, map[string]string])) *CommandRequirement[O]

func (*CommandRequirement[O]) WithMarshallerMapFlag added in v0.1.2

func (this *CommandRequirement[O]) WithMarshallerMapFlag[T encoding.TextMarshaler, TP interface {
	*T
	encoding.TextUnmarshaler
}](name string, configure ...func(*FlagRequirement[map[string]T, map[string]string])) *CommandRequirement[O]

func (*CommandRequirement[O]) WithMarshallerPArgument

func (this *CommandRequirement[O]) WithMarshallerPArgument[
	T interface {
		encoding.TextMarshaler
		encoding.TextUnmarshaler
	},
](name string, factory func() T, configure ...func(*ArgumentRequirement[T, string])) *CommandRequirement[O]

func (*CommandRequirement[O]) WithMarshallerPFlag

func (this *CommandRequirement[O]) WithMarshallerPFlag[
	T interface {
		encoding.TextMarshaler
		encoding.TextUnmarshaler
	},
](name string, factory func() T, configure ...func(*FlagRequirement[T, string])) *CommandRequirement[O]

func (*CommandRequirement[O]) WithMarshallerPMapArgument added in v0.1.2

func (this *CommandRequirement[O]) WithMarshallerPMapArgument[T interface {
	encoding.TextMarshaler
	encoding.TextUnmarshaler
}](name string, factory func() T, configure ...func(*ArgumentRequirement[map[string]T, map[string]string])) *CommandRequirement[O]

func (*CommandRequirement[O]) WithMarshallerPMapFlag added in v0.1.2

func (this *CommandRequirement[O]) WithMarshallerPMapFlag[T interface {
	encoding.TextMarshaler
	encoding.TextUnmarshaler
}](name string, factory func() T, configure ...func(*FlagRequirement[map[string]T, map[string]string])) *CommandRequirement[O]

func (*CommandRequirement[O]) WithMarshallerPSliceArgument

func (this *CommandRequirement[O]) WithMarshallerPSliceArgument[
	T interface {
		encoding.TextMarshaler
		encoding.TextUnmarshaler
	},
](name string, factory func() T, configure ...func(*ArgumentRequirement[[]T, []string])) *CommandRequirement[O]

func (*CommandRequirement[O]) WithMarshallerPSliceFlag

func (this *CommandRequirement[O]) WithMarshallerPSliceFlag[
	T interface {
		encoding.TextMarshaler
		encoding.TextUnmarshaler
	},
](name string, factory func() T, configure ...func(*FlagRequirement[[]T, []string])) *CommandRequirement[O]

func (*CommandRequirement[O]) WithMarshallerSliceArgument

func (this *CommandRequirement[O]) WithMarshallerSliceArgument[
	T encoding.TextMarshaler,
	TP interface {
		*T
		encoding.TextUnmarshaler
	},
](name string, configure ...func(*ArgumentRequirement[[]T, []string])) *CommandRequirement[O]

func (*CommandRequirement[O]) WithMarshallerSliceFlag

func (this *CommandRequirement[O]) WithMarshallerSliceFlag[
	T encoding.TextMarshaler,
	TP interface {
		*T
		encoding.TextUnmarshaler
	},
](name string, configure ...func(*FlagRequirement[[]T, []string])) *CommandRequirement[O]

func (*CommandRequirement[O]) WithName

func (this *CommandRequirement[O]) WithName(v ...string) *CommandRequirement[O]

WithName replaces the primary name and optional aliases. WithAliases appends aliases.

func (*CommandRequirement[O]) WithProfiles added in v0.2.0

func (this *CommandRequirement[O]) WithProfiles(v ...string) *CommandRequirement[O]

WithProfiles replaces the profile selection. No profiles means always active within an active parent; selecting a child never activates its ancestors.

func (*CommandRequirement[O]) WithStringArgument

func (this *CommandRequirement[O]) WithStringArgument(name string, configure ...func(*ArgumentRequirement[string, string])) *CommandRequirement[O]

WithStringArgument adds a positional string; bind options with ArgumentRequirement.WithField.

func (*CommandRequirement[O]) WithStringFlag

func (this *CommandRequirement[O]) WithStringFlag(name string, configure ...func(*FlagRequirement[string, string])) *CommandRequirement[O]

WithStringFlag adds a string flag; bind options with FlagRequirement.WithField.

func (*CommandRequirement[O]) WithStringMapArgument added in v0.1.2

func (this *CommandRequirement[O]) WithStringMapArgument(name string, configure ...func(*ArgumentRequirement[map[string]string, map[string]string])) *CommandRequirement[O]

func (*CommandRequirement[O]) WithStringMapFlag added in v0.1.2

func (this *CommandRequirement[O]) WithStringMapFlag(name string, configure ...func(*FlagRequirement[map[string]string, map[string]string])) *CommandRequirement[O]

WithStringMapFlag adds a repeatable map[string]string flag.

func (*CommandRequirement[O]) WithStringSliceArgument

func (this *CommandRequirement[O]) WithStringSliceArgument(name string, configure ...func(*ArgumentRequirement[[]string, []string])) *CommandRequirement[O]

WithStringSliceArgument adds a variadic string argument; it must be last.

func (*CommandRequirement[O]) WithStringSliceFlag

func (this *CommandRequirement[O]) WithStringSliceFlag(name string, configure ...func(*FlagRequirement[[]string, []string])) *CommandRequirement[O]

WithStringSliceFlag adds a repeatable string flag, one element per occurrence.

func (*CommandRequirement[O]) WithUint8Argument

func (this *CommandRequirement[O]) WithUint8Argument(name string, configure ...func(*ArgumentRequirement[uint8, uint8])) *CommandRequirement[O]

func (*CommandRequirement[O]) WithUint8Flag

func (this *CommandRequirement[O]) WithUint8Flag(name string, configure ...func(*FlagRequirement[uint8, uint8])) *CommandRequirement[O]

func (*CommandRequirement[O]) WithUint8MapArgument added in v0.1.2

func (this *CommandRequirement[O]) WithUint8MapArgument(name string, configure ...func(*ArgumentRequirement[map[string]uint8, map[string]uint8])) *CommandRequirement[O]

func (*CommandRequirement[O]) WithUint8MapFlag added in v0.1.2

func (this *CommandRequirement[O]) WithUint8MapFlag(name string, configure ...func(*FlagRequirement[map[string]uint8, map[string]uint8])) *CommandRequirement[O]

func (*CommandRequirement[O]) WithUint8SliceArgument

func (this *CommandRequirement[O]) WithUint8SliceArgument(name string, configure ...func(*ArgumentRequirement[[]uint8, []uint8])) *CommandRequirement[O]

func (*CommandRequirement[O]) WithUint8SliceFlag

func (this *CommandRequirement[O]) WithUint8SliceFlag(name string, configure ...func(*FlagRequirement[[]uint8, []uint8])) *CommandRequirement[O]

func (*CommandRequirement[O]) WithUint16Argument

func (this *CommandRequirement[O]) WithUint16Argument(name string, configure ...func(*ArgumentRequirement[uint16, uint16])) *CommandRequirement[O]

func (*CommandRequirement[O]) WithUint16Flag

func (this *CommandRequirement[O]) WithUint16Flag(name string, configure ...func(*FlagRequirement[uint16, uint16])) *CommandRequirement[O]

func (*CommandRequirement[O]) WithUint16MapArgument added in v0.1.2

func (this *CommandRequirement[O]) WithUint16MapArgument(name string, configure ...func(*ArgumentRequirement[map[string]uint16, map[string]uint16])) *CommandRequirement[O]

func (*CommandRequirement[O]) WithUint16MapFlag added in v0.1.2

func (this *CommandRequirement[O]) WithUint16MapFlag(name string, configure ...func(*FlagRequirement[map[string]uint16, map[string]uint16])) *CommandRequirement[O]

func (*CommandRequirement[O]) WithUint16SliceArgument

func (this *CommandRequirement[O]) WithUint16SliceArgument(name string, configure ...func(*ArgumentRequirement[[]uint16, []uint16])) *CommandRequirement[O]

func (*CommandRequirement[O]) WithUint16SliceFlag

func (this *CommandRequirement[O]) WithUint16SliceFlag(name string, configure ...func(*FlagRequirement[[]uint16, []uint16])) *CommandRequirement[O]

func (*CommandRequirement[O]) WithUint32Argument

func (this *CommandRequirement[O]) WithUint32Argument(name string, configure ...func(*ArgumentRequirement[uint32, uint32])) *CommandRequirement[O]

func (*CommandRequirement[O]) WithUint32Flag

func (this *CommandRequirement[O]) WithUint32Flag(name string, configure ...func(*FlagRequirement[uint32, uint32])) *CommandRequirement[O]

func (*CommandRequirement[O]) WithUint32MapArgument added in v0.1.2

func (this *CommandRequirement[O]) WithUint32MapArgument(name string, configure ...func(*ArgumentRequirement[map[string]uint32, map[string]uint32])) *CommandRequirement[O]

func (*CommandRequirement[O]) WithUint32MapFlag added in v0.1.2

func (this *CommandRequirement[O]) WithUint32MapFlag(name string, configure ...func(*FlagRequirement[map[string]uint32, map[string]uint32])) *CommandRequirement[O]

func (*CommandRequirement[O]) WithUint32SliceArgument

func (this *CommandRequirement[O]) WithUint32SliceArgument(name string, configure ...func(*ArgumentRequirement[[]uint32, []uint32])) *CommandRequirement[O]

func (*CommandRequirement[O]) WithUint32SliceFlag

func (this *CommandRequirement[O]) WithUint32SliceFlag(name string, configure ...func(*FlagRequirement[[]uint32, []uint32])) *CommandRequirement[O]

func (*CommandRequirement[O]) WithUint64Argument

func (this *CommandRequirement[O]) WithUint64Argument(name string, configure ...func(*ArgumentRequirement[uint64, uint64])) *CommandRequirement[O]

func (*CommandRequirement[O]) WithUint64Flag

func (this *CommandRequirement[O]) WithUint64Flag(name string, configure ...func(*FlagRequirement[uint64, uint64])) *CommandRequirement[O]

func (*CommandRequirement[O]) WithUint64MapArgument added in v0.1.2

func (this *CommandRequirement[O]) WithUint64MapArgument(name string, configure ...func(*ArgumentRequirement[map[string]uint64, map[string]uint64])) *CommandRequirement[O]

func (*CommandRequirement[O]) WithUint64MapFlag added in v0.1.2

func (this *CommandRequirement[O]) WithUint64MapFlag(name string, configure ...func(*FlagRequirement[map[string]uint64, map[string]uint64])) *CommandRequirement[O]

func (*CommandRequirement[O]) WithUint64SliceArgument

func (this *CommandRequirement[O]) WithUint64SliceArgument(name string, configure ...func(*ArgumentRequirement[[]uint64, []uint64])) *CommandRequirement[O]

func (*CommandRequirement[O]) WithUint64SliceFlag

func (this *CommandRequirement[O]) WithUint64SliceFlag(name string, configure ...func(*FlagRequirement[[]uint64, []uint64])) *CommandRequirement[O]

func (*CommandRequirement[O]) WithUintArgument

func (this *CommandRequirement[O]) WithUintArgument(name string, configure ...func(*ArgumentRequirement[uint, uint])) *CommandRequirement[O]

func (*CommandRequirement[O]) WithUintFlag

func (this *CommandRequirement[O]) WithUintFlag(name string, configure ...func(*FlagRequirement[uint, uint])) *CommandRequirement[O]

func (*CommandRequirement[O]) WithUintMapArgument added in v0.1.2

func (this *CommandRequirement[O]) WithUintMapArgument(name string, configure ...func(*ArgumentRequirement[map[string]uint, map[string]uint])) *CommandRequirement[O]

func (*CommandRequirement[O]) WithUintMapFlag added in v0.1.2

func (this *CommandRequirement[O]) WithUintMapFlag(name string, configure ...func(*FlagRequirement[map[string]uint, map[string]uint])) *CommandRequirement[O]

func (*CommandRequirement[O]) WithUintSliceArgument

func (this *CommandRequirement[O]) WithUintSliceArgument(name string, configure ...func(*ArgumentRequirement[[]uint, []uint])) *CommandRequirement[O]

func (*CommandRequirement[O]) WithUintSliceFlag

func (this *CommandRequirement[O]) WithUintSliceFlag(name string, configure ...func(*FlagRequirement[[]uint, []uint])) *CommandRequirement[O]

func (*CommandRequirement[O]) WithUintptrArgument

func (this *CommandRequirement[O]) WithUintptrArgument(name string, configure ...func(*ArgumentRequirement[uintptr, uintptr])) *CommandRequirement[O]

func (*CommandRequirement[O]) WithUintptrFlag

func (this *CommandRequirement[O]) WithUintptrFlag(name string, configure ...func(*FlagRequirement[uintptr, uintptr])) *CommandRequirement[O]

func (*CommandRequirement[O]) WithUintptrMapArgument added in v0.1.2

func (this *CommandRequirement[O]) WithUintptrMapArgument(name string, configure ...func(*ArgumentRequirement[map[string]uintptr, map[string]uintptr])) *CommandRequirement[O]

func (*CommandRequirement[O]) WithUintptrMapFlag added in v0.1.2

func (this *CommandRequirement[O]) WithUintptrMapFlag(name string, configure ...func(*FlagRequirement[map[string]uintptr, map[string]uintptr])) *CommandRequirement[O]

func (*CommandRequirement[O]) WithUintptrSliceArgument

func (this *CommandRequirement[O]) WithUintptrSliceArgument(name string, configure ...func(*ArgumentRequirement[[]uintptr, []uintptr])) *CommandRequirement[O]

func (*CommandRequirement[O]) WithUintptrSliceFlag

func (this *CommandRequirement[O]) WithUintptrSliceFlag(name string, configure ...func(*FlagRequirement[[]uintptr, []uintptr])) *CommandRequirement[O]

func (*CommandRequirement[O]) WithValidateHandler

func (this *CommandRequirement[O]) WithValidateHandler(v func(context.Context, O) error) *CommandRequirement[O]

WithValidateHandler checks fully decoded options after their Validate method and before any initializer runs. It must not mutate options or acquire resources. Mark invalid input with NewValidationErrorf; unmarked failures remain operational.

func (*CommandRequirement[O]) WithValueArgument

func (this *CommandRequirement[O]) WithValueArgument[T any, TP interface {
	*T
	codec.Value
}](name string, configure ...func(*ArgumentRequirement[T, []string])) *CommandRequirement[O]

WithValueArgument adds a positional Set/String value argument.

func (*CommandRequirement[O]) WithValueFlag

func (this *CommandRequirement[O]) WithValueFlag[T any, TP interface {
	*T
	codec.Value
}](name string, configure ...func(*FlagRequirement[T, []string])) *CommandRequirement[O]

WithValueFlag adds a Set/String value flag, keeping T as the field/value type.

func (*CommandRequirement[O]) WithValueMapArgument added in v0.1.2

func (this *CommandRequirement[O]) WithValueMapArgument[T any, TP interface {
	*T
	codec.Value
}](name string, configure ...func(*ArgumentRequirement[map[string]T, map[string][]string])) *CommandRequirement[O]

func (*CommandRequirement[O]) WithValueMapFlag added in v0.1.2

func (this *CommandRequirement[O]) WithValueMapFlag[T any, TP interface {
	*T
	codec.Value
}](name string, configure ...func(*FlagRequirement[map[string]T, map[string][]string])) *CommandRequirement[O]

func (*CommandRequirement[O]) WithValuePArgument

func (this *CommandRequirement[O]) WithValuePArgument[T codec.Value](name string, factory func() T, configure ...func(*ArgumentRequirement[T, []string])) *CommandRequirement[O]

WithValuePArgument adds a positional value with a fresh pointer factory.

func (*CommandRequirement[O]) WithValuePFlag

func (this *CommandRequirement[O]) WithValuePFlag[T codec.Value](name string, factory func() T, configure ...func(*FlagRequirement[T, []string])) *CommandRequirement[O]

WithValuePFlag adds a Set/String flag with a fresh pointer factory.

func (*CommandRequirement[O]) WithValuePMapArgument added in v0.1.2

func (this *CommandRequirement[O]) WithValuePMapArgument[T codec.Value](name string, factory func() T, configure ...func(*ArgumentRequirement[map[string]T, map[string][]string])) *CommandRequirement[O]

func (*CommandRequirement[O]) WithValuePMapFlag added in v0.1.2

func (this *CommandRequirement[O]) WithValuePMapFlag[T codec.Value](name string, factory func() T, configure ...func(*FlagRequirement[map[string]T, map[string][]string])) *CommandRequirement[O]

func (*CommandRequirement[O]) WithValuePSliceArgument

func (this *CommandRequirement[O]) WithValuePSliceArgument[T codec.Value](name string, factory func() T, configure ...func(*ArgumentRequirement[[]T, [][]string])) *CommandRequirement[O]

WithValuePSliceArgument adds a final variadic slice of factory-created pointers.

func (*CommandRequirement[O]) WithValuePSliceFlag

func (this *CommandRequirement[O]) WithValuePSliceFlag[T codec.Value](name string, factory func() T, configure ...func(*FlagRequirement[[]T, [][]string])) *CommandRequirement[O]

WithValuePSliceFlag adds a repeated slice flag of factory-created pointers.

func (*CommandRequirement[O]) WithValueSliceArgument

func (this *CommandRequirement[O]) WithValueSliceArgument[T any, TP interface {
	*T
	codec.Value
}](name string, configure ...func(*ArgumentRequirement[[]T, [][]string])) *CommandRequirement[O]

WithValueSliceArgument adds a final variadic slice of Set/String values.

func (*CommandRequirement[O]) WithValueSliceFlag

func (this *CommandRequirement[O]) WithValueSliceFlag[T any, TP interface {
	*T
	codec.Value
}](name string, configure ...func(*FlagRequirement[[]T, [][]string])) *CommandRequirement[O]

WithValueSliceFlag adds a standard repeated slice flag of Set/String values.

func (*CommandRequirement[O]) WithVisible added in v0.1.2

func (this *CommandRequirement[O]) WithVisible(v bool) *CommandRequirement[O]

WithVisible controls whether the command appears in help listings.

type CommandRequirementLike

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

CommandRequirementLike accepts value and pointer builders with independent options types. Each builder compiles its own typed handler adapters.

var DefaultCompletionCommand CommandRequirementLike = NewCompletionCommand()

DefaultCompletionCommand is the ordinary command requirement selected by ApplicationRequirement.WithCompletion(true). Its initial value is a ready-to-use NewCompletionCommand. Replace this variable before configuring applications, without concurrent modification. The shortcut captures its current value; Create compiles an independent definition and never mutates the requirement. For per-application changes, use a fresh NewCompletionCommand or your own CommandRequirement through WithCompletionCommand instead of modifying the shared default builder.

type CompletionApplication added in v0.3.0

type CompletionApplication interface {
	Container
	Complete(context.Context, *ParseOpts, CompletionRequest) (codec.CompletionResult, error)
	CompletionScript(CompletionShell) (string, error)
	InstallCompletion(context.Context, CompletionShell, string) (string, error)
	CompletionRequestCommandName() string
}

CompletionApplication exposes a typed application's completion operations to ordinary command handlers that do not know the root options type. It is implemented by Application, not by callers. Use CompletionApplicationFromContext to write custom management commands using the standard renderer/installer.

func CompletionApplicationFromContext added in v0.3.0

func CompletionApplicationFromContext(ctx context.Context) (CompletionApplication, bool)

CompletionApplicationFromContext returns the current invocation's application completion API. It neither constructs options nor creates a new invocation. It is available in ordinary lifecycle/command handlers, including a custom completion command. Missing invocation data returns nil, false.

type CompletionHandler added in v0.3.0

type CompletionHandler = codec.CompletionFunc

CompletionHandler supplies value suggestions using the automatically built completion context. It is the same callback accepted by codec.WithCompletionHandler; no duplicated CLI options model is required.

Handlers on a flag or argument run before that input's codec completer. Return Handled=false to delegate, or Handled=true for an authoritative answer, including no candidates. Commands, flag names, prefix filtering and shell quoting remain automatic. Callbacks must honor cancellation and be concurrent-safe.

type CompletionInstallOptions added in v0.3.0

type CompletionInstallOptions struct {
	Shell     string `argument:"shell" enum:"bash|fish|nu|powershell|zsh" required:"true" description:"Shell to configure."`
	Directory string `argument:"directory" type:"completion-directory" description:"Installation directory; omitted uses the shell's default."`
}

CompletionInstallOptions configures the standard completion install command. Shell is bash, fish, nu, powershell or zsh. Directory overrides the shell's default installation path; for PowerShell and Zsh, it also skips startup-file setup. These are ordinary command options, parsed and validated through the usual CLI lifecycle together with the selected application and command scopes.

type CompletionRequest added in v0.3.0

type CompletionRequest struct {
	Words  []string `json:"words"`
	Word   int      `json:"word"`
	Offset int      `json:"offset"`
}

CompletionRequest identifies a cursor in shell-tokenized input, excluding the executable. Word is a zero-based index into Words; Offset is a byte offset in that word, not a terminal column or UTF-16 offset. Word=len(Words), Offset=0 inserts an empty current word at the end. Words may include input after the cursor. Shell quoting has already been removed, but codecs have not run. Invalid cursor coordinates are errors; incomplete CLI syntax is not.

type CompletionShell added in v0.3.0

type CompletionShell string

CompletionShell selects a native adapter, not a shell to start for each query.

const (
	CompletionBash       CompletionShell = "bash"       // Bash 4.4+; bash-completion enables on-demand loading.
	CompletionFish       CompletionShell = "fish"       // Fish 3.6+ with command-specific completion autoloading.
	CompletionNushell    CompletionShell = "nu"         // Nushell 0.114+ with command-wide completers.
	CompletionPowerShell CompletionShell = "powershell" // Windows PowerShell 5.1+ and PowerShell 7+.
	CompletionZsh        CompletionShell = "zsh"        // Zsh 5.8+ with its native completion system.
)

type Container

type Container interface {
	Name() string
	Names() []string
	Description() string
	Commands() iter.Seq[CommandLike]
	Command(string) (CommandLike, bool)
	CommandOfProfile(string, string) (CommandLike, bool)
	Flags() iter.Seq[*Flag[any, any]]
	Flag(string) (*Flag[any, any], bool)
	FlagOfProfile(string, string) (*Flag[any, any], bool)
	ShortFlag(rune) (*Flag[any, any], bool)
	ShortFlagOfProfile(rune, string) (*Flag[any, any], bool)
	Arguments() iter.Seq[*Argument[any, any]]
	Argument(int) (*Argument[any, any], bool)
	OptionsType() reflect.Type
	// contains filtered or unexported methods
}

Container exposes metadata common to applications and commands. Options and handler types remain specific to their respective typed definitions. Applications and commands implement it; callers cannot implement it externally.

func ContainerFromContext

func ContainerFromContext(ctx context.Context) (Container, bool)

ContainerFromContext identifies the application or command whose hook or handler is currently running, independently of its options type.

type ContainerRequirement

type ContainerRequirement[R any] interface {
	ContainerRequirementSetters
	WithCommand(...CommandRequirementLike) R
	WithCodec(any, ...string) R
	WithFlag(...FlagRequirementLike) R
	WithArgument(...ArgumentRequirementLike) R
}

type ContainerRequirementSetters

type ContainerRequirementSetters interface {
	AddCommand(...CommandRequirementLike)
	SetCommands([]CommandRequirementLike)

	AddCodec(any, ...string)
	SetCodecs([]codec.Registration)

	AddFlag(...FlagRequirementLike)
	SetFlags([]FlagRequirementLike)

	AddArgument(...ArgumentRequirementLike)
	SetArguments([]ArgumentRequirementLike)
}

type ErrorHandler

type ErrorHandler func(context.Context, InvocationLike, error) error

ErrorHandler observes input and operational failures after invocation cleanup. A non-nil return replaces the error; nil preserves it. The context exposes the invocation and the container whose execution failed. Direct container calls can have a nil invocation and retain caller ownership of their supplied options.

var DefaultErrorHandler ErrorHandler = (&RespondErrorHandlerRequirement{
	ValidationExitCode: 2, CanceledExitCode: 130, ExecutionExitCode: 1,
}).MustCreate()

DefaultErrorHandler is captured by Create when no error handler is set. Its built-in value writes to context stderr (or discards output when unavailable), shows help for ErrValidation, and exits with status 2 for input errors, 130 for context.Canceled, or 1 for other operational errors. Configure this variable before Create, without concurrent modification. Nil disables the global fallback; individual applications can disable error handling.

type Flag

type Flag[V, R any] struct {
	// contains filtered or unexported fields
}

Flag describes a CLI flag. Metadata and defaults remain separate from parsed values; use Invocation.Flag to read V and Flag.Default to read a default R.

func (*Flag[V, R]) Codec

func (this *Flag[V, R]) Codec() codec.Codec[V, R]

func (*Flag[V, R]) CompletionHandler added in v0.3.0

func (this *Flag[V, R]) CompletionHandler() CompletionHandler

CompletionHandler returns the explicitly configured flag handler, or nil when value completion uses only the codec and standard handler. Codec returns the effective codec, including the captured flag override.

func (*Flag[V, R]) Default

func (this *Flag[V, R]) Default(ctx context.Context) (value R, found bool, err error)

Default returns an independent default R, or found=false if none is declared. It does not acquire runtime resources.

func (*Flag[V, R]) Description

func (this *Flag[V, R]) Description() string

func (*Flag[V, R]) EnvVars

func (this *Flag[V, R]) EnvVars() []string

func (*Flag[V, R]) FormatDefault

func (this *Flag[V, R]) FormatDefault(ctx context.Context) ([]string, bool, error)

FormatDefault returns help-safe default text without opening resources. Invalid declared defaults return an error, even if CLI input could override them.

func (*Flag[V, R]) HasDefault

func (this *Flag[V, R]) HasDefault() bool

func (*Flag[V, R]) IsBoolFlag

func (this *Flag[V, R]) IsBoolFlag() bool

func (*Flag[V, R]) IsCumulative

func (this *Flag[V, R]) IsCumulative() bool

func (*Flag[V, R]) IsRequired

func (this *Flag[V, R]) IsRequired() bool

func (*Flag[V, R]) IsVisible

func (this *Flag[V, R]) IsVisible() bool

func (*Flag[V, R]) Name

func (this *Flag[V, R]) Name() string

func (*Flag[V, R]) Names

func (this *Flag[V, R]) Names() []string

func (*Flag[V, R]) Placeholder

func (this *Flag[V, R]) Placeholder() string

func (*Flag[V, R]) Profiles added in v0.2.0

func (this *Flag[V, R]) Profiles() []string

Profiles returns a copy of the explicit profile assignments; empty means always active.

func (*Flag[V, R]) Shorts

func (this *Flag[V, R]) Shorts() []rune

func (*Flag[V, R]) ValueType

func (this *Flag[V, R]) ValueType() reflect.Type

type FlagRequirement

type FlagRequirement[V, R any] struct {
	// Names contains the primary name followed by aliases.
	Names []string
	// Profiles activates this definition when any listed profile is selected.
	// An empty list makes it active for every parse.
	Profiles []string
	// Shorts contains optional single-rune aliases.
	Shorts []rune

	// EnvVars contains environment fallback names in lookup order.
	EnvVars []string

	Description string
	Required    bool
	Visible     bool
	Placeholder string
	Codec       codec.Codec[V, R]
	// CompletionHandler optionally overrides value suggestions for this flag.
	// Returning Handled=false delegates to the codec and automatic completion.
	CompletionHandler CompletionHandler
	// CodecFactory configures a codec during Create, without acquiring resources.
	CodecFactory func() (codec.Codec[V, R], error)
	Field        []string
	// contains filtered or unexported fields
}

FlagRequirement configures a flag producing V from input requirements R. Use FlagRequirement.WithDefault for typed R or FlagRequirement.WithDefaultStr for input tokens. Required flags cannot declare defaults, including zero/nil. Repetition requires codec.Cumulative; standard slice flags accept one element per occurrence. Bind fields explicitly with FlagRequirement.WithField.

func NewFlag

func NewFlag[V, R any](codec codec.Codec[V, R], nameAndDescription ...string) *FlagRequirement[V, R]

NewFlag starts a visible flag using codec. The first optional string sets the name; further strings form the description, joined with spaces. Add aliases with FlagRequirement.WithAliases. With no strings, configure the name later; Create validates the completed builder.

Example
package main

import (
	"context"
	"fmt"

	cli "github.com/echocat/cli4g"
	"github.com/echocat/cli4g/codec"
)

func main() {
	flag := cli.NewFlag(codec.NewString(), "greeting", "Greeting to use.").
		WithAliases("message").
		WithDefault("Hello")
	app := cli.NewSimpleApplication("greet").
		WithFlag(flag).
		MustCreate()
	defer func() {
		if err := app.Close(); err != nil {
			panic(err)
		}
	}()
	invocation := app.MustParse(context.Background(), nil, "--message=Hey")
	defer func() {
		if err := invocation.Close(); err != nil {
			panic(err)
		}
	}()
	_, value := invocation.Flag("greeting")
	fmt.Println(value)
}
Output:
Hey

func (*FlagRequirement[V, R]) SetCodec

func (this *FlagRequirement[V, R]) SetCodec(v codec.Codec[V, R])

func (*FlagRequirement[V, R]) SetCodecFactory

func (this *FlagRequirement[V, R]) SetCodecFactory(v func() (codec.Codec[V, R], error))

func (*FlagRequirement[V, R]) SetCompletionHandler added in v0.3.0

func (this *FlagRequirement[V, R]) SetCompletionHandler(v CompletionHandler)

SetCompletionHandler is the setter counterpart of WithCompletionHandler.

func (*FlagRequirement[V, R]) SetDefault

func (this *FlagRequirement[V, R]) SetDefault(v R)

func (*FlagRequirement[V, R]) SetDefaultStr

func (this *FlagRequirement[V, R]) SetDefaultStr(v ...string)

func (*FlagRequirement[V, R]) SetDescription

func (this *FlagRequirement[V, R]) SetDescription(v string)

func (*FlagRequirement[V, R]) SetEnvVars

func (this *FlagRequirement[V, R]) SetEnvVars(v []string)

func (*FlagRequirement[V, R]) SetField

func (this *FlagRequirement[V, R]) SetField(v []string) *FlagRequirement[V, R]

func (*FlagRequirement[V, R]) SetNames

func (this *FlagRequirement[V, R]) SetNames(v []string)

func (*FlagRequirement[V, R]) SetPlaceholder

func (this *FlagRequirement[V, R]) SetPlaceholder(v string)

func (*FlagRequirement[V, R]) SetProfiles added in v0.2.0

func (this *FlagRequirement[V, R]) SetProfiles(v []string)

func (*FlagRequirement[V, R]) SetRequired

func (this *FlagRequirement[V, R]) SetRequired(v bool)

func (*FlagRequirement[V, R]) SetShorts

func (this *FlagRequirement[V, R]) SetShorts(v []rune)

func (*FlagRequirement[V, R]) SetVisible

func (this *FlagRequirement[V, R]) SetVisible(v bool)

func (*FlagRequirement[V, R]) WithAliases

func (this *FlagRequirement[V, R]) WithAliases(v ...string) *FlagRequirement[V, R]

func (*FlagRequirement[V, R]) WithCodec

func (this *FlagRequirement[V, R]) WithCodec(v codec.Codec[V, R]) *FlagRequirement[V, R]

WithCodec replaces the decoder and clears any FlagRequirement.WithCodecFactory.

func (*FlagRequirement[V, R]) WithCodecFactory

func (this *FlagRequirement[V, R]) WithCodecFactory(v func() (codec.Codec[V, R], error)) *FlagRequirement[V, R]

WithCodecFactory configures the decoder during Create and replaces FlagRequirement.WithCodec. The factory must not acquire runtime resources; configuration errors fail Create.

func (*FlagRequirement[V, R]) WithCompletionHandler added in v0.3.0

func (this *FlagRequirement[V, R]) WithCompletionHandler(v CompletionHandler) *FlagRequirement[V, R]

WithCompletionHandler sets a context-aware value handler for this flag without changing its parsing codec or CLI syntax. It runs before the codec completer; Handled=false delegates, and Handled=true with no candidates suppresses further suggestions. A nil handler restores codec/automatic completion. Name completion never invokes it. Create captures the callback; it must be concurrent-safe.

func (*FlagRequirement[V, R]) WithDefault

func (this *FlagRequirement[V, R]) WithDefault(v R) *FlagRequirement[V, R]

WithDefault sets a resource-free typed default R, independently copied for each parse. R can differ from V, for example codec.FileRequirement instead of *os.File.

func (*FlagRequirement[V, R]) WithDefaultStr

func (this *FlagRequirement[V, R]) WithDefaultStr(v ...string) *FlagRequirement[V, R]

WithDefaultStr sets default input tokens without shell/CSV splitting. It replaces any previous typed or string default.

func (*FlagRequirement[V, R]) WithDescription

func (this *FlagRequirement[V, R]) WithDescription(v string) *FlagRequirement[V, R]

func (*FlagRequirement[V, R]) WithEnvVar

func (this *FlagRequirement[V, R]) WithEnvVar(v ...string) *FlagRequirement[V, R]

WithEnvVar adds environment fallback names. CLI input takes precedence.

func (*FlagRequirement[V, R]) WithField

func (this *FlagRequirement[V, R]) WithField(v ...string) *FlagRequirement[V, R]

WithField binds V to an exported options field; v is its nested field path. The binding overrides tags on that field. Omit it to keep the flag unbound.

Example
package main

import (
	"context"
	"fmt"

	cli "github.com/echocat/cli4g"
)

func main() {
	type options struct{ Port uint32 }
	app := cli.NewApplication[options]("server").
		WithUint32Flag("port", func(flag *cli.FlagRequirement[uint32, uint32]) {
			flag.
				WithField("Port").
				WithDefault(8080)
		}).
		MustCreate()
	defer func() {
		if err := app.Close(); err != nil {
			panic(err)
		}
	}()
	invocation, err := app.Parse(context.Background(), nil)
	if err != nil {
		panic(err)
	}
	defer func() {
		if err := invocation.Close(); err != nil {
			panic(err)
		}
	}()
	_, opts := invocation.Application()
	fmt.Println(opts.Port)
}
Output:
8080

func (*FlagRequirement[V, R]) WithName

func (this *FlagRequirement[V, R]) WithName(v ...string) *FlagRequirement[V, R]

WithName replaces the primary name and optional aliases. WithAliases appends aliases.

func (*FlagRequirement[V, R]) WithPlaceholder

func (this *FlagRequirement[V, R]) WithPlaceholder(v string) *FlagRequirement[V, R]

WithPlaceholder sets help value text, preserving its case. The default uses the last word of the primary flag name, split at '.', '-', '_' and case boundaries, and lowercased. Help displays --flag=<text>, enclosing text once in <...>.

func (*FlagRequirement[V, R]) WithProfiles added in v0.2.0

func (this *FlagRequirement[V, R]) WithProfiles(v ...string) *FlagRequirement[V, R]

WithProfiles replaces the profile selection. No profiles means always active.

func (*FlagRequirement[V, R]) WithRequired

func (this *FlagRequirement[V, R]) WithRequired(v bool) *FlagRequirement[V, R]

WithRequired demands CLI or environment input. Defaults are incompatible; options-factory values do not satisfy this requirement.

func (*FlagRequirement[V, R]) WithShort

func (this *FlagRequirement[V, R]) WithShort(v ...rune) *FlagRequirement[V, R]

func (*FlagRequirement[V, R]) WithVisible

func (this *FlagRequirement[V, R]) WithVisible(v bool) *FlagRequirement[V, R]

type FlagRequirementLike

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

FlagRequirementLike allows flags with different value types in one builder. It is implemented by FlagRequirement, not by callers.

type HelpArgumentInfo

type HelpArgumentInfo struct {
	Definition *Argument[any, any]
	MinValues  int
	MaxValues  int
}

type HelpArgumentTemplateData

type HelpArgumentTemplateData struct {
	HelpArgumentInfo
	Name                  string
	Label                 string
	Description           string
	Placeholder           string
	ValueType             reflect.Type
	Required              bool
	HasDefault            bool
	Default               []string
	DefaultText           string
	Choices               []HelpEnumChoice
	ChoicesText           string
	HasChoiceDescriptions bool
}

HelpArgumentTemplateData is the input to the argument template.

type HelpCommandTemplateData

type HelpCommandTemplateData struct {
	Definition  CommandLike
	Names       []string
	FullName    string
	Label       string
	Description string
}

HelpCommandTemplateData is the input to the command-entry template.

type HelpEnumChoice added in v0.1.4

type HelpEnumChoice struct {
	Values      []string
	Text        string
	Description string
}

HelpEnumChoice describes an accepted scalar or collection-element value.

type HelpFlagInfo

type HelpFlagInfo struct {
	Definition *Flag[any, any]
	Owner      Container
	Inherited  bool
	MinValues  int
	MaxValues  int // -1 means variadic
}

type HelpFlagTemplateData

type HelpFlagTemplateData struct {
	HelpFlagInfo
	Names                 []string
	Shorts                []rune
	Label                 string
	Description           string
	Placeholder           string
	ValueType             reflect.Type
	Required              bool
	EnvVars               []string
	HasDefault            bool
	Default               []string
	DefaultText           string
	Choices               []HelpEnumChoice
	ChoicesText           string
	HasChoiceDescriptions bool
}

HelpFlagTemplateData is the input to the flag template, including safe default text.

type HelpHandler

type HelpHandler func(context.Context, InvocationLike) error

HelpHandler executes a valid help invocation. Its metadata includes the selected path's resolved codecs; no options or normal lifecycle are created.

var DefaultHelpHandler HelpHandler = func(ctx context.Context, invocation InvocationLike) error {
	if ctx == nil {
		ctx = context.Background()
	}
	if err := ctx.Err(); err != nil {
		return err
	}
	return defaultHelpHandler()(ctx, invocation)
}

DefaultHelpHandler is the overridable fallback captured by ApplicationRequirement.Create when no application handler is set. Configure it before Create, without concurrent modification. Its built-in value compiles templates once on first use, writes to context stderr (or discards output when unavailable) and returns normally.

type HelpInfo

type HelpInfo struct {
	Application Container
	Target      Container
	Path        []Container
	Commands    []CommandLike
	Flags       []HelpFlagInfo
	Arguments   []HelpArgumentInfo
}

HelpInfo is a fresh metadata view of the selected path. Definition pointers refer to immutable compiled snapshots. Mutating the returned lists does not change the application. No options, codecs, defaults or handlers are executed.

type HelpTemplateData

type HelpTemplateData struct {
	HelpInfo
	Invocation     InvocationLike
	FullName       string
	NamePath       []string
	Description    string
	Usage          string
	Commands       []HelpCommandTemplateData
	Flags          []HelpFlagTemplateData
	InheritedFlags []HelpFlagTemplateData
	Arguments      []HelpArgumentTemplateData
}

HelpTemplateData supplies visible commands, inputs, and display-safe defaults to application, command, and usage templates. Embedded HelpInfo also contains hidden definitions. DefaultText uses codec DisplayRequirement, not serialization.

type Initializable

type Initializable interface {
	// Initialize prepares options. Retained resources must be released by
	// options' Close method, including after partial initialization.
	Initialize(context.Context) error
}

Initializable prepares options after successful validation. Pointer-receiver methods retain assignments, including for struct options. See Invocation.Close and ApplicationRequirement.WithInitializeHandler.

type Invocation

type Invocation[O any] struct {
	// contains filtered or unexported fields
}

Invocation owns the options and resources of one successful parse. Execute it with Invocation.Execute and always call Invocation.Close. Option getters read current fields; input getters retain decoded values. Pointers, maps, and slices can share data within this invocation.

func (Invocation[O]) Application

func (this Invocation[O]) Application() (*Application[O], O)

Application returns the application and its current options. Struct options are returned by value; pointer options refer to the owned instance. Reference fields in returned structs still share their underlying data. Help invocations have no options and return the zero value of O.

func (Invocation[O]) Argument

func (this Invocation[O]) Argument(i int) (*Argument[any, any], any)

Argument returns a decoded leaf argument by definition index, or nil, nil if absent.

func (Invocation[O]) Arguments

func (this Invocation[O]) Arguments() iter.Seq2[*Argument[any, any], any]

Arguments and Argument expose resolved runtime values of the deepest selected container. Arguments iterates only values present in the invocation. Argument uses the container's definition index; omitted arguments return nil, nil.

func (*Invocation[O]) Close

func (this *Invocation[O]) Close() error

Close closes owned options in reverse scope order, exactly once. Repeated calls return the original cleanup result. Callers must Close every invocation returned by a successful Parse, including after an Execute error. Execute and Close must not run concurrently on the same invocation.

func (Invocation[O]) ContainsProfile added in v0.2.0

func (this Invocation[O]) ContainsProfile(profile string) bool

ContainsProfile reports whether an exact, case-sensitive profile was selected for this invocation, independently of whether the command path uses it.

func (Invocation[O]) ErrorHandler

func (this Invocation[O]) ErrorHandler() ErrorHandler

ErrorHandler returns the application's captured input/operational response.

func (*Invocation[O]) Execute

func (this *Invocation[O]) Execute(ctx context.Context) (err error)

Execute runs handlers from root to leaf and checks cancellation before and after each handler. Handlers must honor their context during their own work. A nil context is replaced with context.Background. With a configured error handler, failures close this invocation before reporting. Without one, the caller retains cleanup responsibility. Successful invocations must be closed. A help invocation executes only the application's HelpHandler. A completion request invocation executes only its protocol operation. Public completion commands execute through the ordinary command lifecycle. Context streams apply to handlers; file values already resolved by Parse retain their original streams. Use the same stream context for both phases.

func (Invocation[O]) Flag

func (this Invocation[O]) Flag(name string) (*Flag[any, any], any)

Flag returns a decoded flag by name or alias; the deepest selected definition wins. Missing values return nil, nil. Factory-only fields are not decoded inputs.

func (Invocation[O]) Flags

func (this Invocation[O]) Flags() iter.Seq2[*Flag[any, any], any]

Flags exposes successfully resolved runtime values, including after failed parsing or cleanup. Prepared requirements are never published by these getters.

func (Invocation[O]) HelpHandler

func (this Invocation[O]) HelpHandler() HelpHandler

HelpHandler returns the application's captured handler, including its global fallback. It is usable directly for parse-error responses after cleanup.

func (Invocation[O]) HelpInfo

func (this Invocation[O]) HelpInfo() HelpInfo

func (Invocation[O]) HelpRequested

func (this Invocation[O]) HelpRequested() bool

func (Invocation[O]) NameStack

func (this Invocation[O]) NameStack() []string

NameStack returns the selected canonical command names, excluding the application.

func (Invocation[O]) Profiles added in v0.2.0

func (this Invocation[O]) Profiles() iter.Seq[string]

Profiles lists this invocation's selected profiles exactly once in alphabetical order. Unlike Application.Profiles, it does not list every known profile. The snapshot remains readable after Close and on help/error invocations.

func (Invocation[O]) Root

func (this Invocation[O]) Root() Container

Root exposes the application's metadata when its concrete options type is unknown to a command handler obtaining the invocation from its context.

func (Invocation[O]) ShortFlag

func (this Invocation[O]) ShortFlag(short rune) (*Flag[any, any], any)

ShortFlag returns a decoded flag by its short alias, or nil, nil if absent.

func (Invocation[O]) Stack

func (this Invocation[O]) Stack() []InvocationStackFrame

Stack returns a new list of the selected commands and their current options. It does not deep-copy options or include the root application. Help invocations contain the selected commands with nil Options.

type InvocationLike

type InvocationLike interface {
	Root() Container
	HelpRequested() bool
	HelpInfo() HelpInfo
	HelpHandler() HelpHandler
	ErrorHandler() ErrorHandler
	Stack() []InvocationStackFrame
	NameStack() []string
	Profiles() iter.Seq[string]
	ContainsProfile(string) bool
	Flags() iter.Seq2[*Flag[any, any], any]
	Flag(string) (*Flag[any, any], any)
	ShortFlag(rune) (*Flag[any, any], any)
	Arguments() iter.Seq2[*Argument[any, any], any]
	Argument(int) (*Argument[any, any], any)
	// contains filtered or unexported methods
}

InvocationLike gives handlers and tools access to any invocation's metadata and decoded values. It is implemented by Invocation, not by callers.

func InvocationFromContext

func InvocationFromContext(ctx context.Context) (InvocationLike, bool)

InvocationFromContext returns the complete invocation associated with a lifecycle hook or handler. No new invocation is attached during decoding.

type InvocationStackFrame

type InvocationStackFrame struct {
	Command CommandLike
	Options any
}

InvocationStackFrame contains a selected command and its current options. Use Command.OptionsFrom for typed access. Reference data remains shared.

type NoOptions

type NoOptions struct{}

NoOptions is the concrete options type for definitions using only explicit flags and arguments. Their handlers can obtain the complete invocation and its values with InvocationFromContext.

type ParseOpts

type ParseOpts struct {
	// Profiles selects explicit, case-sensitive profiles. Unknown names fail
	// before scanning tokens. Repeated names are treated as one selection.
	Profiles []string
	// LookupEnv replaces os.LookupEnv. Return exists=false to disable environment input.
	// CLI flags take precedence; callbacks used by concurrent parses must be safe.
	LookupEnv func(ctx context.Context, name string) (value string, exists bool)
}

ParseOpts selects profiles and customizes environment input. Nil selects no profiles and uses os.LookupEnv.

type RespondErrorHandlerRequirement

type RespondErrorHandlerRequirement struct {
	Output             io.Writer   // nil selects context stderr, or io.Discard when unavailable
	HelpHandler        HelpHandler // nil selects the invocation's application handler
	ValidationExitCode int         // zero returns validation errors normally
	CanceledExitCode   int         // zero returns context.Canceled errors normally
	ExecutionExitCode  int         // zero returns operational errors normally
}

RespondErrorHandlerRequirement configures output responses and exit codes. Validation errors show help; cancellations and other errors do not. Zero codes return the original error joined with any response errors. Nonzero codes call os.Exit, which does not run caller defers.

func NewRespondErrorHandler

func NewRespondErrorHandler() *RespondErrorHandlerRequirement

NewRespondErrorHandler starts a returning responder with all exit codes zero. Attach the created handler with ApplicationRequirement.WithErrorHandler.

func (*RespondErrorHandlerRequirement) Create

func (*RespondErrorHandlerRequirement) MustCreate

func (this *RespondErrorHandlerRequirement) MustCreate() ErrorHandler

MustCreate creates the handler and panics on invalid configuration.

func (*RespondErrorHandlerRequirement) SetCanceledExitCode

func (this *RespondErrorHandlerRequirement) SetCanceledExitCode(v int)

func (*RespondErrorHandlerRequirement) SetExecutionExitCode

func (this *RespondErrorHandlerRequirement) SetExecutionExitCode(v int)

func (*RespondErrorHandlerRequirement) SetHelpHandler

func (this *RespondErrorHandlerRequirement) SetHelpHandler(v HelpHandler)

func (*RespondErrorHandlerRequirement) SetOutput

func (this *RespondErrorHandlerRequirement) SetOutput(v io.Writer)

func (*RespondErrorHandlerRequirement) SetValidationExitCode

func (this *RespondErrorHandlerRequirement) SetValidationExitCode(v int)

func (*RespondErrorHandlerRequirement) WithCanceledExitCode

func (this *RespondErrorHandlerRequirement) WithCanceledExitCode(v int) *RespondErrorHandlerRequirement

func (*RespondErrorHandlerRequirement) WithExecutionExitCode

func (this *RespondErrorHandlerRequirement) WithExecutionExitCode(v int) *RespondErrorHandlerRequirement

func (*RespondErrorHandlerRequirement) WithHelpHandler

func (*RespondErrorHandlerRequirement) WithOutput

WithOutput selects a caller-owned writer. Nil uses context stderr at each response, or io.Discard when no output is supplied by the context.

func (*RespondErrorHandlerRequirement) WithValidationExitCode

func (this *RespondErrorHandlerRequirement) WithValidationExitCode(v int) *RespondErrorHandlerRequirement

type TemplatedHelpHandlerRequirement

type TemplatedHelpHandlerRequirement struct {
	// Output remains caller-owned. Custom writers and handlers need their own synchronization.
	Output   io.Writer // nil selects context stderr, or io.Discard when unavailable
	ExitCode int       // non-zero calls os.Exit after successful rendering/writing

	// Width overrides the output width in characters. Zero detects terminal width
	// from the selected output's Fd method, falling back to 80. Negative is invalid.
	// Detection occurs for each rendering, including when context streams change.
	Width int

	ApplicationTemplate  string           // template "application": root help
	CommandTemplate      string           // template "command": selected command help
	UsageTemplate        string           // template "usage": invocation syntax
	CommandEntryTemplate string           // template "command-entry": available command
	FlagTemplate         string           // template "flag": flag entry
	ArgumentTemplate     string           // template "argument": positional entry
	Funcs                template.FuncMap // custom functions must be concurrent-safe
	// contains filtered or unexported fields
}

TemplatedHelpHandlerRequirement configures text/template-based help. Empty templates stay empty; defaults are not inserted automatically. Main templates receive HelpTemplateData; entry templates receive the matching Help*TemplateData type. Built-in functions include join and quote. Create reports invalid syntax; execution reports render/write/default errors. Formatting is enabled by default: tabbed runs form tables with independent column widths per indentation level. Long lines wrap with hanging indentation. Widths count Unicode code points, not terminal cells or ANSI escape sequences. Unbreakable words and labels are preserved even when wider than the output.

func NewTemplatedHelpHandler

func NewTemplatedHelpHandler() *TemplatedHelpHandlerRequirement

NewTemplatedHelpHandler starts an empty help-template builder. Set templates explicitly, using the Default*HelpTemplate constants as needed.

func (*TemplatedHelpHandlerRequirement) Create

Create compiles an independent template set. Template execution may run concurrently; framework help/error writes are serialized and rendering errors do not produce partial output. Custom functions must be concurrency-safe.

func (*TemplatedHelpHandlerRequirement) MustCreate

func (this *TemplatedHelpHandlerRequirement) MustCreate() HelpHandler

MustCreate compiles the templates and panics on invalid configuration.

func (*TemplatedHelpHandlerRequirement) SetApplicationTemplate

func (this *TemplatedHelpHandlerRequirement) SetApplicationTemplate(v string)

func (*TemplatedHelpHandlerRequirement) SetArgumentTemplate

func (this *TemplatedHelpHandlerRequirement) SetArgumentTemplate(v string)

func (*TemplatedHelpHandlerRequirement) SetCommandEntryTemplate

func (this *TemplatedHelpHandlerRequirement) SetCommandEntryTemplate(v string)

func (*TemplatedHelpHandlerRequirement) SetCommandTemplate

func (this *TemplatedHelpHandlerRequirement) SetCommandTemplate(v string)

func (*TemplatedHelpHandlerRequirement) SetExitCode

func (this *TemplatedHelpHandlerRequirement) SetExitCode(v int)

func (*TemplatedHelpHandlerRequirement) SetFlagTemplate

func (this *TemplatedHelpHandlerRequirement) SetFlagTemplate(v string)

func (*TemplatedHelpHandlerRequirement) SetFormatting added in v0.2.1

func (this *TemplatedHelpHandlerRequirement) SetFormatting(v bool)

func (*TemplatedHelpHandlerRequirement) SetFuncs

func (*TemplatedHelpHandlerRequirement) SetOutput

func (this *TemplatedHelpHandlerRequirement) SetOutput(v io.Writer)

func (*TemplatedHelpHandlerRequirement) SetUsageTemplate

func (this *TemplatedHelpHandlerRequirement) SetUsageTemplate(v string)

func (*TemplatedHelpHandlerRequirement) SetWidth added in v0.2.1

func (this *TemplatedHelpHandlerRequirement) SetWidth(v int)

func (*TemplatedHelpHandlerRequirement) WithApplicationTemplate

func (*TemplatedHelpHandlerRequirement) WithArgumentTemplate

func (*TemplatedHelpHandlerRequirement) WithCommandEntryTemplate

func (this *TemplatedHelpHandlerRequirement) WithCommandEntryTemplate(v string) *TemplatedHelpHandlerRequirement

func (*TemplatedHelpHandlerRequirement) WithCommandTemplate

func (*TemplatedHelpHandlerRequirement) WithExitCode

func (*TemplatedHelpHandlerRequirement) WithFlagTemplate

func (*TemplatedHelpHandlerRequirement) WithFormatting added in v0.2.1

WithFormatting enables automatic column alignment and word wrapping. Enabled by default. Disable it for byte-exact or deliberately preformatted templates; disabling also skips terminal-size queries. Create snapshots this setting.

Example
package main

import (
	"context"
	"os"

	cli "github.com/echocat/cli4g"
)

func main() {
	help := cli.NewTemplatedHelpHandler().
		WithOutput(os.Stdout).
		WithWidth(12).
		WithFormatting(false).
		WithApplicationTemplate("Exact template spacing:    preserved.\n").
		MustCreate()
	cli.NewSimpleApplication("tool").WithHelpHandler(help).
		MustCreateParseAndExecute(context.Background(), nil, "--help")
}
Output:
Exact template spacing:    preserved.

func (*TemplatedHelpHandlerRequirement) WithFuncs

func (*TemplatedHelpHandlerRequirement) WithOutput

WithOutput selects a caller-owned writer. Nil uses context stderr at each invocation, or io.Discard when no output is supplied by the context.

func (*TemplatedHelpHandlerRequirement) WithUsageTemplate

func (*TemplatedHelpHandlerRequirement) WithWidth added in v0.2.1

WithWidth sets a fixed help width. Zero detects terminal width, falling back to 80 for non-terminals, writers without Fd, and unsuccessful size queries.

Example
package main

import (
	"context"
	"os"

	cli "github.com/echocat/cli4g"
)

func main() {
	help := cli.NewTemplatedHelpHandler().
		WithOutput(os.Stdout).
		WithWidth(36).
		WithApplicationTemplate("{{.FullName}}\n  run\tInspect configured flows and recordings.\n").
		MustCreate()
	cli.NewSimpleApplication("tool").WithHelpHandler(help).
		MustCreateParseAndExecute(context.Background(), nil, "--help")
}
Output:
tool
  run  Inspect configured flows and
       recordings.

type Validatable

type Validatable interface {
	// Validate checks the fully decoded options before any initializer runs.
	// It must not acquire resources or mutate the options.
	// Mark invalid input with NewValidationError or NewValidationErrorf; unmarked
	// failures remain operational and retain their original causes.
	// Warning: marked messages are displayed verbatim and must not include input
	// values or confidential data. Unmarked failures receive a neutral message.
	Validate(context.Context) error
}

Validatable checks decoded options before initialization. Mark invalid user input with NewValidationErrorf; return technical errors normally.

type ValidationError

type ValidationError = codec.ValidationError

ValidationError is the codec package's input-error wrapper.

Source Files

Directories

Path Synopsis
Package codec parses CLI inputs into typed values and provides codecs for custom types, dates, durations, slices, maps, and invocation-owned files.
Package codec parses CLI inputs into typed values and provides codecs for custom types, dates, durations, slices, maps, and invocation-owned files.
internal
coveragemerge command
Command coveragemerge unions Go coverage profiles before reporting them.
Command coveragemerge unions Go coverage profiles before reporting them.
examplecmd command
Command examplecmd implements mise's example run/list tasks using only Go.
Command examplecmd implements mise's example run/list tasks using only Go.
exampleutil
Package exampleutil shares example discovery between Go tests and the runner.
Package exampleutil shares example discovery between Go tests and the runner.
shelltestcmd command
Command shelltestcmd runs completion E2E tests in an isolated Linux container.
Command shelltestcmd runs completion E2E tests in an isolated Linux container.
testexec
Package testexec runs native test subprocesses with bounded output and cleanup.
Package testexec runs native test subprocesses with bounded output and cleanup.

Jump to

Keyboard shortcuts

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