kli

package module
v0.4.0 Latest Latest
Warning

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

Go to latest
Published: Nov 30, 2026 License: MIT Imports: 25 Imported by: 2 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

kli

A Go library for building command-line applications. A configuration key is declared once — with its type, flag, environment variable, file key, default value and validation rules — and resolved automatically from every source. Commands and subcommands get their own flags and generated help.

  • Typed access through generics: kli.Get[T] and kli.MustGet[T]
  • Flags, environment variables and config files (JSON, YAML, TOML) with a configurable source priority
  • Validation: ranges, enums, regular expressions, length and item bounds, durations, custom checks
  • Secrets held in guarded memory and masked in dumps and help output
  • Commands, subcommands, aliases and a middleware pipeline
  • Execute returns errors that carry exit codes; it never calls os.Exit
  • Environment lookup and standard I/O are injectable for in-process testing

Contents

Quick start

Configuration-only application

For services, daemons and tools that need configuration without commands. cfg.Command("") registers a default command that runs when no command word is given:

package main

import (
    "fmt"
    "os"

    "github.com/fernandezvara/kli"
)

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

    // An empty name makes this the default command.
    cfg.Command("").
        Func(func(ctx *kli.CommandContext) error {
            port := kli.MustGet[int64](ctx, "PORT")
            fmt.Printf("Server starting on port %d\n", port)

            if s := ctx.CommandConfig.GetSecret("DATABASE_URL"); s.IsSet() {
                fmt.Printf("Database configured (%d bytes)\n", s.Size())
            }
            return nil
        }).
        ShortHelp("Start the server").
        Config(func(cc *kli.CommandConfig) {
            cc.Define("PORT").
                Int64().
                Env("PORT").
                Flag("port").
                Default(int64(8080)).
                Range(1, 65535).
                Description("HTTP server port")

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

    err := cfg.Execute(os.Args)
    if err != nil && !kli.IsReported(err) {
        fmt.Fprintln(os.Stderr, err)
    }
    os.Exit(kli.ExitCode(err))
}
DATABASE_URL=postgres://localhost/db ./app               # start with defaults
DATABASE_URL=postgres://localhost/db ./app --port 9000   # flag overrides the default
./app --help                                             # help for the default command

The default command supports everything a named command does — its own definitions, validation, secrets, help and middleware — so configuration-only applications use the same machinery as multi-command tools.

Command-based application

For tools with multiple commands. Each command declares its own configuration inside Config:

package main

import (
    "fmt"
    "os"

    "github.com/fernandezvara/kli"
)

func main() {
    cfg := kli.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 *kli.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")

    err := cfg.Execute(os.Args)
    if err != nil && !kli.IsReported(err) {
        fmt.Fprintln(os.Stderr, err)
    }
    os.Exit(kli.ExitCode(err))
}

func deployCommand(ctx *kli.CommandContext) error {
    env := kli.MustGet[string](ctx, "ENVIRONMENT")
    dryRun := kli.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 *kli.CommandContext) error {
    fmt.Println("Application is running")
    return nil
}

Definitions on cfg itself are global: shared by every command. Their flags go after the command word, among the command's own flags (myapp deploy --verbose); myapp --verbose deploy is an error. Without a command word they belong to the default command, if there is one. Define them before the commands: a command with its own Config accepts only the global definitions that exist when Config is called. kli.Get resolves a key in the command's definitions first, then in the global ones.

Configuration

Types

Seven types:

cc.Define("NAME").String().Default("app")
cc.Define("PORT").Int64().Default(int64(8080))
cc.Define("RATE").Float64().Default(100.0)
cc.Define("ENABLED").Bool().Default(true)
cc.Define("TIMEOUT").Duration().Default(30 * time.Second)
cc.Define("TAGS").StringSlice().Default([]string{"v1", "api"})
cc.Define("NUMBERS").Int64Slice().Default([]int64{1, 2, 3})
Repeated flags

A slice flag collects every occurrence, under any of its names. Each value is also split by the delimiter (a comma by default):

cc.Define("TAGS").StringSlice().Flag("t").Flag("tag")
// -t a --tag b,c  ->  ["a", "b", "c"]

Use Delimiter("") to keep each value exactly as typed, as docker build --build-arg does:

cc.Define("BUILD_ARGS").StringSlice().Flag("build-arg").Delimiter("")
// --build-arg HOSTS=a,b --build-arg DEBUG=1  ->  ["HOSTS=a,b", "DEBUG=1"]

With an empty delimiter an environment variable gives a single item, and a list in a configuration file one item per element. Empty values are ignored. Flags replace the values of other sources; they are not added to them. Repeating a flag of any other type keeps the last value.

Validation
cc.Define("PORT").
    Int64().
    Range(1, 65535).
    Required()

cc.Define("EMAIL").
    String().
    Regexp(`^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$`).
    MinLength(5).
    MaxLength(100)

cc.Define("LOG_LEVEL").
    String().
    OneOf("debug", "info", "warn", "error").
    Default("info")

Custom(name, check) adds a validation function of your own.

Configuration files

JSON, YAML and TOML are supported. File(key) maps a definition to a key in the file:

cc.Define("PORT").
    Int64().
    Flag("port").
    File("server_port").
    Default(int64(8080))

cfg.LoadFile("config.json")                 // one file
cfg.LoadFiles("config.json", "local.json")  // later files override earlier ones
cfg.LoadFileFromEnv("CONFIG_FILE")          // file path taken from an env var
{
  "server_port": 3000,
  "database_url": "postgres://localhost/mydb"
}
Values that are not given

An optional value that no flag, environment variable, file or default provides reads as the empty value of its type, without an error: "", false, 0, 0s or an empty slice. A slice is never nil, so it encodes to JSON as []. Validations run only on values that are given, defaults included, so OneOf needs no default:

cc.Define("MODE").String().Flag("mode").OneOf("new", "patch")

mode, err := kli.Get[string](ctx, "MODE") // "" when --mode is not passed
given := ctx.CommandConfig.Has("MODE")    // false when --mode is not passed

Add Default(value) for a different value, or Required() to refuse a command line without one.

Source priority

Values resolve in priority order — Flag > Environment > File > Default by default. A higher-priority source replaces a lower one silently: a flag overriding an environment variable is normal operation, not something to warn about.

Change the order globally or per definition:

cfg.SetDefaultPriority(kli.PriorityFileEnvFlagDefault)

cc.Define("PORT").
    Int64().
    Flag("port").
    Env("PORT").
    Default(int64(8080)).
    Priority(kli.PriorityEnvFlagDefault)

Presets: PriorityFlagEnvFileDefault, PriorityFlagEnvDefault, PriorityEnvFlagDefault, PriorityFileEnvFlagDefault, PriorityDefaultOnly. A priority that references a source the definition doesn't declare is reported as a configuration error.

Secrets

Secret() stores the value in guarded memory instead of the values map; it is masked in Dump(), and Get refuses to return it:

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

// Inside a command — CommandConfig for command keys, GlobalConfig for global ones:
s := ctx.CommandConfig.GetSecret("API_KEY")
if s.IsSet() {
    fmt.Printf("key configured (%d bytes)\n", s.Size())
    // s.String() / s.Bytes() return the value when needed
}

cfg.Destroy() wipes all stored secrets.

Help doesn't show a secret's default, and an error about a rejected secret value reads invalid value (not shown: secret), so that neither prints it. This covers custom validations too.

Commands

Subcommands and aliases
docker := cfg.Command("docker").ShortHelp("Docker operations")

docker.SubCommand("run").
    Func(dockerRun).
    ShortHelp("Run a container")

docker.SubCommand("stop").
    Func(dockerStop).
    ShortHelp("Stop a container")

cfg.Command("start").
    Func(start).
    ShortHelp("Start the service").
    Aliases("run", "up")
Boolean flags

Bool() definitions are switches: --dry-run sets the value to true, --dry-run=false sets it to false. A boolean flag never consumes the next argument. Boolean values, from any source, are true, 1 or yes and false, 0 or no, in any letter case.

Positional arguments

Arguments left after the flags are a usage error (unknown argument: "stray", exit code 2). A command that takes them says so with AllowArgs() and reads them with ctx.Positional():

cfg.Command("cat").Func(cat).AllowArgs() // app cat --number a.txt b.txt

Flags go first: everything from the first non-flag argument on is positional, including later flags. -- ends the flags, so what follows it needs AllowArgs() too. Subcommands don't inherit it. A program without commands uses cfg.AllowArgs() and reads its own arguments. There are no positional-argument declarations: names, types and counts are up to the command.

Help

app --help, app help, app help <command>, app <command> --help and app <group> help all print help (-h, --h and -help work like --help). A help flag works in any position before --, unless it is the value of the flag in front of it. A word after a group command that is not one of its subcommands (app user zzz) is a usage error.

A help page shows CustomHelp, else the generated page described by LongHelp, else by ShortHelp. CustomHelp is printed as written and replaces the whole page, including the lists of commands, flags and environment variables, for every help flag. Configuration errors are still reported with the generated page.

cfg.LongHelp("Manage deployments.") // app --help, app help
cfg.CustomHelp(appHelp)             // replaces that page

cfg.Command("deploy").
    CustomHelp(deployHelp)          // app deploy --help, app help deploy

users := cfg.Command("user").ShortHelp("Manage users")
users.SubCommand("list").
    CustomHelp(listHelp)            // app user list --help

In a program whose only command is "", the general help is that command's help: the program's CustomHelp, else the command's, and so on.

Exit codes, environment and I/O

Execute never exits the process. It returns an error, and kli.ExitCode(err) gives the exit code to end with:

Situation Code
Success, or help shown 0 (kli.ExitOK)
A command returned an error 1 (kli.ExitFailure)
Unknown command, flag or argument, missing or invalid flag value, unknown subcommand 2 (kli.ExitUsage)
A command returned kli.Exit(code, err) code

A wrong command line is explained on stderr, so a user is never left with only an exit code:

Error: unknown argument: "stray"
Run 'app status --help' for usage.

The library prints:

Problem Printed
Unknown command or subcommand The word, similar command names if any, and the help command to run
Unknown argument The argument and the help command to run (without it in a program with no commands)
Unknown flag, missing or invalid value A usage line and the configuration errors
A command with no Func and no subcommands The command name (exit code 1)

Execute still returns an error for each, and kli.IsReported(err) is true. Errors returned by your commands are not printed: do that in main. Check IsReported so nothing shows twice, and use ExitCode so a wrong command line exits with 2:

func main() {
    cfg := kli.New()
    // ... definitions and commands ...
    err := cfg.Execute(os.Args)
    if err != nil && !kli.IsReported(err) {
        fmt.Fprintln(os.Stderr, err) // your commands' errors; the library prints its own
    }
    os.Exit(kli.ExitCode(err))
}

// in a command:
return kli.Exit(3, errors.New("deploy failed")) // exit code 3

Everything the library reads or writes can be replaced, which makes commands testable in-process:

cfg.SetName("myapp").                                  // program name in usage lines
    SetEnv(func(k string) string { return env[k] }).   // instead of os.Getenv
    SetIO(stdin, stdout, stderr)                       // help -> stdout, errors -> stderr

// in a command: ctx.Getenv("X"), ctx.Stdin(), ctx.Stdout(), ctx.Stderr()

Middleware

Add cross-cutting concerns to your commands:

// Global middleware - applies to all commands
cfg.UseMiddleware(kli.RecoveryMiddleware())
cfg.UseMiddleware(kli.LoggingMiddleware(func(ctx *kli.CommandContext, d time.Duration) {
    log.Printf("%s completed in %v", ctx.Command, d)
}))
cfg.UseMiddleware(kli.MetricsMiddleware(collectMetrics))

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

// Custom middleware - plain functions matching CommandMiddleware
// (see a full example in examples/cli-tool: tokenAuthMiddleware)
func authMiddleware(next kli.CommandFunc) kli.CommandFunc {
    return func(ctx *kli.CommandContext) error {
        // ...validate...
        return next(ctx)
    }
}

Built-in middleware:

Middleware Description
RecoveryMiddleware() Recover from panics in commands
LoggingMiddleware(func(ctx, duration)) Log command execution with timing
MetricsMiddleware(func(ctx, duration, err)) Collect command metrics
AuthMiddleware(func(ctx) error) Validate authentication before execution
TimingMiddleware() Measure and store execution timing in the context
ConditionalMiddleware(cond, mw) Apply middleware only when a condition holds

Error handling

Usage and configuration errors print to stderr together with the usage line; the exit code is 2:

$ DATABASE_URL=x ./app --port 99999
Usage: app [options]

Configuration errors:
  --port int64 (default: 8080, valid: 1-65535, env: PORT) -> value 99999 is greater than maximum 65535

Help output

Global help:

$ myapp --help
Usage: myapp <command> [options]

Available commands:

  deploy       Deploy the application to the specified environment.
  status       (aliases: st, info) Show application status


Use 'myapp <command> --help' for command-specific help

Command help:

$ myapp deploy --help
Usage: myapp deploy [options]

Deploy the application to the specified environment.

Flags:
  --dry-run bool
        Show what would be deployed
  --env string (required, oneOf: ['dev', 'staging', 'prod'])
        Target environment

Examples

Four programs under examples/:

  • web-server — configuration-only application using the empty string command: environment variables, flags, file loading, secrets, validation
  • cli-tool — multi-command tool with subcommands, aliases and a middleware pipeline including token authentication
  • conversions — exercises Get[T] conversions for every supported type across every source
  • read — a command that takes a file path as an argument, with AllowArgs()
cd examples/web-server && go run main.go --help
cd examples/cli-tool && go run main.go help
cd examples/conversions && go run main.go
cd examples/read && go run . read main.go

Benchmarks

benchmark_test.go contains the benchmarks:

go test -run=^$ -bench=. -benchmem

API reference

Definition builder

Returned by cfg.Define(key) and cc.Define(key):

Method Description
String(), Int64(), Float64(), Bool(), Duration(), StringSlice(), Int64Slice() Set value type
Env(name) Environment variable name
Flag(name) Command-line flag name; repeat it to add aliases (Flag("f").Flag("file")). Passing more than one adds up on a slice; otherwise the last one wins. h and help are reserved, and a name can belong to only one definition per command
File(key) Config-file key name
Default(value) Default value
Delimiter(d) Delimiter that splits slice values (default ,); "" disables splitting
Required() Mark as required
Secret() Guarded memory; masked in output
Description(text) Text for help
Priority(p) Per-definition source priority
Min(n), Max(n), Range(min, max) Numeric bounds
OneOf(values...) Enum validation (string values)
Regexp(pattern) Regex validation
MinLength(n), MaxLength(n) String length bounds
MinItems(n), MaxItems(n) Slice item-count bounds
MinDuration(d), MaxDuration(d) Duration bounds
Custom(name, check) Custom validation function
Config
Method Description
New() Create a Config
Define(key) Define a global configuration key
Command(name) Define a command ("" is the default command)
Execute(args) Route and run; returns an error carrying an exit code
SetName(name) Program name shown in usage lines
ShortHelp(text), LongHelp(text) Program description in the general help
CustomHelp(text) Replaces the generated general help page
AllowArgs() Accept leftover arguments in a program without commands
SetEnv(fn) Replace the environment lookup (default os.Getenv)
SetIO(in, out, err) Replace stdin, stdout, stderr
SetDefaultPriority(p) Global default source priority
LoadFile(path), LoadFiles(paths...), LoadFileFromEnv(env) Load configuration files
GetSecret(key), HasSecret(key), IsSecret(key) Secret access
Has(key), Keys() Definition lookup
Dump() All values (secrets masked)
Destroy() Wipe all secrets
GenerateHelp() Generated help text
ShowGlobalHelp(), ShowCommandHelp(name) Print help
UseMiddleware(fn), UseMiddlewareForCommands(names, fn), UseMiddlewareForSubcommands(cmd, names, fn) Register middleware
Command builder
Method Description
Func(fn) Command function
ShortHelp(text), LongHelp(text) Help text
CustomHelp(text) Replaces the generated help page
Aliases(names...) Command aliases
AllowArgs() Accept arguments left after the flags
Config(fn) Command-specific definitions via cc.Define
SubCommand(name) Add a subcommand
Middleware(fn) Command-specific middleware
CommandContext
Member Description
Args, Command, SubCommand Invocation details
GlobalConfig, CommandConfig Resolved configuration
Positional() Arguments left after flag parsing
Getenv(name) Environment lookup through SetEnv
Stdin(), Stdout(), Stderr() Streams from SetIO
Set(k, v), GetData(k) Middleware data sharing
Package functions and exit codes
Function Description
Get[T](ctx, key) Typed lookup (returns T, error); the empty value for an optional value that is not given
MustGet[T](ctx, key) Typed lookup or panic
Exit(code, err) Error that makes ExitCode report code
ExitCode(err) Exit code for the error Execute returned
IsReported(err) Whether the library already printed the error
ExitOK, ExitFailure, ExitUsage Exit codes 0, 1, 2

Install

go get github.com/fernandezvara/kli

License

MIT

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

View Source
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

View Source
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

func Exit(code int, err error) error

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

func ExitCode(err error) int

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

func IsReported(err error) bool

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
	AllowArgs   bool   // accepts arguments left after its flags
	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

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) AllowArgs added in v0.3.6

