commandkit

package module
v0.5.2 Latest Latest
Warning

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

Go to latest
Published: Mar 13, 2026 License: MIT Imports: 28 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

CommandKit

A production-ready Go CLI framework that makes building command-line applications simple and enjoyable.

Why CommandKit?

CommandKit eliminates the boilerplate and complexity of building CLI applications, letting you focus on your application logic. With type-safe configuration, automatic help generation, and clear error handling, you can create robust CLIs in minutes, not hours.

🚀 What Makes CommandKit Different
  • Zero Boilerplate: Define once, use anywhere - no repetitive setup code
  • Type Safety: Compile-time guarantees with generics - no more string-based configuration
  • Transparent by Default: Clean output, silent overrides, and clear error messages
  • Production Features: File configuration, secret protection, middleware, and comprehensive validation
  • Performance Optimized: 68% faster template rendering, 79% fewer allocations

Quick Start

Configuration-Only Applications

Perfect for services, daemons, and tools that need configuration without commands:

package main

import (
    "fmt"
    "os"
    
    "github.com/fernandezvara/commandkit"
)

func main() {
    cfg := commandkit.New()

    // Define your configuration - fluent and readable
    cfg.Define("PORT").
        Int64().
        Env("PORT").
        Flag("port").
        Default(8080).
        Range(1, 65535).
        Description("HTTP server port")

    cfg.Define("DATABASE_URL").
        String().
        Env("DATABASE_URL").
        Required().
        Secret().
        Description("Database connection string")

    // Add empty string command for config-only mode
    cfg.Command("").
        Func(func(ctx *commandkit.CommandContext) error {
            // Type-safe access to configuration
            port := commandkit.MustGet[int64](ctx, "PORT")
            dbURL := commandkit.MustGet[string](ctx, "DATABASE_URL")
            
            fmt.Printf("🚀 Server starting on port %d\n", port)
            fmt.Printf("📊 Database: %s\n", maskSecret(dbURL))
            return nil
        }).
        ShortHelp("Start the server").
        LongHelp("Starts the web server with the specified configuration.").
        Config(func(cc *commandkit.CommandConfig) {
            // Add configuration to the default command
            cc.Define("PORT").
                Int64().
                Env("PORT").
                Flag("port").
                Default(8080).
                Range(1, 65535).
                Description("HTTP server port")

            cc.Define("DATABASE_URL").
                String().
                Env("DATABASE_URL").
                Required().
                Secret().
                Description("Database connection string")
        })

    // One line to process everything
    if err := cfg.Execute(os.Args); err != nil {
        os.Exit(1)
    }
    defer cfg.Destroy()
}

func maskSecret(secret string) string {
    if len(secret) <= 8 {
        return strings.Repeat("*", len(secret))
    }
    return secret[:4] + strings.Repeat("*", len(secret)-8) + secret[len(secret)-4:]
}

Usage:

./app                           # Starts with defaults
./app --port 9000               # Starts on port 9000
./app --help                    # Shows help for default command
DATABASE_URL=... ./app          # Starts with environment variable

🎯 Empty String Command - The Magic

CommandKit introduces an elegant solution for configuration-only applications: the empty string command (cfg.Command("")).

When you define an empty string command, it becomes the default action that executes when no command is provided. This creates a seamless experience for:

  • Services & Daemons - Run directly with configuration flags
  • Simple Tools - No need for subcommands, just configure and run
  • Configuration Management - Perfect for apps that just need to load config and start

How it works:

./app                    # Runs empty string command
./app --port 9000        # Empty string command gets the flag
./app --help             # Shows help for empty string command

The empty string command has access to all CommandKit features:

  • ✅ Type-safe configuration access
  • ✅ Environment variable support
  • ✅ Flag parsing and validation
  • ✅ Secret management
  • ✅ Help generation
  • ✅ Error handling

This approach eliminates the need for separate APIs or special cases - configuration-only apps use the exact same command system as complex CLIs!

Command-Based Applications

Perfect for CLI tools with multiple commands and subcommands:

package main

import (
    "fmt"
    "github.com/fernandezvara/commandkit"
)

func main() {
    cfg := commandkit.New()

    // Global configuration
    cfg.Define("VERBOSE").
        Bool().
        Flag("verbose").
        Default(false).
        Description("Enable verbose output")

    // Define commands with their own configuration
    cfg.Command("deploy").
        Func(deployCommand).
        ShortHelp("Deploy the application").
        LongHelp("Deploy the application to the specified environment.").
        Config(func(cc *commandkit.CommandConfig) {
            cc.Define("ENVIRONMENT").
                String().
                Flag("env").
                Required().
                OneOf("dev", "staging", "prod").
                Description("Target environment")
            
            cc.Define("DRY_RUN").
                Bool().
                Flag("dry-run").
                Default(false).
                Description("Show what would be deployed")
        })

    cfg.Command("status").
        Func(statusCommand).
        ShortHelp("Show application status").
        Aliases("st", "info")

    // Execute with professional help and error handling
    cfg.Execute(os.Args)
}

