Documentation
¶
Index ¶
- Constants
- func Bind(c *cobra.Command, opts any) error
- func Define(c *cobra.Command, o Options, defineOpts ...DefineOption) error
- func EnvPrefix() string
- func ExecuteC(cmd *cobra.Command) (*cobra.Command, error)
- func ExecuteOrExit(cmd *cobra.Command)
- func GetConfigViper(c *cobra.Command) *viper.Viper
- func GetOrSetAppName(name, cName string) string
- func GetViper(c *cobra.Command) *viper.Viper
- func HandleError(cmd *cobra.Command, err error, w io.Writer) int
- func IsDebugActive(c *cobra.Command) bool
- func IsHelpTopicCommand(c *cobra.Command) bool
- func RegisterEnum[E ~string](values map[E][]string)
- func RegisterIntEnum[E ~int | ~int8 | ~int16 | ~int32 | ~int64](values map[E][]string)
- func RegisterType[T any](hooks TypeHooks[T])
- func Reset()
- func SetEnvPrefix(str string)
- func Setup(cmd *cobra.Command, opts ...SetupOption) error
- func SetupConfig(rootC *cobra.Command, cfgOpts config.Options) error
- func SetupDebug(rootC *cobra.Command, debugOpts debug.Options) error
- func SetupFlagErrors(rootC *cobra.Command)
- func SetupHelpTopics(rootC *cobra.Command, opts helptopics.Options) error
- func SetupJSONSchema(rootC *cobra.Command, opts jsonschema.Options) error
- func SetupMCP(rootC *cobra.Command, opts structclimcp.Options) error
- func SetupUsage(c *cobra.Command)
- func Unmarshal(c *cobra.Command, opts Options, hooks ...mapstructure.DecodeHookFunc) error
- func UseConfig(readWhen func() bool) (inUse bool, mes string, err error)
- func UseConfigSimple(c *cobra.Command) (inUse bool, message string, err error)
- func UseDebug(c *cobra.Command, w io.Writer)
- type Base64
- type CommandSchema
- type CompleteHookFunc
- type ContextInjector
- type ContextOptions
- type DecodeHookFunc
- type DefineHookFunc
- type DefineOption
- type EnumValuer
- type FieldCompleter
- type FieldHook
- type FieldHookProvider
- type FlagSchema
- type Hex
- type Options
- type PresetInfo
- type SetupOption
- func WithAppName(name string) SetupOption
- func WithConfig(opts ...config.Options) SetupOption
- func WithDebug(opts debug.Options) SetupOption
- func WithFlagErrors() SetupOption
- func WithHelpTopics(opts ...helptopics.Options) SetupOption
- func WithJSONSchema(opts ...jsonschema.Options) SetupOption
- func WithMCP(opts ...structclimcp.Options) SetupOption
- type StructuredError
- type Transformable
- type TransformableOptions
- type TypeHooks
- type Validatable
- type ValidatableOptions
- type Violation
Constants ¶
const ( // DefaultValidateTagName is the struct tag name for validation rules. // Matches the go-playground/validator default. Exported so callers // configuring their own validator can reference the structcli default // (e.g. validator.New().SetTagName(structcli.DefaultValidateTagName)). DefaultValidateTagName = "validate" // DefaultModTagName is the struct tag name for transformation rules. // Matches the go-playground/mold default. Exported so callers // configuring their own mold can reference the structcli default. DefaultModTagName = "mod" )
const ( // ConfigFlagAnnotation is the command annotation key that stores the // config flag name set by WithConfig. Exported for use by generate/. ConfigFlagAnnotation = "leodido/structcli/config-flag" )
const Version = "0.18.0"
Version is the current release version of structcli. It MUST match the git tag (without the "v" prefix) at release time. The release CI workflow verifies this.
Variables ¶
This section is empty.
Functions ¶
func Bind ¶ added in v0.17.0
Bind defines flags from opts on cmd and registers opts for auto-unmarshal during ExecuteC/ExecuteOrExit.
opts must be a non-nil struct pointer. If opts implements Options (has Attach), Attach is called. Otherwise flags are defined directly from struct tags.
Multiple Bind calls per command are supported; unmarshal order matches call order (FIFO). Define runs immediately; flags exist on the command after Bind returns.
As a side effect, the first Bind call on a command tree installs a cobra.Command.PersistentPreRunE on root that warns to stderr when the tree is executed via cmd.Execute() instead of ExecuteC. This warning is best-effort: it is suppressed when a child command defines its own PersistentPreRunE (Cobra only runs the nearest ancestor's hook), and it can be overwritten if the caller sets root.PersistentPreRunE after calling Bind.
func Define ¶
func Define(c *cobra.Command, o Options, defineOpts ...DefineOption) error
Define creates flags from struct field tags and binds them to the command.
It processes struct tags to generate appropriate cobra flags, handles environment variable binding, sets up flag groups, and configures the usage template.
func EnvPrefix ¶
func EnvPrefix() string
EnvPrefix returns the current global environment variable prefix without the trailing underscore.
func ExecuteC ¶ added in v0.17.0
ExecuteC prepares the command tree for execution and delegates to cmd.ExecuteC().
Preparation (idempotent, safe to call multiple times on the same tree):
- Sets SilenceErrors and SilenceUsage on the root command.
- Runs SetupUsage on every command in the tree.
- Recursively wraps PersistentPreRunE on every command to run the bind pipeline (auto-unmarshal for all Bind-registered options, root-to-leaf, FIFO per command).
- When WithConfig was used in Setup, auto-loads config (UseConfigSimple) once before the first auto-unmarshal.
- Skips the bind pipeline when execution is intercepted (--jsonschema, --mcp).
- Preserves any user-set PersistentPreRunE or PersistentPreRun.
- Warns (once per tree) if non-leaf commands have Bind-registered local flags but root.TraverseChildren is false.
- Suppresses the Bind warning hook by setting an annotation that is cleared after execution returns.
Returns the executed subcommand and any error.
func ExecuteOrExit ¶ added in v0.13.0
ExecuteOrExit is a convenience wrapper around ExecuteC for the common main() pattern. On error it writes structured JSON to stderr and exits with a semantic exit code. On success it exits 0.
func main() {
structcli.ExecuteOrExit(buildMyCLI())
}
func GetConfigViper ¶ added in v0.10.0
GetConfigViper returns the root-scoped config-source viper for c.
SetupConfig/UseConfig read configuration file data into this viper. Unmarshal then merges command-relevant settings from this viper into the effective command-scoped viper returned by GetViper.
Use this viper for imperative config-tree style injection (eg. top-level keys and command sections). Use GetViper for direct command-effective overrides.
func GetOrSetAppName ¶
GetOrSetAppName resolves the app name consistently.
When name is given, use it (and set as prefix if none exists). When cName is given, use it if no prefix exists, or if existing prefix matches cName. Otherwise, when an environment prefix already exists, return the app name that corresponds to it. Finally, it falls back to empty string.
func GetViper ¶
GetViper returns the effective command-scoped viper associated with c.
This is the runtime source used by Unmarshal and includes flags, env vars, defaults, plus command-relevant config merged from the root-scoped config viper.
Use this for imperative overrides that must affect option resolution for c.
func HandleError ¶ added in v0.13.0
HandleError classifies err, writes a JSON StructuredError to w, and returns a semantic exit code.
The cmd parameter must be the command where the error originated, not the root command. This is because HandleError looks up flag metadata (type, enum values, env var bindings) from cmd's flag annotations to produce accurate error details. If the root command is passed for a subcommand error, the metadata lookup yields empty results and the output is degraded (no expected type, no enum check, no env var attribution).
Use ExecuteOrExit to get this right automatically. It uses cobra's ExecuteC to obtain the correct command. If calling HandleError directly, use cobra.Command.ExecuteC:
cmd, err := rootCmd.ExecuteC()
if err != nil {
os.Exit(structcli.HandleError(cmd, err, os.Stderr))
}
HandleError has no side effects beyond reading the current process environment to improve source attribution and writing the structured error JSON to w.
If err is nil, HandleError returns exitcode.OK and writes nothing.
func IsDebugActive ¶
IsDebugActive checks if the debug option is set for the command c, either through a command-line flag or an environment variable.
func IsHelpTopicCommand ¶ added in v0.16.0
IsHelpTopicCommand returns true if the command was registered by SetupHelpTopics.
func RegisterEnum ¶ added in v0.16.0
RegisterEnum registers a string-based enum type for automatic flag handling. After registration, struct fields of type E work without any special tag or interface. This is a convenience wrapper over RegisterType for the common case of string-based enums with named values and aliases.
values maps each enum constant to its string representations. The first string in each slice is the canonical name shown in help text and shell completion; additional strings are accepted as aliases during parsing (case-insensitive). Canonical names appear sorted alphabetically in help text.
Must be called in init() before any Define() calls. Panics if the type is already registered (duplicate registration or conflict with a built-in), or if values is empty.
Example:
type Environment string
const (
EnvDev Environment = "dev"
EnvProd Environment = "prod"
)
func init() {
structcli.RegisterEnum[Environment](map[Environment][]string{
EnvDev: {"dev", "development"},
EnvProd: {"prod", "production"},
})
}
func RegisterIntEnum ¶ added in v0.16.0
RegisterIntEnum registers an integer-based enum type for automatic flag handling. Same semantics as RegisterEnum but for types with a signed integer underlying type (e.g., custom iota-based enums). Uses enumflag/v2 internally for flag parsing.
Values appear in help text sorted by their integer value.
Unsigned integer types (~uint, ~uint8, etc.) are not supported. For those, use RegisterType with manual Define/Decode hooks.
Must be called in init() before any Define() calls. Panics if the type is already registered, or if values is empty.
Example:
type Priority int
const (
PriorityLow Priority = 0
PriorityMedium Priority = 1
PriorityHigh Priority = 2
)
func init() {
structcli.RegisterIntEnum[Priority](map[Priority][]string{
PriorityLow: {"low"},
PriorityMedium: {"medium", "med"},
PriorityHigh: {"high", "hi"},
})
}
func RegisterType ¶ added in v0.18.0
RegisterType registers custom flag hooks for type T.
After registration, struct fields of type T work without any special tag or interface. The define hook is called once per field during Define/Bind; the decode hook is called during Unmarshal for env/config values.
Must be called in init() before any Define/Bind calls. Panics if T is already registered (duplicate or conflict with a built-in). Panics if Define is nil. Panics if Decode is nil.
func SetEnvPrefix ¶
func SetEnvPrefix(str string)
SetEnvPrefix sets the global environment variable prefix for the application.
The prefix is automatically appended with an underscore when generating environment variable names.
func Setup ¶ added in v0.17.0
func Setup(cmd *cobra.Command, opts ...SetupOption) error
Setup configures the root command with the selected features.
It calls the underlying Setup* functions in the correct internal order. Individual Setup* functions remain available for power users.
Most With* options are variadic: call them with no arguments for defaults (e.g., WithJSONSchema()) WithDebug is the exception: it requires an explicit debug.Options because AppName and Exit have no sensible defaults.
Ordering is handled internally:
- AppName + env annotation patching (if flags already exist from earlier Bind calls)
- Config (registers --config flag, defers auto-load to ExecuteC)
- Debug (registers --debug-options flag)
- JSON Schema (registers --jsonschema flag, wraps execution)
- Help Topics (adds help topic subcommands)
- Flag Errors (intercepts flag parsing errors)
- MCP (registers --mcp flag, wraps execution)
func SetupConfig ¶
SetupConfig creates the --config global flag and wires config discovery for the root command.
Works only for the root command.
Call this before attaching/defining options when you rely on app-prefixed environment variables (eg. FULL_*), because SetupConfig is what initializes the global env prefix used while defining env annotations.
Configuration file data is loaded into a root-scoped config viper (see GetConfigViper), then merged into the active command scoped viper during UseConfig/Unmarshal.
Set config.Options.ValidateKeys to enable strict config-key validation during Unmarshal for command-relevant config entries.
func SetupDebug ¶
SetupDebug creates the --debug-options global flag and sets up debug behavior.
Works only for the root command.
func SetupFlagErrors ¶ added in v0.13.0
SetupFlagErrors installs a flag error interceptor on the root command.
When active, cobra's flag parsing errors (invalid values, unknown flags) are wrapped in typed structclierrors.FlagError values. HandleError then uses errors.As to classify them, eliminating regex parsing at classification time.
Call this on the root command before Execute():
structcli.SetupFlagErrors(rootCmd)
This is optional. If not called, HandleError falls back to regex-based classification of cobra's string errors.
func SetupHelpTopics ¶ added in v0.16.0
func SetupHelpTopics(rootC *cobra.Command, opts helptopics.Options) error
SetupHelpTopics adds "env-vars" and "config-keys" reference commands to the root command. By default they appear as regular subcommands under "Available Commands:". Set ReferenceSection to move them into a dedicated "Reference:" section.
Text is generated lazily at invocation time, so commands added after this call are included.
func SetupJSONSchema ¶ added in v0.13.0
func SetupJSONSchema(rootC *cobra.Command, opts jsonschema.Options) error
SetupJSONSchema adds a --jsonschema persistent flag to the root command.
When the flag is set, the command prints its JSON Schema to stdout and returns without running the command's normal execution path. Works only for the root command.
func SetupMCP ¶ added in v0.14.0
func SetupMCP(rootC *cobra.Command, opts structclimcp.Options) error
SetupMCP adds a --mcp persistent flag to the root command.
When the flag is set, the command serves a minimal MCP server over stdio and returns without running the command's normal execution path. Works only for the root command.
func SetupUsage ¶
SetupUsage generates and sets a dynamic usage function for the command.
It also groups flags based on the `flaggroup` annotation.
func Unmarshal ¶
func Unmarshal(c *cobra.Command, opts Options, hooks ...mapstructure.DecodeHookFunc) error
Unmarshal populates opts with values from flags, environment variables, defaults, and configuration files.
It automatically handles decode hooks, validation, transformation, and context updates based on the options type.
Resolution happens from the effective command-scoped viper (GetViper(c)). Before decoding, Unmarshal merges command-relevant config from the root-scoped config-source viper (GetConfigViper(c)).
func UseConfig ¶
UseConfig attempts to read the configuration file based on the provided condition.
The readWhen function determines whether config reading should be attempted. Returns whether config was loaded, a status message, and any error encountered.
When SetupConfig was configured, this reads into the root-scoped config viper and merges command-relevant settings into the active command scoped viper.
If SetupConfig was not called, UseConfig falls back to reading on the global viper singleton. Prefer SetupConfig for deterministic command-scoped behavior.
func UseConfigSimple ¶
UseConfigSimple is a simpler version of UseConfig that uses c.IsAvailableCommand() as the readWhen function.
It does not check for the config file when the command is not available (eg., help).
The config file (if found) is loaded through the root-scoped config viper and merged into c's effective scoped viper.
func UseDebug ¶
UseDebug manually triggers debug output for the given options.
When --debug-options=json, output goes to w as a JSON object. When --debug-options or --debug-options=text, output goes to w as a human-readable table.
Debug output is automatically triggered when the debug flag is enabled.
Types ¶
type Base64 ¶ added in v0.12.0
type Base64 []byte
Base64 represents binary data provided as base64-encoded textual input.
type CommandSchema ¶ added in v0.13.0
type CommandSchema struct {
Name string `json:"name"`
CommandPath string `json:"command_path"`
Description string `json:"description,omitempty"`
Flags map[string]*FlagSchema `json:"flags"`
Groups map[string][]string `json:"groups,omitempty"`
Subcommands []string `json:"subcommands,omitempty"`
EnvPrefix string `json:"env_prefix,omitempty"`
ConfigFlag string `json:"config_flag,omitempty"`
Example string `json:"example,omitempty"` // Usage examples from cobra.Command.Example
Aliases []string `json:"aliases,omitempty"` // Command aliases from cobra.Command.Aliases
ValidArgs []string `json:"valid_args,omitempty"` // Valid positional arguments from cobra.Command.ValidArgs
}
CommandSchema describes a command's inputs in machine-readable form.
func JSONSchema ¶ added in v0.13.0
func JSONSchema(c *cobra.Command, opts ...jsonschema.Opt) ([]*CommandSchema, error)
JSONSchema returns machine-readable schemas for a command's inputs.
By default it returns a single-element slice with the schema for the given command. Pass jsonschema.WithFullTree() to walk the entire command tree and return schemas for all subcommands.
It extracts all flag metadata from cobra annotations set during Define(), including types, defaults, descriptions, environment variables, groups, presets, and enum values.
func (*CommandSchema) ToJSONSchema ¶ added in v0.13.0
func (cs *CommandSchema) ToJSONSchema() ([]byte, error)
ToJSONSchema converts a CommandSchema to a JSON Schema draft 2020-12 document.
Standard JSON Schema fields (type, properties, required, enum, default, description) are used for core flag metadata. structcli-specific metadata is preserved in x-structcli-* extension fields.
type CompleteHookFunc ¶ added in v0.18.0
type CompleteHookFunc = internalhooks.CompleteHookFunc
CompleteHookFunc defines how to provide shell completion candidates for a flag.
type ContextInjector ¶ added in v0.17.0
ContextInjector is a struct that propagates values into the command context after unmarshalling.
Context is called automatically during Unmarshal() to derive a new context. Does not require Options (Attach). Works with plain struct pointers via Bind.
Reading values back from context (FromContext) is a user-side pattern, not part of this interface.
type ContextOptions ¶
type ContextOptions interface {
Options
Context(context.Context) context.Context
FromContext(context.Context) error
}
ContextOptions extends Options with context manipulation capabilities.
For the Bind API, consider using ContextInjector instead. It only requires the Context method (propagation) and works with plain struct pointers. FromContext is a user-side pattern; structcli never calls it internally. ContextOptions remains the right choice when using Define/Unmarshal directly or when the type already implements Options.
type DecodeHookFunc ¶ added in v0.18.0
type DecodeHookFunc = internalhooks.DecodeHookFunc
DecodeHookFunc defines how to decode a raw value into a custom type during Unmarshal.
type DefineHookFunc ¶ added in v0.18.0
type DefineHookFunc = internalhooks.DefineHookFunc
DefineHookFunc defines how to create a pflag.Value for a custom type during Define/Bind.
type DefineOption ¶
type DefineOption func(*defineContext)
DefineOption configures the behavior of the Define function.
func WithExclusions ¶
func WithExclusions(exclusions ...string) DefineOption
WithExclusions sets flags to exclude from definition based on flag names or paths.
Exclusions are case-insensitive and apply only to the specific command.
func WithModTagName ¶ added in v0.13.0
func WithModTagName(name string) DefineOption
WithModTagName sets the struct tag name used to read transformation rules.
Defaults to DefaultModTagName ("mod", the go-playground/mold default). Use this when your mold instance is configured with a custom tag name.
func WithValidateTagName ¶ added in v0.13.0
func WithValidateTagName(name string) DefineOption
WithValidateTagName sets the struct tag name used to read validation rules.
Defaults to DefaultValidateTagName ("validate", the go-playground/validator default). Use this when your validator is configured with a custom tag name (eg. validator.New().SetTagName("binding")).
type EnumValuer ¶ added in v0.13.0
type EnumValuer interface {
EnumValues() []string
}
EnumValuer is an optional interface that pflag.Value implementations can satisfy to declare their allowed values at the type level.
When a pflag.Value returned by a DefineHookFunc (built-in or custom) implements EnumValuer, structcli stores the allowed values as a flag annotation during Define(). This is the authoritative source of enum values; no description string parsing is needed.
Example:
type myEnumFlag struct {
pflag.Value // embed the underlying pflag.Value
allowed []string
}
func (f *myEnumFlag) EnumValues() []string { return f.allowed }
type FieldCompleter ¶ added in v0.18.0
type FieldCompleter interface {
CompletionHooks() map[string]CompleteHookFunc
}
FieldCompleter provides per-field shell completion hooks.
Map keys are struct field names. Works for any field that becomes a flag, not only fields with FieldHookProvider hooks.
If a completion function is already registered on a flag before Define, structcli preserves it (the FieldCompleter hook is not applied).
type FieldHook ¶ added in v0.18.0
type FieldHook struct {
// Define creates the pflag.Value for this field.
Define DefineHookFunc
// Decode converts raw input to the field's type during Unmarshal.
Decode DecodeHookFunc
}
FieldHook bundles the Define and Decode hooks for a single struct field.
If Define is nil, the field falls through to the type registry or built-in handling. If Decode is nil, the default decode path is used. Setting Decode without Define is an error (caught at Define/Bind time).
type FieldHookProvider ¶ added in v0.18.0
FieldHookProvider provides per-field Define/Decode hooks.
Implement this interface when the same type needs different flag behavior in different fields, or when a standard type needs custom handling for a specific field.
Map keys are struct field names (e.g., "ListenAddr", not the flag name "listen"). Unknown keys that do not match any struct field cause an error at Define/Bind time.
Precedence: FieldHookProvider > RegisterType > built-in registry.
type FlagSchema ¶ added in v0.13.0
type FlagSchema struct {
Name string `json:"name"`
Shorthand string `json:"shorthand,omitempty"`
Type string `json:"type"`
Default string `json:"default,omitempty"`
Description string `json:"description,omitempty"`
Required bool `json:"required,omitempty"`
EnvOnly bool `json:"env_only,omitempty"`
EnvVars []string `json:"env_vars,omitempty"`
Group string `json:"group,omitempty"`
FieldPath string `json:"field_path,omitempty"`
Enum []string `json:"enum,omitempty"`
Presets []PresetInfo `json:"presets,omitempty"`
}
FlagSchema describes a single flag in machine-readable form.
type Hex ¶ added in v0.12.0
type Hex []byte
Hex represents binary data provided as hex-encoded textual input.
type Options ¶
Options represents a struct that can define command-line flags, env vars, config file keys.
Types implementing this interface can be used with Define() to automatically generate flags from struct fields.
type PresetInfo ¶ added in v0.13.0
PresetInfo describes a preset alias for a flag.
type SetupOption ¶ added in v0.17.0
type SetupOption func(*setupConfig)
SetupOption configures a feature in Setup.
func WithAppName ¶ added in v0.17.0
func WithAppName(name string) SetupOption
WithAppName sets the application name used for environment variable prefixes and config file discovery. When flags already exist on the command tree (from earlier Bind calls), their env annotations are retroactively patched to include the new prefix.
If a sub-option (e.g., debug.Options.AppName or config.Options.AppName) specifies a different name, Setup returns an error.
func WithConfig ¶ added in v0.17.0
func WithConfig(opts ...config.Options) SetupOption
WithConfig enables config file discovery and the --config flag on the root command. The actual config loading (UseConfigSimple) is deferred to ExecuteC's bind pipeline, before the first auto-unmarshal.
func WithDebug ¶ added in v0.17.0
func WithDebug(opts debug.Options) SetupOption
WithDebug enables the debug flag (--debug-options) on the root command.
Unlike other With* options, WithDebug requires an explicit debug.Options argument because AppName and Exit have no sensible zero-value defaults.
func WithFlagErrors ¶ added in v0.17.0
func WithFlagErrors() SetupOption
WithFlagErrors enables structured flag error interception on the root command.
func WithHelpTopics ¶ added in v0.17.0
func WithHelpTopics(opts ...helptopics.Options) SetupOption
WithHelpTopics enables help topic commands on the root command. Pass helptopics.Options{} for defaults.
func WithJSONSchema ¶ added in v0.17.0
func WithJSONSchema(opts ...jsonschema.Options) SetupOption
WithJSONSchema enables the --jsonschema flag on the root command. Pass jsonschema.Options{} for defaults.
func WithMCP ¶ added in v0.17.0
func WithMCP(opts ...structclimcp.Options) SetupOption
WithMCP enables the --mcp flag on the root command. Pass mcp.Options{} for defaults.
type StructuredError ¶ added in v0.13.0
type StructuredError struct {
Error string `json:"error"`
ExitCode int `json:"exit_code"`
Message string `json:"message"`
// Input error fields
Flag string `json:"flag,omitempty"`
Got string `json:"got,omitempty"`
Expected string `json:"expected,omitempty"`
Command string `json:"command,omitempty"`
Hint string `json:"hint,omitempty"`
Available []string `json:"available,omitempty"`
// Validation fields
Violations []Violation `json:"violations,omitempty"`
// Config fields
ConfigFile string `json:"config_file,omitempty"`
Key string `json:"key,omitempty"`
// Environment variable fields
EnvVar string `json:"env_var,omitempty"`
}
StructuredError is the JSON object written to stderr by HandleError.
Every field is optional except Error, ExitCode, and Message. Agents parse this to decide whether to self-correct, fix the environment, or report to a human.
type Transformable ¶ added in v0.17.0
Transformable is a struct that supports transformation after unmarshalling.
Transform is called automatically during Unmarshal(), before Validate. Does not require Options (Attach). Works with plain struct pointers via Bind.
type TransformableOptions ¶
TransformableOptions extends Options with transformation capabilities.
For the Bind API, consider using Transformable instead. It does not require implementing Attach and works with plain struct pointers. TransformableOptions remains the right choice when using Define/Unmarshal directly or when the type already implements Options.
type TypeHooks ¶ added in v0.18.0
type TypeHooks[T any] struct { Define DefineHookFunc Decode DecodeHookFunc }
TypeHooks defines custom flag behavior for a type.
Define creates the pflag.Value for this type. Called during Define/Bind for each struct field of type T. Receives the specific field's value and metadata.
Decode converts raw input (string from env/config) to T during Unmarshal.
type Validatable ¶ added in v0.17.0
Validatable is a struct that supports validation after unmarshalling.
Validate is called automatically during Unmarshal(), after Transform. Does not require Options (Attach). Works with plain struct pointers via Bind.
type ValidatableOptions ¶
ValidatableOptions extends Options with validation capabilities.
For the Bind API, consider using Validatable instead. It does not require implementing Attach and works with plain struct pointers. ValidatableOptions remains the right choice when using Define/Unmarshal directly or when the type already implements Options.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
examples
|
|
|
full
module
|
|
|
Package exitcode defines semantic exit codes for structcli-powered CLIs.
|
Package exitcode defines semantic exit codes for structcli-powered CLIs. |
|
Package flagkit provides reusable, embeddable flag structs that standardize common CLI flag declarations for use with structcli.
|
Package flagkit provides reusable, embeddable flag structs that standardize common CLI flag declarations for use with structcli. |
|
Package generate produces static discovery files from structcli command trees.
|
Package generate produces static discovery files from structcli command trees. |
|
internal
|
|
|
proptest/gen
Package gen provides shared rapid generators for property-based tests.
|
Package gen provides shared rapid generators for property-based tests. |
|
Package structerr configures structured error output for structcli-powered CLIs.
|
Package structerr configures structured error output for structcli-powered CLIs. |