func (b *CommandBuilder) AllowArgs() *CommandBuilder

AllowArgs lets the command take arguments left after its flags, read with ctx.Positional(). Without it they are a usage error. Subcommands don't inherit it.

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 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). Only a command with AllowArgs receives any.

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

type CommandResult struct {
	Error      error
	ExitCode   int
	ShouldExit bool
	Message    string
}

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 New

func New() *Config

New creates a new Config instance

func (*Config) AllowArgs added in v0.3.6

func (c *Config) AllowArgs() *Config

AllowArgs lets a program without commands receive arguments that are not flags. Without it they are a usage error. Commands have their own CommandBuilder.AllowArgs.

func (*Config) Command

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

Command starts a new command definition

func (*Config) CustomHelp added in v0.3.5

func (c *Config) CustomHelp(help string) *Config

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

func (c *Config) GetDefaultPriority() SourcePriority

GetDefaultPriority returns the current default priority order

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

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) LongHelp added in v0.3.5

func (c *Config) LongHelp(help string) *Config

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

func (c *Config) SetEnv(getenv func(string) string) *Config

SetEnv replaces the environment lookup (default os.Getenv), so programs and tests can supply their own environment.

func (*Config) SetIO

func (c *Config) SetIO(stdin io.Reader, stdout, stderr io.Writer) *Config

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

func (c *Config) SetName(name string) *Config

SetName sets the program name shown in usage lines (default: the executable's base name).

func (*Config) ShortHelp added in v0.3.5

func (c *Config) ShortHelp(help string) *Config

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

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

type ConsoleHelpOutput

type ConsoleHelpOutput struct {
	// W is where help is written; nil means os.Stdout.
	W io.Writer
}

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

Delimiter sets what splits a slice value into items (default ","). With "" values are not split: each one is an item, kept exactly as given.

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

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"). A slice collects every occurrence of any of them; for other types the last one wins. Empty and repeated names are ignored.

func (*DefinitionBuilder) Float64

func (b *DefinitionBuilder) Float64() *DefinitionBuilder

func (*DefinitionBuilder) Int64

func (*DefinitionBuilder) Int64Slice

func (b *DefinitionBuilder) Int64Slice() *DefinitionBuilder

func (*DefinitionBuilder) Max

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 (*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.

func (*ExitError) Error

func (e *ExitError) Error() string

func (*ExitError) Unwrap

func (e *ExitError) Unwrap() error

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

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

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

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
	TypeFloat64
	TypeBool
	TypeDuration
	TypeStringSlice
	TypeInt64Slice
)

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
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)
read command
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
⌂ 换网址