func deployCommand(ctx *commandkit.CommandContext) error {
    env := commandkit.MustGet[string](ctx, "ENVIRONMENT")
    dryRun := commandkit.MustGet[bool](ctx, "DRY_RUN")
    
    if dryRun {
        fmt.Printf("🔍 Would deploy to %s (dry run)\n", env)
    } else {
        fmt.Printf("🚀 Deploying to %s\n", env)
    }
    return nil
}

func statusCommand(ctx *commandkit.CommandContext) error {
    fmt.Println("✅ Application is running")
    return nil
}

🎯 Real-World Usage

Clear Error Handling

CommandKit provides clear, actionable error messages that help users fix problems:

$ go run app.go --port 99999
Usage: app [options]

Configuration errors:
  --port int64 (default: 8080) -> value 99999 is greater than maximum 65535

Flags:
  --port int64 (default: 8080) (valid: 1-65535)
        HTTP server port
File Configuration

Load configuration from JSON, YAML, or TOML files with flexible key mapping:

cfg.Define("PORT").
    Int64().
    Flag("port").
    File("server_port").  // Maps to "server_port" in files
    Default(8080)

cfg.LoadFile("config.json")  // Load once, use everywhere

config.json:

{
  "server_port": 3000,
  "database_url": "postgres://localhost/mydb",
  "log_level": "debug"
}
Silent Override Behavior

CLI tools don't warn about expected behavior:

# Environment variable (8080) → Flag (3000) → Works silently
PORT=8080 go run app.go --port 3000
🚀 Server starting on port 3000

# No confusing warning messages cluttering the output
Secret Protection

Sensitive data gets special treatment:

cfg.Define("API_KEY").
    String().
    Required().
    Secret().
    Description("API authentication key")

// Access safely
secret := cfg.GetSecret("API_KEY")
if secret.IsSet() {
    fmt.Printf("API key configured (%d bytes)\n", secret.Size())
    // Use secret.Value() when actually needed
}

📁 File Configuration

CommandKit supports multiple file formats with flexible key mapping:

Basic Usage
cfg.Define("PORT").
    Int64().
    Flag("port").
    File("port_in_file").  // Look for this key in files
    Default(8080)

cfg.Define("DATABASE_URL").
    String().
    File("db_connection").
    Required().
    Secret()

// Load from environment variable containing file path
cfg.LoadFileFromEnv("CONFIG_FILE")

// Or load directly
cfg.LoadFile("config.json")
Priority System

Configuration sources work seamlessly in priority order:

Flag > Environment > File > Default
Multiple Files
// Load multiple files (later files override earlier ones)
cfg.LoadFiles("config.json", "secrets.json", "local.json")

🔧 Configuration Types

All Types Supported
cfg.Define("PORT").Int64().Default(8080)
cfg.Define("ENABLED").Bool().Default(true)
cfg.Define("NAME").String().Default("app")
cfg.Define("RATE").Float64().Default(100.0)
cfg.Define("TAGS").StringSlice().Default([]string{"v1", "api"})
cfg.Define("TIMEOUT").Duration().Default(30 * time.Second)
Rich Validation
cfg.Define("PORT").
    Int64().
    Range(1, 65535).                    // Numeric range
    Required()                          // Required field

cfg.Define("EMAIL").
    String().
    Regex(`^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$`). // Email format
    MinLength(5).                      // Minimum length
    MaxLength(100).                    // Maximum length

cfg.Define("LOG_LEVEL").
    String().
    OneOf("debug", "info", "warn", "error"). // Enum validation
    Default("info")

🎮 Command System

Commands with Configuration
cfg.Command("deploy").
    Func(deployCommand).
    ShortHelp("Deploy the application").
    LongHelp("Deploy the application to the specified environment.").
    Config(func(cc *commandkit.CommandConfig) {
        cc.Define("ENVIRONMENT").
            String().
            Flag("env").
            Required().
            OneOf("dev", "staging", "prod").
            Description("Target environment")
    })
Subcommands and Aliases
cfg.Command("docker").
    ShortHelp("Docker operations").
    Config(func(cc *commandkit.CommandConfig) {
        cc.Command("run").
            Func(dockerRunCommand).
            ShortHelp("Run Docker container")
        
        cc.Command("stop").
            Func(dockerStopCommand).
            ShortHelp("Stop Docker container")
    })

cfg.Command("start").
    Func(startCommand).
    ShortHelp("Start the service").
    Aliases("run", "up")  // Multiple aliases

🛡️ Middleware System

Add cross-cutting concerns to your commands:

// Global middleware - applies to all commands
cfg.UseMiddleware(commandkit.RecoveryMiddleware())
cfg.UseMiddleware(commandkit.DefaultLoggingMiddleware())
cfg.UseMiddleware(commandkit.DefaultMetricsMiddleware())

