Documentation
¶
Index ¶
- func Define(c *cobra.Command, o Options, defineOpts ...DefineOption) error
- func EnvPrefix() string
- 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 Reset()
- func SetEnvPrefix(str string)
- func SetupConfig(rootC *cobra.Command, cfgOpts config.Options) error
- func SetupDebug(rootC *cobra.Command, debugOpts debug.Options) error
- func SetupFlagErrors(rootC *cobra.Command)
- func SetupJSONSchema(rootC *cobra.Command, opts jsonschema.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 ContextOptions
- type DefineOption
- type EnumValuer
- type FlagSchema
- type Hex
- type Options
- type PresetInfo
- type StructuredError
- type TransformableOptions
- type ValidatableOptions
- type Violation
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
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 ExecuteOrExit ¶ added in v0.13.0
ExecuteOrExit runs cmd.Execute(). On error it writes structured JSON to stderr and exits with a semantic exit code. On success it exits 0.
It automatically sets SilenceErrors and SilenceUsage on the root command so cobra doesn't print its own error messages or usage text — structcli handles all error output as structured JSON.
This is a convenience wrapper for the common main() pattern:
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 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 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 — no 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 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 exits. 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.
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"`
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 ContextOptions ¶
type ContextOptions interface {
Options
Context(context.Context) context.Context
FromContext(context.Context) error
}
ContextOptions extends Options with context manipulation capabilities.
The Context method is called automatically during Unmarshal() to modify the command context.
type DefineOption ¶
type DefineOption func(*defineContext)
DefineOption configures the behavior of the Define function.
func WithExclusions ¶
func WithExclusions(exclusions ...string) DefineOption
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 "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
WithExclusions sets flags to exclude from definition based on flag names or paths.
Exclusions are case-insensitive and apply only to the specific command. WithValidateTagName sets the struct tag name used to read validation rules.
Defaults to "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 needed.
Example:
type myEnumFlag struct {
pflag.Value // embed the underlying pflag.Value
allowed []string
}
func (f *myEnumFlag) EnumValues() []string { return f.allowed }
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"`
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 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 TransformableOptions ¶
TransformableOptions extends Options with transformation capabilities.
The Transform method is called automatically during Unmarshal() before validation.
type ValidatableOptions ¶
ValidatableOptions extends Options with validation capabilities.
The Validate method is called automatically during Unmarshal().
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 generate produces static discovery files from structcli command trees.
|
Package generate produces static discovery files from structcli command trees. |
|
internal
|
|
|
Package structerr configures structured error output for structcli-powered CLIs.
|
Package structerr configures structured error output for structcli-powered CLIs. |