Documentation
¶
Overview ¶
cli/command.go
cli/command_builder.go
cli/command_context.go
cli/command_executor.go
cli/command_result.go
cli/command_router.go
cli/config.go
cli/config_processor.go
cli/definition.go
cli/errors.go
cli/execution_context.go
cli/files.go
cli/flag_parser.go
cli/get.go
cli/help_data.go
cli/help_layer_coordinator.go
cli/help_models.go
cli/help_service.go
cli/help_templates.go
cli/middleware.go
cli/middleware_chain.go
cli/secret.go
cli/services.go
cli/type_converter.go
cli/types.go
cli/validation.go
Index ¶
- Constants
- Variables
- func Exit(code int, err error) error
- func ExitCode(err error) int
- func Get[T any](ctx *CommandContext, key string) (T, error)
- func IsReported(err error) bool
- func MustGet[T any](ctx *CommandContext, key string) T
- type Command
- type CommandBuilder
- func (b *CommandBuilder) Aliases(aliases ...string) *CommandBuilder
- func (b *CommandBuilder) Config(fn func(*CommandConfig)) *CommandBuilder
- func (b *CommandBuilder) CustomHelp(help string) *CommandBuilder
- func (b *CommandBuilder) Func(fn CommandFunc) *CommandBuilder
- func (b *CommandBuilder) LongHelp(help string) *CommandBuilder
- func (b *CommandBuilder) Middleware(middleware CommandMiddleware) *CommandBuilder
- func (b *CommandBuilder) ShortHelp(help string) *CommandBuilder
- func (b *CommandBuilder) SubCommand(name string) *CommandBuilder
- type CommandConfig
- type CommandContext
- func (ctx *CommandContext) GetData(key string) (any, bool)
- func (ctx *CommandContext) Getenv(name string) string
- func (ctx *CommandContext) IsHelpRequested() bool
- func (ctx *CommandContext) Positional() []string
- func (ctx *CommandContext) Set(key string, value any)
- func (ctx *CommandContext) Stderr() io.Writer
- func (ctx *CommandContext) Stdin() io.Reader
- func (ctx *CommandContext) Stdout() io.Writer
- type CommandExecutor
- type CommandFunc
- type CommandMiddleware
- func AuthMiddleware(authFunc func(*CommandContext) error) CommandMiddleware
- func ConditionalMiddleware(condition func(*CommandContext) bool, middleware CommandMiddleware) CommandMiddleware
- func LoggingMiddleware(logger func(*CommandContext, time.Duration)) CommandMiddleware
- func MetricsMiddleware(metricsCollector func(*CommandContext, time.Duration, error)) CommandMiddleware
- func RecoveryMiddleware() CommandMiddleware
- func TimingMiddleware() CommandMiddleware
- type CommandResult
- type CommandRouter
- type CommandServices
- type Config
- func (c *Config) Command(name string) *CommandBuilder
- func (c *Config) CustomHelp(help string) *Config
- func (c *Config) Define(key string) *DefinitionBuilder
- func (c *Config) Destroy()
- func (c *Config) Dump() map[string]string
- func (c *Config) Execute(args []string) error
- func (c *Config) GenerateHelp() string
- func (c *Config) GetDefaultPriority() SourcePriority
- func (c *Config) GetSecret(key string) *Secret
- func (c *Config) Has(key string) bool
- func (c *Config) HasSecret(key string) bool
- func (c *Config) IsSecret(key string) bool
- func (c *Config) Keys() []string
- func (c *Config) LoadFile(filename string) error
- func (c *Config) LoadFileFromEnv(envVar string) error
- func (c *Config) LoadFiles(filenames ...string) error
- func (c *Config) LongHelp(help string) *Config
- func (c *Config) SetDefaultPriority(priority SourcePriority) *Config
- func (c *Config) SetEnv(getenv func(string) string) *Config
- func (c *Config) SetIO(stdin io.Reader, stdout, stderr io.Writer) *Config
- func (c *Config) SetName(name string) *Config
- func (c *Config) ShortHelp(help string) *Config
- func (c *Config) ShowCommandHelp(commandName string) error
- func (c *Config) ShowGlobalHelp() error
- func (c *Config) UseMiddleware(middleware CommandMiddleware)
- func (c *Config) UseMiddlewareForCommands(commandNames []string, middleware CommandMiddleware)
- func (c *Config) UseMiddlewareForSubcommands(commandName string, subcommandNames []string, middleware CommandMiddleware)
- type ConfigError
- type ConfigProcessor
- type ConsoleHelpOutput
- type Definition
- type DefinitionBuilder
- func (b *DefinitionBuilder) Bool() *DefinitionBuilder
- func (b *DefinitionBuilder) Custom(name string, check func(value any) error) *DefinitionBuilder
- func (b *DefinitionBuilder) Default(value any) *DefinitionBuilder
- func (b *DefinitionBuilder) Delimiter(d string) *DefinitionBuilder
- func (b *DefinitionBuilder) Description(desc string) *DefinitionBuilder
- func (b *DefinitionBuilder) Duration() *DefinitionBuilder
- func (b *DefinitionBuilder) Env(envVar string) *DefinitionBuilder
- func (b *DefinitionBuilder) File(fileKey string) *DefinitionBuilder
- func (b *DefinitionBuilder) Flag(flag string) *DefinitionBuilder
- func (b *DefinitionBuilder) Float64() *DefinitionBuilder
- func (b *DefinitionBuilder) Int64() *DefinitionBuilder
- func (b *DefinitionBuilder) Int64Slice() *DefinitionBuilder
- func (b *DefinitionBuilder) Max(max float64) *DefinitionBuilder
- func (b *DefinitionBuilder) MaxDuration(max time.Duration) *DefinitionBuilder
- func (b *DefinitionBuilder) MaxItems(max int) *DefinitionBuilder
- func (b *DefinitionBuilder) MaxLength(max int) *DefinitionBuilder
- func (b *DefinitionBuilder) Min(min float64) *DefinitionBuilder
- func (b *DefinitionBuilder) MinDuration(min time.Duration) *DefinitionBuilder
- func (b *DefinitionBuilder) MinItems(min int) *DefinitionBuilder
- func (b *DefinitionBuilder) MinLength(min int) *DefinitionBuilder
- func (b *DefinitionBuilder) OneOf(allowed ...string) *DefinitionBuilder
- func (b *DefinitionBuilder) Priority(priority SourcePriority) *DefinitionBuilder
- func (b *DefinitionBuilder) Range(min, max float64) *DefinitionBuilder
- func (b *DefinitionBuilder) Regexp(pattern string) *DefinitionBuilder
- func (b *DefinitionBuilder) Required() *DefinitionBuilder
- func (b *DefinitionBuilder) Secret() *DefinitionBuilder
- func (b *DefinitionBuilder) String() *DefinitionBuilder
- func (b *DefinitionBuilder) StringSlice() *DefinitionBuilder
- type ExecutionContext
- func (ctx *ExecutionContext) Clear()
- func (ctx *ExecutionContext) CollectConfigError(c *Config, configErr ConfigError)
- func (ctx *ExecutionContext) CollectError(c *Config, key, expectedType, actualType, message string, isSecret bool)
- func (ctx *ExecutionContext) GetCommand() string
- func (ctx *ExecutionContext) GetErrors() []GetError
- func (ctx *ExecutionContext) HasErrors() bool
- func (ctx *ExecutionContext) SetCommand(command string)
- type ExitError
- type FileConfig
- type FlagParser
- type GetError
- type MiddlewareChain
- type ParsedFlags
- type Secret
- type SecretStore
- type SourcePriority
- type SourceType
- type StringHelpOutput
- type TypeConverter
- func (tc *TypeConverter) ConvertDefaultValue(value any, targetType ValueType) (any, error)
- func (tc *TypeConverter) ConvertToDisplayString(value any, delimiter string) string
- func (tc *TypeConverter) ConvertToString(value any, delimiter string) (string, error)
- func (tc *TypeConverter) IsSupportedType(value any) bool
- type Validation
- type ValidationCache
- type ValueType
Constants ¶
const ( ExitOK = 0 // success, or help shown ExitFailure = 1 // a command failed at run time ExitUsage = 2 // unknown command or flag, missing or invalid flag value )
Process exit codes used by the library. Command functions may return any other code with Exit.
Variables ¶
var ( // PriorityFlagEnvFileDefault sets Flag > Env > File > Default priority (current default) PriorityFlagEnvFileDefault = SourcePriority{SourceFlag, SourceEnv, SourceFile, SourceDefault} // PriorityFlagEnvDefault sets Flag > Env > Default priority PriorityFlagEnvDefault = SourcePriority{SourceFlag, SourceEnv, SourceDefault} // PriorityEnvFlagDefault sets Env > Flag > Default priority PriorityEnvFlagDefault = SourcePriority{SourceEnv, SourceFlag, SourceDefault} // PriorityFileEnvFlagDefault sets File > Env > Flag > Default priority PriorityFileEnvFlagDefault = SourcePriority{SourceFile, SourceEnv, SourceFlag, SourceDefault} // PriorityDefaultOnly uses only Default values PriorityDefaultOnly = SourcePriority{SourceDefault} )
Common priority presets
Functions ¶
func Exit ¶
Exit returns an error that makes ExitCode report code. Commands return it to end with a chosen exit code: return cli.Exit(3, err). err may be nil for a silent exit.
func ExitCode ¶
ExitCode is the exit code for the error Execute returned: 0 for nil, the code of an ExitError anywhere in the chain, 1 for any other error.
func Get ¶
func Get[T any](ctx *CommandContext, key string) (T, error)
Get retrieves a configuration value with proper error handling. An optional value that no source provides is returned as the empty value of its type, without an error: the zero value, or an empty slice, never a nil one. Use Config.Has to tell it apart from a given value. This function performs early secret detection to prevent type assertion exposure
func IsReported ¶
IsReported reports whether the library already printed err's details.
func MustGet ¶
func MustGet[T any](ctx *CommandContext, key string) T
MustGet retrieves a configuration value and panics on error Use when you expect the configuration to be valid and want to fail fast
Types ¶
type Command ¶
type Command struct {
Name string
Func CommandFunc
ShortHelp string
LongHelp string
CustomHelp string // replaces the generated help page
Aliases []string
Definitions map[string]*Definition
SubCommands map[string]*Command
Middleware []CommandMiddleware
}
Command represents a CLI command with its configuration
func (*Command) Execute ¶
func (cmd *Command) Execute(ctx *CommandContext) *CommandResult
Execute executes the command with the given context and returns CommandResult for unified error handling
func (*Command) FindSubCommand ¶
FindSubCommand finds a subcommand by name or alias
type CommandBuilder ¶
type CommandBuilder struct {
// contains filtered or unexported fields
}
CommandBuilder provides a fluent API for building commands
func (*CommandBuilder) Aliases ¶
func (b *CommandBuilder) Aliases(aliases ...string) *CommandBuilder
Aliases sets the command aliases
func (*CommandBuilder) Config ¶
func (b *CommandBuilder) Config(fn func(*CommandConfig)) *CommandBuilder
Config defines command-specific configuration
func (*CommandBuilder) CustomHelp ¶ added in v0.3.5
func (b *CommandBuilder) CustomHelp(help string) *CommandBuilder
CustomHelp replaces the command's generated help page with this text
func (*CommandBuilder) Func ¶
func (b *CommandBuilder) Func(fn CommandFunc) *CommandBuilder
Func sets the command function
func (*CommandBuilder) LongHelp ¶
func (b *CommandBuilder) LongHelp(help string) *CommandBuilder
LongHelp sets the long help text
func (*CommandBuilder) Middleware ¶
func (b *CommandBuilder) Middleware(middleware CommandMiddleware) *CommandBuilder
Middleware adds middleware to this command
func (*CommandBuilder) ShortHelp ¶
func (b *CommandBuilder) ShortHelp(help string) *CommandBuilder
ShortHelp sets the short help text
func (*CommandBuilder) SubCommand ¶
func (b *CommandBuilder) SubCommand(name string) *CommandBuilder
SubCommand adds a subcommand
type CommandConfig ¶
type CommandConfig struct {
*Config
// contains filtered or unexported fields
}
CommandConfig wraps Config for command-specific configuration
func (*CommandConfig) Define ¶
func (cc *CommandConfig) Define(key string) *DefinitionBuilder
Define starts a new command-specific configuration definition
type CommandContext ¶
type CommandContext struct {
Args []string
GlobalConfig *Config // Immutable global config
CommandConfig *Config // Immutable command-specific config (nil if no command defs)
Command string
SubCommand string
// contains filtered or unexported fields
}
CommandContext provides context for command execution
func NewCommandContext ¶
func NewCommandContext(args []string, config *Config, command, subCommand string) *CommandContext
NewCommandContext creates a new command context
func (*CommandContext) GetData ¶
func (ctx *CommandContext) GetData(key string) (any, bool)
GetData retrieves data from the context
func (*CommandContext) Getenv ¶
func (ctx *CommandContext) Getenv(name string) string
Getenv looks a variable up through the environment the Config was given (SetEnv), os.Getenv by default.
func (*CommandContext) IsHelpRequested ¶
func (ctx *CommandContext) IsHelpRequested() bool
IsHelpRequested checks if help is being requested in the current context This is context-specific (no args parameter) and used by config processing to skip validation when help is shown
func (*CommandContext) Positional ¶
func (ctx *CommandContext) Positional() []string
Set stores data in the context for middleware sharing Positional returns the arguments left over once the command's flags are parsed (everything from the first non-flag argument on). Commands that take only flags use it to reject stray arguments.
func (*CommandContext) Set ¶
func (ctx *CommandContext) Set(key string, value any)
func (*CommandContext) Stderr ¶
func (ctx *CommandContext) Stderr() io.Writer
func (*CommandContext) Stdin ¶
func (ctx *CommandContext) Stdin() io.Reader
Stdin, Stdout and Stderr are the streams the Config was given (SetIO), the process's own by default. Commands should use them, not os.Std*.
func (*CommandContext) Stdout ¶
func (ctx *CommandContext) Stdout() io.Writer
type CommandExecutor ¶
type CommandExecutor interface {
// Execute orchestrates the complete command execution using all services
Execute(cmd *Command, ctx *CommandContext, services *CommandServices) *CommandResult
}
CommandExecutor orchestrates command execution flow
type CommandFunc ¶
type CommandFunc func(*CommandContext) error
CommandFunc represents the function that executes a command
type CommandMiddleware ¶
type CommandMiddleware func(next CommandFunc) CommandFunc
CommandMiddleware represents middleware that can wrap command execution
func AuthMiddleware ¶
func AuthMiddleware(authFunc func(*CommandContext) error) CommandMiddleware
AuthMiddleware creates middleware that validates authentication before command execution The auth function should return nil if authentication succeeds, or an error if it fails
func ConditionalMiddleware ¶
func ConditionalMiddleware(condition func(*CommandContext) bool, middleware CommandMiddleware) CommandMiddleware
ConditionalMiddleware creates middleware that only applies when the condition is true This allows for sophisticated conditional middleware application
func LoggingMiddleware ¶
func LoggingMiddleware(logger func(*CommandContext, time.Duration)) CommandMiddleware
LoggingMiddleware creates middleware that logs command execution with timing The logger function receives the command context and execution duration
func MetricsMiddleware ¶
func MetricsMiddleware(metricsCollector func(*CommandContext, time.Duration, error)) CommandMiddleware
MetricsMiddleware creates middleware for collecting command metrics This is useful for monitoring and analytics
func RecoveryMiddleware ¶
func RecoveryMiddleware() CommandMiddleware
RecoveryMiddleware creates middleware that recovers from panics This prevents the entire application from crashing due to panics in commands
func TimingMiddleware ¶
func TimingMiddleware() CommandMiddleware
TimingMiddleware creates middleware that measures and stores execution timing The timing is stored in ctx for other middleware to use
type CommandResult ¶
CommandResult represents the result of command execution with unified error handling
type CommandRouter ¶
type CommandRouter interface {
// HandleSubcommands checks for and handles subcommand routing
HandleSubcommands(cmd *Command, ctx *CommandContext) (*Command, *CommandContext, error)
// RouteWithHelpHandling integrates help detection with command routing
RouteWithHelpHandling(args []string, config *Config) (*Command, *CommandContext, error)
}
CommandRouter routes commands and handles subcommands
type CommandServices ¶
type CommandServices struct {
Executor CommandExecutor
ConfigProcessor ConfigProcessor
MiddlewareChain MiddlewareChain
CommandRouter CommandRouter
FlagParser FlagParser
}
CommandServices holds all command execution services
type Config ¶
type Config struct {
// contains filtered or unexported fields
}
Config holds configuration definitions and values
func (*Config) Command ¶
func (c *Config) Command(name string) *CommandBuilder
Command starts a new command definition
func (*Config) CustomHelp ¶ added in v0.3.5
CustomHelp replaces the generated general help page with this text
func (*Config) Define ¶
func (c *Config) Define(key string) *DefinitionBuilder
Define starts a new configuration definition
func (*Config) GenerateHelp ¶
GenerateHelp creates a help message using the new template-based help system
func (*Config) GetDefaultPriority ¶
func (c *Config) GetDefaultPriority() SourcePriority
GetDefaultPriority returns the current default priority order
func (*Config) Has ¶
Has checks if a key exists and has a non-nil value Note: This function will return false for secret keys to prevent exposure
func (*Config) LoadFileFromEnv ¶
LoadFileFromEnv loads configuration file from environment variable containing the file path
func (*Config) LoadFiles ¶
LoadFiles loads configuration from multiple files (later files override earlier ones)
func (*Config) LongHelp ¶ added in v0.3.5
LongHelp describes the program in the general help, instead of ShortHelp
func (*Config) SetDefaultPriority ¶
func (c *Config) SetDefaultPriority(priority SourcePriority) *Config
SetDefaultPriority sets the default priority order for all definitions that don't have an explicit priority set
func (*Config) SetEnv ¶
SetEnv replaces the environment lookup (default os.Getenv), so programs and tests can supply their own environment.
func (*Config) SetIO ¶
SetIO replaces stdin, stdout and stderr (defaults os.Stdin, os.Stdout, os.Stderr). Help goes to stdout; configuration errors go to stderr. A nil argument keeps the default for that stream.
func (*Config) SetName ¶
SetName sets the program name shown in usage lines (default: the executable's base name).
func (*Config) ShortHelp ¶ added in v0.3.5
ShortHelp describes the program in the general help. It applies to the Config that New returns, not to a command's CommandConfig.
func (*Config) ShowCommandHelp ¶
ShowCommandHelp displays help for a specific command using the new template-based help system
func (*Config) ShowGlobalHelp ¶
ShowGlobalHelp displays help for all commands using the new template-based help system
func (*Config) UseMiddleware ¶
func (c *Config) UseMiddleware(middleware CommandMiddleware)
UseMiddleware adds global middleware that applies to all commands
func (*Config) UseMiddlewareForCommands ¶
func (c *Config) UseMiddlewareForCommands(commandNames []string, middleware CommandMiddleware)
UseMiddlewareForCommands adds middleware only for specific commands
func (*Config) UseMiddlewareForSubcommands ¶
func (c *Config) UseMiddlewareForSubcommands(commandName string, subcommandNames []string, middleware CommandMiddleware)
UseMiddlewareForSubcommands adds middleware only for specific subcommands of a command
type ConfigError ¶
type ConfigError struct {
Key string
Source string // "env", "flag", "default", or "none"
Value string // Masked if secret
Display string
ErrorDescription string
}
ConfigError represents a single configuration error
func (*ConfigError) Error ¶
func (e *ConfigError) Error() string
type ConfigProcessor ¶
type ConfigProcessor interface {
// ProcessCommandConfig handles command-specific configuration processing
ProcessCommandConfig(cmd *Command, ctx *CommandContext) *CommandResult
// ValidateRequiredFlags checks if all required flags have values and logs warnings for missing ones
ValidateRequiredFlags(cmd *Command, ctx *CommandContext) *CommandResult
}
ConfigProcessor processes command-specific configuration
type ConsoleHelpOutput ¶
ConsoleHelpOutput implements HelpOutput for console output
func (*ConsoleHelpOutput) Get ¶
func (cho *ConsoleHelpOutput) Get() string
Get returns the accumulated output (not applicable for console)
func (*ConsoleHelpOutput) Print ¶
func (cho *ConsoleHelpOutput) Print(text string) error
Print prints text to console
func (*ConsoleHelpOutput) Reset ¶
func (cho *ConsoleHelpOutput) Reset()
Reset resets the output (not applicable for console)
type Definition ¶
type Definition struct {
// contains filtered or unexported fields
}
Definition represents a configuration definition with fluent builder
type DefinitionBuilder ¶
type DefinitionBuilder struct {
// contains filtered or unexported fields
}
DefinitionBuilder provides a fluent API for building definitions
func (*DefinitionBuilder) Bool ¶
func (b *DefinitionBuilder) Bool() *DefinitionBuilder
func (*DefinitionBuilder) Custom ¶
func (b *DefinitionBuilder) Custom(name string, check func(value any) error) *DefinitionBuilder
Custom adds a custom validation function
func (*DefinitionBuilder) Default ¶
func (b *DefinitionBuilder) Default(value any) *DefinitionBuilder
func (*DefinitionBuilder) Delimiter ¶
func (b *DefinitionBuilder) Delimiter(d string) *DefinitionBuilder
func (*DefinitionBuilder) Description ¶
func (b *DefinitionBuilder) Description(desc string) *DefinitionBuilder
func (*DefinitionBuilder) Duration ¶
func (b *DefinitionBuilder) Duration() *DefinitionBuilder
func (*DefinitionBuilder) Env ¶
func (b *DefinitionBuilder) Env(envVar string) *DefinitionBuilder
func (*DefinitionBuilder) File ¶
func (b *DefinitionBuilder) File(fileKey string) *DefinitionBuilder
func (*DefinitionBuilder) Flag ¶
func (b *DefinitionBuilder) Flag(flag string) *DefinitionBuilder
Flag adds a command-line flag name. Call it more than once to give the same value several names, such as Flag("f").Flag("file"). If more than one of them is passed, the last one wins. Empty and repeated names are ignored.
func (*DefinitionBuilder) Float64 ¶
func (b *DefinitionBuilder) Float64() *DefinitionBuilder
func (*DefinitionBuilder) Int64 ¶
func (b *DefinitionBuilder) Int64() *DefinitionBuilder
func (*DefinitionBuilder) Int64Slice ¶
func (b *DefinitionBuilder) Int64Slice() *DefinitionBuilder
func (*DefinitionBuilder) Max ¶
func (b *DefinitionBuilder) Max(max float64) *DefinitionBuilder
func (*DefinitionBuilder) MaxDuration ¶
func (b *DefinitionBuilder) MaxDuration(max time.Duration) *DefinitionBuilder
func (*DefinitionBuilder) MaxItems ¶
func (b *DefinitionBuilder) MaxItems(max int) *DefinitionBuilder
func (*DefinitionBuilder) MaxLength ¶
func (b *DefinitionBuilder) MaxLength(max int) *DefinitionBuilder
func (*DefinitionBuilder) Min ¶
func (b *DefinitionBuilder) Min(min float64) *DefinitionBuilder
func (*DefinitionBuilder) MinDuration ¶
func (b *DefinitionBuilder) MinDuration(min time.Duration) *DefinitionBuilder
func (*DefinitionBuilder) MinItems ¶
func (b *DefinitionBuilder) MinItems(min int) *DefinitionBuilder
func (*DefinitionBuilder) MinLength ¶
func (b *DefinitionBuilder) MinLength(min int) *DefinitionBuilder
func (*DefinitionBuilder) OneOf ¶
func (b *DefinitionBuilder) OneOf(allowed ...string) *DefinitionBuilder
OneOf restricts the value to one of the allowed strings (string values only)
func (*DefinitionBuilder) Priority ¶
func (b *DefinitionBuilder) Priority(priority SourcePriority) *DefinitionBuilder
Priority sets the custom priority order for this definition The priority is validated during configuration processing
func (*DefinitionBuilder) Range ¶
func (b *DefinitionBuilder) Range(min, max float64) *DefinitionBuilder
func (*DefinitionBuilder) Regexp ¶
func (b *DefinitionBuilder) Regexp(pattern string) *DefinitionBuilder
func (*DefinitionBuilder) Required ¶
func (b *DefinitionBuilder) Required() *DefinitionBuilder
func (*DefinitionBuilder) Secret ¶
func (b *DefinitionBuilder) Secret() *DefinitionBuilder
func (*DefinitionBuilder) String ¶
func (b *DefinitionBuilder) String() *DefinitionBuilder
func (*DefinitionBuilder) StringSlice ¶
func (b *DefinitionBuilder) StringSlice() *DefinitionBuilder
type ExecutionContext ¶
type ExecutionContext struct {
// contains filtered or unexported fields
}
ExecutionContext provides thread-safe error collection for command execution
func NewExecutionContext ¶
func NewExecutionContext(command string) *ExecutionContext
NewExecutionContext creates a new execution context for the specified command
func (*ExecutionContext) Clear ¶
func (ctx *ExecutionContext) Clear()
Clear removes all collected errors (useful for testing)
func (*ExecutionContext) CollectConfigError ¶
func (ctx *ExecutionContext) CollectConfigError(c *Config, configErr ConfigError)
CollectConfigError adds a normalized config error to the execution context This method preserves the existing Display and ErrorDescription from ConfigError
func (*ExecutionContext) CollectError ¶
func (ctx *ExecutionContext) CollectError(c *Config, key, expectedType, actualType, message string, isSecret bool)
CollectError adds an error to the execution context with thread safety
func (*ExecutionContext) GetCommand ¶
func (ctx *ExecutionContext) GetCommand() string
GetCommand returns the command name for this context
func (*ExecutionContext) GetErrors ¶
func (ctx *ExecutionContext) GetErrors() []GetError
GetErrors returns a copy of all collected errors
func (*ExecutionContext) HasErrors ¶
func (ctx *ExecutionContext) HasErrors() bool
HasErrors returns true if there are collected errors
func (*ExecutionContext) SetCommand ¶
func (ctx *ExecutionContext) SetCommand(command string)
SetCommand updates the command name for this context
type ExitError ¶
type ExitError struct {
Code int
Err error
// Reported is true when the library already printed the details of
// this error (for example the configuration errors of a command), so
// the caller should not print it again.
Reported bool
}
ExitError is an error that carries the process exit code the program should end with. Execute never exits the process itself: the caller passes the result to ExitCode and to os.Exit.
type FileConfig ¶
type FileConfig struct {
// contains filtered or unexported fields
}
FileConfig represents configuration loaded from files
type FlagParser ¶
type FlagParser interface {
// ParseCommand parses flags for command-specific configuration
ParseCommand(args []string, defs map[string]*Definition) (*ParsedFlags, error)
// ParseGlobal parses flags for global configuration
ParseGlobal(args []string, defs map[string]*Definition) (*ParsedFlags, error)
// ConvertFlagErrorsToConfigErrors converts flag parsing errors to ConfigError instances
ConvertFlagErrorsToConfigErrors(errs []error, defs map[string]*Definition) []ConfigError
}
FlagParser provides centralized flag parsing functionality
type GetError ¶
type GetError struct {
Key string
ExpectedType string
ActualType string
Message string
IsSecret bool
Flag string // Flag name (e.g., "port")
EnvVar string // Environment variable name (e.g., "PORT")
Display string
ErrorDescription string
// contains filtered or unexported fields
}
GetError represents an error collected from Get functions
type MiddlewareChain ¶
type MiddlewareChain interface {
// ApplyCommandOnly applies only command-specific middleware (for use within Command.Execute)
ApplyCommandOnly(cmd *Command, baseFunc CommandFunc) CommandFunc
// ApplyGlobalOnly applies only global middleware (for use within Config.Execute)
ApplyGlobalOnly(globalMiddleware []CommandMiddleware, baseFunc CommandFunc) CommandFunc
}
MiddlewareChain manages middleware application and composition
type ParsedFlags ¶
type ParsedFlags struct {
Values map[string]*string // Parsed flag values
FlagSet *flag.FlagSet // The actual FlagSet used
Errors []error // Any parsing errors encountered
}
ParsedFlags contains the results of flag parsing
type Secret ¶
type Secret struct {
// contains filtered or unexported fields
}
Secret wraps a memguard LockedBuffer for secure secret storage
func (*Secret) Bytes ¶
Bytes returns the secret value as bytes The returned slice is only valid until Destroy() is called
func (*Secret) Destroy ¶
func (s *Secret) Destroy()
Destroy securely wipes the secret from memory Multiple calls are safe and will not panic
type SecretStore ¶
type SecretStore struct {
// contains filtered or unexported fields
}
SecretStore holds all secrets for cleanup with thread-safe operations
func (*SecretStore) DestroyAll ¶
func (ss *SecretStore) DestroyAll()
DestroyAll securely destroys all secrets with verification
func (*SecretStore) Get ¶
func (ss *SecretStore) Get(key string) *Secret
Get retrieves a secret with thread safety
func (*SecretStore) Has ¶
func (ss *SecretStore) Has(key string) bool
Has checks if a secret exists and is set
func (*SecretStore) Store ¶
func (ss *SecretStore) Store(key, value string)
Store securely stores a secret with thread safety
type SourcePriority ¶
type SourcePriority []SourceType
SourcePriority defines the priority order for configuration sources
type SourceType ¶
type SourceType int
SourceType represents a configuration source type
const ( SourceDefault SourceType = iota SourceFlag SourceEnv SourceFile )
func (SourceType) String ¶
func (s SourceType) String() string
type StringHelpOutput ¶
type StringHelpOutput struct {
// contains filtered or unexported fields
}
StringHelpOutput captures help output as a string
func (*StringHelpOutput) Get ¶
func (sho *StringHelpOutput) Get() string
Get returns the accumulated output
func (*StringHelpOutput) Print ¶
func (sho *StringHelpOutput) Print(text string) error
Print appends text to the string builder
func (*StringHelpOutput) Reset ¶
func (sho *StringHelpOutput) Reset()
Reset clears the accumulated output
type TypeConverter ¶
type TypeConverter struct{}
TypeConverter handles type-to-string conversions consistently across all value sources
func NewTypeConverter ¶
func NewTypeConverter() *TypeConverter
NewTypeConverter creates a new TypeConverter instance
func (*TypeConverter) ConvertDefaultValue ¶
func (tc *TypeConverter) ConvertDefaultValue(value any, targetType ValueType) (any, error)
ConvertDefaultValue converts a default value to the target ValueType This is the main method that should be used for default value type conversion
func (*TypeConverter) ConvertToDisplayString ¶
func (tc *TypeConverter) ConvertToDisplayString(value any, delimiter string) string
ConvertToDisplayString converts value to string for display purposes Falls back to fmt.Sprintf for unsupported types to ensure display always works
func (*TypeConverter) ConvertToString ¶
func (tc *TypeConverter) ConvertToString(value any, delimiter string) (string, error)
ConvertToString converts any value to string representation for processing Returns error for unsupported types to ensure proper error handling
func (*TypeConverter) IsSupportedType ¶
func (tc *TypeConverter) IsSupportedType(value any) bool
IsSupportedType checks if a type is supported for conversion
type Validation ¶
Validation represents a validation rule
type ValidationCache ¶
type ValidationCache struct {
// contains filtered or unexported fields
}
ValidationCache stores pre-compiled regex patterns for performance
Source Files
¶
- command.go
- command_builder.go
- command_context.go
- command_executor.go
- command_result.go
- command_router.go
- config.go
- config_processor.go
- definition.go
- errors.go
- execution_context.go
- exit.go
- files.go
- flag_parser.go
- get.go
- help_data.go
- help_layer_coordinator.go
- help_models.go
- help_service.go
- help_templates.go
- middleware.go
- middleware_chain.go
- secret.go
- services.go
- type_converter.go
- types.go
- validation.go
Directories
¶
| Path | Synopsis |
|---|---|
|
examples
|
|
|
cli-tool
command
CLI Tool Example - Full-Featured Command Line Application Demonstrates: command system, middleware pipeline, authentication, help customization
|
CLI Tool Example - Full-Featured Command Line Application Demonstrates: command system, middleware pipeline, authentication, help customization |
|
conversions
command
cli Type Conversion TDD Test Suite Tests all supported type conversions across all sources (DEFAULT, ENV, FLAG, FILE)
|
cli Type Conversion TDD Test Suite Tests all supported type conversions across all sources (DEFAULT, ENV, FLAG, FILE) |
|
web-server
command
Web Server Example - Complete Production Application Demonstrates: config-only mode, validation, secrets, file loading, source priority, builder patterns
|
Web Server Example - Complete Production Application Demonstrates: config-only mode, validation, secrets, file loading, source priority, builder patterns |