// Command-specific middleware
cfg.UseMiddlewareForCommands([]string{"admin", "shutdown"},
    commandkit.TokenAuthMiddleware("ADMIN_TOKEN"))

// Custom middleware
cfg.UseMiddleware(func(ctx *commandkit.CommandContext, next commandkit.HandlerFunc) error {
    start := time.Now()
    err := next(ctx)
    fmt.Printf("Command %s took %v\n", ctx.Command, time.Since(start))
    return err
})

📚 Clear Help

CommandKit automatically generates helpful help:

Global Help
$ go run myapp --help
Usage: myapp <command> [options]

Available commands:
  deploy       Deploy the application
  start        Start the service (aliases: run, up)
  status       Show application status

Use 'myapp <command> --help' for command-specific help
Command Help
$ go run myapp deploy --help
Usage: deploy [options]

Deploy the application to the specified environment.

Flags:
  --env string (required) (oneOf: dev staging prod)
        Target environment
  --dry-run bool (default: false)
        Show what would be deployed

🚀 Examples

CommandKit includes complete examples:

Web Server Example

Location: examples/web-server/

A production-ready web server demonstrating the empty string command approach for configuration-only applications:

cd examples/web-server

# Run with defaults (empty string command executes)
go run main.go

# Use environment variables
DATABASE_URL="postgres://user:pass@localhost/db" \
JWT_SIGNING_KEY="your-32-character-secret-key-here" \
go run main.go

# Override with flags
go run main.go --port 3000 --host 0.0.0.0 --log-level debug

# Get help for the default command
go run main.go --help

# Full help with all options
go run main.go --full-help

Features demonstrated:

  • ✅ Empty string command for config-only mode
  • ✅ Environment variable configuration
  • ✅ Flag-based configuration
  • ✅ Secret management
  • ✅ Validation and error handling
  • ✅ Help generation
CLI Tool Example

Location: examples/cli-tool/

A full-featured CLI tool with commands and middleware:

cd examples/cli-tool

# Deploy with validation
go run main.go deploy --env staging --dry-run=true

# Show system status
go run main.go status --detailed=true

# Manage configuration
go run main.go config --show-secrets=true

📊 Performance

CommandKit is optimized for production use:

  • 68% faster template rendering
  • 79% fewer memory allocations
  • Silent overrides for transparent CLI behavior
  • Zero boilerplate configuration access
  • Thread-safe concurrent operations

🔍 API Reference

Configuration Builder
Method Description
Define(key) Start defining a configuration key
String(), Int64(), Bool(), etc. Set value type
Env(name) Set environment variable name
Flag(name) Set command-line flag name
File(key) Set file key name
Default(value) Set default value
Required() Mark as required
Secret() Mark as secret (memory protected)
Description(text) Set description for help
Validation
Method Description
Range(min, max) Set numeric range validation
OneOf(values...) Set enum validation
Regex(pattern) Set regex validation
MinLength(n) Set minimum string length
MaxLength(n) Set maximum string length
Access Methods
Method Description
Get[T](ctx, key) Get value with type T (returns T, error)
MustGet[T](ctx, key) Get value or panic on error
GetSecret(key) Get a secret value
Execute(args) Execute with command routing
Command Builder
Method Description
Command(name) Define a new command
Func(fn) Set command function
ShortHelp(text) Set short help text
LongHelp(text) Set long help text
Aliases(names...) Set command aliases
Config(fn) Define command-specific config
UseMiddleware(fn) Add middleware

🏁 Getting Started

  1. Install: go get github.com/fernandezvara/commandkit
  2. Try Examples: cd examples/web-server && go run main.go
  3. Read Documentation: Check the examples for real-world patterns
  4. Build: Start with configuration-only mode, add commands as needed

📄 License

MIT License - feel free to use CommandKit in your projects!


CommandKit: Professional CLI applications, simplified. 🚀

Documentation

Overview

commandkit/command.go

commandkit/command_builder.go

commandkit/command_context.go

commandkit/command_executor.go

commandkit/command_router.go

commandkit/config.go

commandkit/config_processor.go

commandkit/definition.go

commandkit/errors.go

commandkit/execution_context.go

commandkit/files.go

commandkit/flag_parser.go

commandkit/get.go

commandkit/help_data.go

commandkit/help_layer_coordinator.go

commandkit/help_models.go

commandkit/help_service.go

commandkit/help_templates.go

commandkit/middleware.go

commandkit/middleware_chain.go

commandkit/overrides.go

commandkit/secret.go

commandkit/service_interfaces.go

commandkit/services.go

commandkit/template_renderer.go

commandkit/type_converter.go

commandkit/types.go

commandkit/validation.go

Index

Constants

This section is empty.

Variables

View Source
var (
	// 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 (current default)
	PriorityFileEnvFlagDefault = SourcePriority{SourceFile, SourceEnv, SourceFlag, SourceDefault}

	// PriorityDefaultOnly uses only Default values
	PriorityDefaultOnly = SourcePriority{SourceDefault}
)

Common priority presets

Functions

func Get

func Get[T any](ctx *CommandContext, key string) (T, error)

Get retrieves a configuration value with proper error handling This function performs early secret detection to prevent type assertion exposure

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 CachedTemplateRenderer added in v0.3.15

type CachedTemplateRenderer struct {
	*GoTemplateRenderer
	// contains filtered or unexported fields
}

CachedTemplateRenderer implements TemplateRenderer with template caching and string builder pool

func (*CachedTemplateRenderer) AddFunction added in v0.3.15

func (r *CachedTemplateRenderer) AddFunction(name string, fn any)

AddFunction adds a custom function to the function map and clears cache

func (*CachedTemplateRenderer) GetFuncMap added in v0.3.15

func (r *CachedTemplateRenderer) GetFuncMap() template.FuncMap

GetFuncMap returns the current function map

func (*CachedTemplateRenderer) Render added in v0.3.15

func (r *CachedTemplateRenderer) Render(templateStr string, data any) (string, error)

Render renders a template with caching and string builder pool optimization

func (*CachedTemplateRenderer) SetFuncMap added in v0.3.15

func (r *CachedTemplateRenderer) SetFuncMap(funcMap template.FuncMap)

SetFuncMap sets the custom function map for templates and clears cache

type Command

type Command struct {
	Name      string
	Func      CommandFunc
	ShortHelp string
	LongHelp  string

	Aliases     []string
	Definitions map[string]*Definition
	SubCommands map[string]*Command
	Middleware  []CommandMiddleware
	// contains filtered or unexported fields
}

Command represents a CLI command with its configuration

func NewCommand

func NewCommand(name string) *Command

NewCommand creates a new command instance

func (*Command) AddSubCommand

func (cmd *Command) AddSubCommand(name string, subCmd *Command)

AddSubCommand adds a subcommand to this command

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

func (cmd *Command) FindSubCommand(name string) *Command

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) Clone

func (b *CommandBuilder) Clone() *CommandBuilder

Clone creates a copy of the command builder for creating variations

func (*CommandBuilder) Config

func (b *CommandBuilder) Config(fn func(*CommandConfig)) *CommandBuilder

Config defines command-specific configuration

func (*CommandBuilder) CustomHelp added in v0.4.1

func (b *CommandBuilder) CustomHelp() *CommandBuilder

CustomHelp enables custom help for this command

func (*CommandBuilder) Func

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
	Flags         map[string]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 (renamed from Get to avoid naming conflict)

func (*CommandContext) IsHelpRequested added in v0.4.1

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) Set

func (ctx *CommandContext) Set(key string, value any)

Set stores data in the context for middleware sharing

type CommandError

type CommandError struct {
	Category   ErrorCategory
	Key        string
	Source     string // "env", "flag", "default", "runtime", "system", "user"
	Value      string // Masked if secret
	Message    string
	Command    string         // Command that generated this error
	SubCommand string         // Subcommand if applicable
	Context    map[string]any // Additional context
}

CommandError represents a unified error type for all command operations

func (*CommandError) Error

func (e *CommandError) Error() string

Error implements the error interface

func (*CommandError) IsSecret

func (e *CommandError) IsSecret() bool

IsSecret returns true if the error is related to a secret value

func (*CommandError) WithCommand

func (e *CommandError) WithCommand(command, subcommand string) *CommandError

WithCommand sets the command context

func (*CommandError) WithContext

func (e *CommandError) WithContext(key string, value any) *CommandError

WithContext adds context to the error

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 AdminOnlyMiddleware

func AdminOnlyMiddleware(adminTokenKey string) CommandMiddleware

AdminOnlyMiddleware creates middleware that only allows admin commands It checks for an admin token in the configuration

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 DefaultErrorHandlingMiddleware

func DefaultErrorHandlingMiddleware() CommandMiddleware

DefaultErrorHandlingMiddleware creates standard error handling with logging

func DefaultLoggingMiddleware

func DefaultLoggingMiddleware() CommandMiddleware

DefaultLoggingMiddleware creates a standard logging middleware with sensible defaults

func DefaultMetricsMiddleware

func DefaultMetricsMiddleware() CommandMiddleware

DefaultMetricsMiddleware creates standard metrics collection

func ErrorHandlingMiddleware

func ErrorHandlingMiddleware(errorHandler func(error, *CommandContext)) CommandMiddleware

ErrorHandlingMiddleware creates middleware that handles errors from command execution The errorHandler function receives the error and command context for logging/monitoring

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 RateLimitMiddleware

func RateLimitMiddleware(maxExecutions int, window time.Duration) CommandMiddleware

RateLimitMiddleware creates middleware that implements basic rate limiting It tracks command execution count in the context

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.Values["duration"] for other middleware to use

func TokenAuthMiddleware

func TokenAuthMiddleware(tokenKey string) CommandMiddleware

TokenAuthMiddleware creates authentication middleware that validates a token from config It looks for the token in the config using the provided key

type CommandResult

type CommandResult struct {
	Error      error
	ExitCode   int
	ShouldExit bool
	Message    string
	Data       any            // Optional data for successful results
	Context    map[string]any // Context information
}

CommandResult represents the result of command execution with unified error handling

func (*CommandResult) Handle

func (r *CommandResult) Handle()

Handle processes the command result according to its state

func (*CommandResult) WithCommand

func (r *CommandResult) WithCommand(command, subcommand string) *CommandResult

WithCommand sets the command context in the CommandResult

func (*CommandResult) WithContext

func (r *CommandResult) WithContext(key string, value any) *CommandResult

WithContext adds context to the CommandResult

type CommandRouter

type CommandRouter interface {
	// RouteCommand parses arguments and routes to the appropriate command
	RouteCommand(args []string, config *Config) (*Command, *CommandContext, error)

	// HandleSubcommands checks for and handles subcommand routing
	HandleSubcommands(cmd *Command, ctx *CommandContext) (*Command, *CommandContext, error)

	// RouteWithErrorHandling is a convenience method that handles special routing cases
	RouteWithErrorHandling(args []string, config *Config) (*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 New

func New() *Config

New creates a new Config instance

func (*Config) Command

func (c *Config) Command(name string) *CommandBuilder

Command starts a new command definition

func (*Config) Define

func (c *Config) Define(key string) *DefinitionBuilder

Define starts a new configuration definition

func (*Config) Destroy

func (c *Config) Destroy()

Destroy cleans up all secrets from memory

func (*Config) Dump

func (c *Config) Dump() map[string]string

Dump returns a map of all configuration values (secrets masked)

func (*Config) Execute

func (c *Config) Execute(args []string) error

func (*Config) GenerateHelp

func (c *Config) GenerateHelp() string

GenerateHelp creates a help message using the new template-based help system

func (*Config) GetDefaultPriority added in v0.3.7

func (c *Config) GetDefaultPriority() SourcePriority

GetDefaultPriority returns the current default priority order

func (*Config) GetOverrideWarnings

func (c *Config) GetOverrideWarnings() *OverrideWarnings

GetOverrideWarnings returns all override warnings

func (*Config) GetSecret

func (c *Config) GetSecret(key string) *Secret

GetSecret retrieves a secret value securely

func (*Config) Has

func (c *Config) Has(key string) bool

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) HasOverrideWarnings

func (c *Config) HasOverrideWarnings() bool

HasOverrideWarnings returns true if there are override warnings

func (*Config) HasSecret

func (c *Config) HasSecret(key string) bool

HasSecret checks if a secret exists and is set

func (*Config) IsSecret

func (c *Config) IsSecret(key string) bool

IsSecret checks if a configuration key is defined as a secret

func (*Config) Keys

func (c *Config) Keys() []string

Keys returns all defined configuration keys

func (*Config) LoadFile

func (c *Config) LoadFile(filename string) error

LoadFile loads configuration from a single file

func (*Config) LoadFileFromEnv added in v0.3.14

func (c *Config) LoadFileFromEnv(envVar string) error

LoadFileFromEnv loads configuration file from environment variable containing the file path

func (*Config) LoadFiles

func (c *Config) LoadFiles(filenames ...string) error

LoadFiles loads configuration from multiple files (later files override earlier ones)

func (*Config) LoadFromEnv

func (c *Config) LoadFromEnv(envVar string) error

LoadFromEnv loads configuration file path from environment variable

func (*Config) PrintOverrideWarnings

func (c *Config) PrintOverrideWarnings()

PrintOverrideWarnings prints override warnings to stderr

func (*Config) SetDefaultPriority added in v0.3.7

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) ShowCommandHelp

func (c *Config) ShowCommandHelp(commandName string) error

ShowCommandHelp displays help for a specific command using the new template-based help system

func (*Config) ShowGlobalHelp

func (c *Config) ShowGlobalHelp() error

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

func NewConfigProcessor

func NewConfigProcessor() ConfigProcessor

NewConfigProcessor creates a new ConfigProcessor instance

type ConsoleHelpOutput

type ConsoleHelpOutput struct{}

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 (*DefinitionBuilder) BoolSlice added in v0.4.4

func (b *DefinitionBuilder) BoolSlice() *DefinitionBuilder

func (*DefinitionBuilder) Clone

Clone creates a copy of the definition builder for creating variations

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) DurationRange

func (b *DefinitionBuilder) DurationRange(min, max time.Duration) *DefinitionBuilder

func (*DefinitionBuilder) DurationRangeSec

func (b *DefinitionBuilder) DurationRangeSec(minSeconds, maxSeconds float64) *DefinitionBuilder

func (*DefinitionBuilder) Env

func (b *DefinitionBuilder) Env(envVar string) *DefinitionBuilder

func (*DefinitionBuilder) File added in v0.3.14

func (b *DefinitionBuilder) File(fileKey string) *DefinitionBuilder

func (*DefinitionBuilder) FileMode added in v0.4.4

func (b *DefinitionBuilder) FileMode() *DefinitionBuilder

func (*DefinitionBuilder) FileModeRange added in v0.4.4

func (b *DefinitionBuilder) FileModeRange(min, max os.FileMode) *DefinitionBuilder

func (*DefinitionBuilder) Flag

func (*DefinitionBuilder) Float32 added in v0.4.4

func (b *DefinitionBuilder) Float32() *DefinitionBuilder

func (*DefinitionBuilder) Float64

func (b *DefinitionBuilder) Float64() *DefinitionBuilder

func (*DefinitionBuilder) Float64Slice added in v0.4.4

func (b *DefinitionBuilder) Float64Slice() *DefinitionBuilder

func (*DefinitionBuilder) IP added in v0.4.4

func (*DefinitionBuilder) IPLoopback added in v0.4.4

func (b *DefinitionBuilder) IPLoopback() *DefinitionBuilder

func (*DefinitionBuilder) IPPrivate added in v0.4.4

func (b *DefinitionBuilder) IPPrivate() *DefinitionBuilder

func (*DefinitionBuilder) IPVersion added in v0.4.4

func (b *DefinitionBuilder) IPVersion(version int) *DefinitionBuilder

IP validation methods

func (*DefinitionBuilder) Int added in v0.4.2

func (*DefinitionBuilder) Int64

func (*DefinitionBuilder) Int64Slice

func (b *DefinitionBuilder) Int64Slice() *DefinitionBuilder

func (*DefinitionBuilder) IntSlice added in v0.4.2

func (b *DefinitionBuilder) IntSlice() *DefinitionBuilder

func (*DefinitionBuilder) ItemsRange

func (b *DefinitionBuilder) ItemsRange(min, max int) *DefinitionBuilder

func (*DefinitionBuilder) LengthRange

func (b *DefinitionBuilder) LengthRange(min, max int) *DefinitionBuilder

func (*DefinitionBuilder) Max

func (*DefinitionBuilder) MaxDuration

func (b *DefinitionBuilder) MaxDuration(max time.Duration) *DefinitionBuilder

func (*DefinitionBuilder) MaxDurationSec

func (b *DefinitionBuilder) MaxDurationSec(maxSeconds float64) *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 (*DefinitionBuilder) MinDuration

func (b *DefinitionBuilder) MinDuration(min time.Duration) *DefinitionBuilder

func (*DefinitionBuilder) MinDurationSec

func (b *DefinitionBuilder) MinDurationSec(minSeconds float64) *DefinitionBuilder

Duration-specific validation methods that work with time.Duration

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

func (*DefinitionBuilder) Path added in v0.4.4

func (*DefinitionBuilder) PathExists added in v0.4.4

func (b *DefinitionBuilder) PathExists() *DefinitionBuilder

Path validation methods

func (*DefinitionBuilder) PathIsDir added in v0.4.4

func (b *DefinitionBuilder) PathIsDir() *DefinitionBuilder

func (*DefinitionBuilder) PathIsFile added in v0.4.4

func (b *DefinitionBuilder) PathIsFile() *DefinitionBuilder

func (*DefinitionBuilder) PathReadable added in v0.4.4

func (b *DefinitionBuilder) PathReadable() *DefinitionBuilder

func (*DefinitionBuilder) PathWritable added in v0.4.4

func (b *DefinitionBuilder) PathWritable() *DefinitionBuilder

func (*DefinitionBuilder) Priority added in v0.3.7

func (b *DefinitionBuilder) Priority(priority SourcePriority) *DefinitionBuilder

Priority sets the custom priority order for this definition

func (*DefinitionBuilder) PriorityDefaultOnly added in v0.3.7

func (b *DefinitionBuilder) PriorityDefaultOnly() *DefinitionBuilder

PriorityDefaultOnly uses only Default values

func (*DefinitionBuilder) PriorityEnvFlagDefault added in v0.3.7

func (b *DefinitionBuilder) PriorityEnvFlagDefault() *DefinitionBuilder

PriorityEnvFlagDefault sets Env > Flag > Default priority

func (*DefinitionBuilder) PriorityFileEnvFlagDefault added in v0.3.7

func (b *DefinitionBuilder) PriorityFileEnvFlagDefault() *DefinitionBuilder

PriorityFileEnvFlagDefault sets File > Env > Flag > Default priority (current default)

func (*DefinitionBuilder) PriorityFlagEnvDefault added in v0.3.7

func (b *DefinitionBuilder) PriorityFlagEnvDefault() *DefinitionBuilder

PriorityFlagEnvDefault sets Flag > Env > Default priority

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) Sources added in v0.3.7

func (b *DefinitionBuilder) Sources(sources ...SourceType) *DefinitionBuilder

Sources sets the available sources for this definition

func (*DefinitionBuilder) String

func (b *DefinitionBuilder) String() *DefinitionBuilder

func (*DefinitionBuilder) StringSlice

func (b *DefinitionBuilder) StringSlice() *DefinitionBuilder

func (*DefinitionBuilder) Time added in v0.4.4

func (*DefinitionBuilder) TimeAfter added in v0.4.4

func (b *DefinitionBuilder) TimeAfter(after time.Time) *DefinitionBuilder

Time validation methods

func (*DefinitionBuilder) TimeBefore added in v0.4.4

func (b *DefinitionBuilder) TimeBefore(before time.Time) *DefinitionBuilder

func (*DefinitionBuilder) TimeRange added in v0.4.4

func (b *DefinitionBuilder) TimeRange(min, max time.Time) *DefinitionBuilder

func (*DefinitionBuilder) URL

func (*DefinitionBuilder) UUID added in v0.4.4

func (*DefinitionBuilder) Uint added in v0.4.4

func (*DefinitionBuilder) Uint8 added in v0.4.4

func (*DefinitionBuilder) Uint16 added in v0.4.4

func (b *DefinitionBuilder) Uint16() *DefinitionBuilder

func (*DefinitionBuilder) Uint32 added in v0.4.4

func (b *DefinitionBuilder) Uint32() *DefinitionBuilder

func (*DefinitionBuilder) Uint64 added in v0.4.4

func (b *DefinitionBuilder) Uint64() *DefinitionBuilder

func (*DefinitionBuilder) ValidFilePermission added in v0.4.4

func (b *DefinitionBuilder) ValidFilePermission() *DefinitionBuilder

FileMode validation methods

type ErrorCategory

type ErrorCategory int

ErrorCategory represents the category of an error

const (
	ErrorCategoryValidation ErrorCategory = iota
	ErrorCategoryConfiguration
	ErrorCategoryRuntime
	ErrorCategorySystem
	ErrorCategoryUser
)

func (ErrorCategory) String

func (c ErrorCategory) String() string

String returns the string representation of the error category

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) DisplayAndExit

func (ctx *ExecutionContext) DisplayAndExit()

DisplayAndExit shows all collected errors and exits with non-zero code

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) GetFormattedErrors

func (ctx *ExecutionContext) GetFormattedErrors() string

GetFormattedErrors returns all collected errors as a simplified fallback string

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 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)

	// GenerateHelp generates consistent help text for flags
	GenerateHelp(defs map[string]*Definition) string

	// ConvertFlagErrorsToConfigErrors converts flag parsing errors to ConfigError instances
	ConvertFlagErrorsToConfigErrors(errors []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 GoTemplateRenderer

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

GoTemplateRenderer implements TemplateRenderer using Go's text/template

func (*GoTemplateRenderer) AddFunction

func (r *GoTemplateRenderer) AddFunction(name string, fn any)

AddFunction adds a custom function to the function map

func (*GoTemplateRenderer) GetFuncMap

func (r *GoTemplateRenderer) GetFuncMap() template.FuncMap

GetFuncMap returns the current function map

func (*GoTemplateRenderer) Render

func (r *GoTemplateRenderer) Render(templateStr string, data any) (string, error)

Render renders a template with the given data

func (*GoTemplateRenderer) SetFuncMap

func (r *GoTemplateRenderer) SetFuncMap(funcMap template.FuncMap)

SetFuncMap sets the custom function map for templates

type MiddlewareChain

type MiddlewareChain interface {
	// Apply combines command-specific and global middleware and applies them in correct order
	Apply(cmd *Command, globalMiddleware []CommandMiddleware, baseFunc CommandFunc) CommandFunc

	// 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 OverrideWarning

type OverrideWarning struct {
	Key        string // Configuration key
	Command    string // Command name (if command-specific)
	Source     string // Source being overridden (global, flag, env, etc.)
	OverrideBy string // Source doing the overriding
	OldValue   string // Previous value (masked if secret)
	NewValue   string // New value (masked if secret)
	Message    string // Warning message
}

OverrideWarning represents a configuration override warning

type OverrideWarnings

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

OverrideWarnings holds all override warnings

func NewOverrideWarnings

func NewOverrideWarnings() *OverrideWarnings

NewOverrideWarnings creates a new warnings collector

func (*OverrideWarnings) Add

func (ow *OverrideWarnings) Add(warning OverrideWarning)

Add adds a new override warning

func (*OverrideWarnings) FormatWarnings

func (ow *OverrideWarnings) FormatWarnings() string

FormatWarnings formats all warnings for display

func (*OverrideWarnings) GetWarnings

func (ow *OverrideWarnings) GetWarnings() []OverrideWarning

GetWarnings returns all warnings

func (*OverrideWarnings) HasWarnings

func (ow *OverrideWarnings) HasWarnings() bool

HasWarnings returns true if there are warnings

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
	Args    []string           // Remaining arguments after flag parsing
}

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

func (s *Secret) Bytes() []byte

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

func (*Secret) IsDestroyed

func (s *Secret) IsDestroyed() bool

IsDestroyed returns true if the secret has been securely destroyed

func (*Secret) IsSet

func (s *Secret) IsSet() bool

IsSet returns true if the secret has a value and hasn't been destroyed

func (*Secret) Size

func (s *Secret) Size() int

Size returns the length of the secret

func (*Secret) String

func (s *Secret) String() string

String returns the secret value as a string The returned string is only valid until Destroy() is called

func (*Secret) VerifyDestroyed

func (s *Secret) VerifyDestroyed() bool

VerifyDestroyed returns true if the secret memory has been securely wiped This provides verification that cleanup was successful

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) IsDestroyed

func (ss *SecretStore) IsDestroyed() bool

IsDestroyed returns true if the store has been destroyed

func (*SecretStore) Keys

func (ss *SecretStore) Keys() []string

Keys returns all secret keys

func (*SecretStore) Size

func (ss *SecretStore) Size() int

Size returns the number of stored secrets

func (*SecretStore) Store

func (ss *SecretStore) Store(key, value string)

Store securely stores a secret with thread safety

func (*SecretStore) VerifyAllDestroyed

func (ss *SecretStore) VerifyAllDestroyed() bool

VerifyAllDestroyed returns true if all secrets have been securely destroyed

type SourcePriority added in v0.3.7

type SourcePriority []SourceType

SourcePriority defines the priority order for configuration sources

type SourceType added in v0.3.7

type SourceType int

SourceType represents a configuration source type

const (
	SourceDefault SourceType = iota
	SourceFlag
	SourceEnv
	SourceFile
)

func (SourceType) String added in v0.3.7

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 TemplateRenderer

type TemplateRenderer interface {
	Render(templateStr string, data any) (string, error)
	SetFuncMap(funcMap template.FuncMap)
	GetFuncMap() template.FuncMap
	AddFunction(name string, fn any)
}

TemplateRenderer renders templates with data

func NewCachedTemplateRenderer added in v0.3.15

func NewCachedTemplateRenderer() TemplateRenderer

NewCachedTemplateRenderer creates a new cached template renderer

func NewGoTemplateRenderer

func NewGoTemplateRenderer() TemplateRenderer

NewGoTemplateRenderer creates a new Go template renderer

type TypeConverter added in v0.4.3

type TypeConverter struct{}

TypeConverter handles type-to-string conversions consistently across all value sources

func NewTypeConverter added in v0.4.3

func NewTypeConverter() *TypeConverter

NewTypeConverter creates a new TypeConverter instance

func (*TypeConverter) ConvertDefaultValue added in v0.4.6

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 added in v0.4.3

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 added in v0.4.3

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 added in v0.4.3

func (tc *TypeConverter) IsSupportedType(value any) bool

IsSupportedType checks if a type is supported for conversion

type UnifiedHelpData added in v0.4.8

type UnifiedHelpData struct {
	Command     *Command
	Usage       string
	Description string
	Flags       []flagInfo
	EnvVars     []flagInfo
	Subcommands []subcommandInfo
	Errors      []GetError
	Mode        helpMode
	HasErrors   bool
}

UnifiedHelpData represents the complete help data for a command

type Validation

type Validation struct {
	Name  string
	Check func(value any) error
}

Validation represents a validation rule

type ValidationCache

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

ValidationCache stores pre-compiled regex patterns for performance

type ValueType

type ValueType int

ValueType represents the expected type of a configuration value

const (
	TypeString ValueType = iota
	TypeInt64
	TypeInt // Platform-specific int type
	TypeFloat64
	TypeBool
	TypeDuration
	TypeURL
	TypeStringSlice
	TypeInt64Slice
	TypeIntSlice // Platform-specific int slice type
	TypeUint
	TypeUint8
	TypeUint16
	TypeUint32
	TypeUint64
	TypeFloat32
	TypeTime
	TypeFloat64Slice
	TypeBoolSlice
	TypeFileMode
	TypeIP
	TypeUUID
	TypePath
)

func (ValueType) String

func (t ValueType) String() string

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
CommandKit Type Conversion TDD Test Suite Tests all type conversions across all sources (DEFAULT, ENV, FLAG, FILE)
CommandKit Type Conversion TDD Test Suite Tests all 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

Jump to

Keyboard shortcuts

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