README
¶
cmdguard
End goal: Make it IMPOSSIBLE to NOT create SUPERB CLI apps with near ZERO-BUGs and fantastic User Experience while keeping Code requirements developers and AI Agents need to write to an absolute minimum!
Website · Docs · pkg.go.dev
The Go CLI framework that catches missing handlers, duplicate commands, and invalid flags at construction — not at 2am in production.
cmdguard is the only Go CLI framework that unifies type-safe flags, dependency injection with lifecycle management, and a zero-panic error contract into a single system validated at construction. It wraps Cobra so you keep full compatibility while eliminating its footguns.
Get started in 30 seconds: go get github.com/larsartmann/cmdguard/v5 · Quick Start · Full Docs
API Stability: v5.0.0 is the current release. The v4 line is retired — final release v4.3.1, frozen on the
release/v4branch (bug-fix only); the legacy v2 line is in maintenance at v2.10.4. Migrating from v4? See the v4→v5 Migration Guide (mechanical codemod included). Earlier migrations: v3→v4, v2→v3. Full change history in CHANGELOG.md.
Why cmdguard?
Other Go CLI frameworks give you flags. cmdguard gives you flags plus everything production CLIs need: dependency injection, service lifecycle, health checks, graceful shutdown, styled output, and error handling that won't bite you.
The trinity — what no other CLI framework offers together
| Capability | Cobra | Kong | urfave/cli | cmdguard |
|---|---|---|---|---|
| Struct-tag flags (no string lookups) | — | Yes | — | Yes |
| Dependency injection (lazy services, lifecycle) | — | — | — | Yes |
| Graceful shutdown (reverse-order on SIGINT) | — | — | — | Yes |
Health checks (DoctorCommand, Healthchecker) |
— | — | — | Yes |
Zero panics by construction (no Run, no Must) |
— | — | — | Yes |
| Validated at construction (not at runtime) | — | Some [1] | — | Yes |
| Error printed exactly once + correct exit codes | — | — | — | Yes |
| Styled output by default (fang + lipgloss) | — | — | — | Yes |
| Gradual migration (raw cobra + typed runtime) | — | — | — | Yes |
[1] Kong validates struct tags at parse time but does not validate command structure (missing handlers, duplicates) at registration.
Dependency injection — the real differentiator
Register services, invoke them in handlers, and manage their entire lifecycle:
cli, _ := v5.NewCLI[AppConfig]("myapp", "My production CLI", AppConfig{})
// v5 default: SIGINT/SIGTERM cancels the run and shuts down DI services in reverse order
// Register a database service (lazy — created on first invoke)
v5.Provide(cli.Scope(), func(i do.Injector) (*Database, error) {
return &Database{DSN: "postgres://..."}, nil
})
// Use it in any command handler
v5.NewCommand("query", v5.NoFlags{},
func(ctx context.Context, cfg *AppConfig, _ v5.NoFlags) error {
db, _ := v5.Invoke[*Database](cli.Scope())
return db.Query(ctx)
},
)
Type-safe flags — validated at construction
Raw Cobra — flags are strings, validated at runtime:
var name string
var count int
rootCmd.Flags().StringVarP(&name, "name", "n", "World", "Name to greet")
rootCmd.Flags().IntVarP(&count, "count", "c", 1, "Number of greetings")
// Forgot to add "count"? Missing handler? Duplicate command? Runtime surprise.
cmdguard — flags are typed structs, validated at construction:
type GreetFlags struct {
Name string `flag:"name" short:"n" default:"World" help:"Name to greet"`
Count int `flag:"count" short:"c" default:"1" help:"Number of greetings"`
}
// Missing handler? Duplicate command? Invalid name? Caught at AddCommand time.
Zero panics — by construction
Every function returns errors. No Run (panics), no Must* variants. The error is printed exactly once (styled by fang), usage is silenced on error by default, and exit codes are handled automatically:
cli.ExecuteAndExit(context.Background()) // one line, correct exit code
Machine-readable by default
Every cmdguard CLI can describe itself. A hidden describe command prints the
full command and flag tree as versioned JSON (schema_version, types, defaults,
env vars, enum values, required flags), and the JSON error envelope carries an
actionable hint next to the message:
myapp describe
# {"schema_version":"1","name":"myapp","commands":[{"name":"scan","path":"myapp scan",...}]}
AI agents and tooling can discover and drive your CLI without scraping
--help. The same contract is available programmatically:
cli.Describe() / cli.WriteDescription(w).
Error handling & exit codes
cmdguard owns the error-output contract so you can't get it wrong:
- The error is printed exactly once — styled by fang when enabled (the default), or plain by Cobra when disabled.
- Usage is never printed on error (
SilenceUsage: trueby default). UseWithoutSilenceUsage()to re-enable usage-on-error. - The error returned by
Executeis for exit-code mapping only — do not re-print it, or you'll duplicate the output.
Recommended — one line, correct exit code:
cli.ExecuteAndExit(context.Background())
When you need to run code before exiting (flush logs, export an audit log, tear
down resources), use ExitCode instead of ExecuteAndExit:
err := cli.Execute(ctx)
// ...flush / export audit log / teardown...
os.Exit(v5.ExitCode(err)) // 0 on success, ExitCoder code or 1 on failure
Pitfall to avoid:
if err := cli.Execute(ctx); err != nil { fmt.Fprintln(os.Stderr, err) }re-prints the error that cmdguard already printed.
Quick Start
go get github.com/larsartmann/cmdguard/v5
package main
import (
"context"
"fmt"
"os"
"strings"
"github.com/larsartmann/cmdguard/v5/pkg/cmdguard/v5"
)
type AppConfig struct {
Verbose bool `flag:"verbose" short:"v" default:"false" help:"Enable verbose output"`
Output string `flag:"output" short:"o" default:"text" help:"Output format"`
}
type GreetFlags struct {
Name string `flag:"name" short:"n" default:"World" help:"Name to greet"`
Shout bool `flag:"shout" short:"s" default:"false" help:"Uppercase output"`
}
func main() {
cli, err := v5.NewApp("myapp", "My CLI application", AppConfig{},
func(cli *v5.CLI[AppConfig]) error {
greet, err := v5.NewCommand("greet", GreetFlags{},
func(ctx context.Context, cfg *AppConfig, flags GreetFlags) error {
msg := fmt.Sprintf("Hello, %s!", flags.Name)
if flags.Shout {
msg = strings.ToUpper(msg)
}
fmt.Println(msg)
return nil
},
v5.WithShort("Greet someone"),
)
if err != nil {
return err
}
return v5.AddCommands(cli, greet)
},
v5.WithCLIVersion("1.0.0"),
// v5 note: batteries (strict validation, signals + graceful shutdown,
// strict config keys, version/doctor, hints) are ON by default —
// WithBatteries() is the explicit no-op kept for v4-flavored call sites.
v5.WithBatteries(),
)
if err != nil {
fmt.Fprintf(os.Stderr, "Failed to create CLI: %v\n", err)
os.Exit(1)
}
cli.ExecuteAndExit(context.Background())
}
$ go run main.go greet -n "cmdguard" --shout
HELLO, CMDGUARD!
Features
| Category | Highlights |
|---|---|
| Type-safe flags | Struct tags (flag, short, default, help, env, required, count) — no string lookups |
| Per-command flag types | Each Command[T, F] has its own F — mix different flag structs freely |
| Dependency injection | Built-in samber/do/v2 with Provide, Invoke, lifecycle hooks |
| Environment variables | env:"DB_HOST" tag with WithEnvPrefix("MYAPP_") prefix support |
| 16 output formats | table, JSON, CSV, YAML, Markdown, XML, HTML, D2, Mermaid, JSONL, TOML, PlantUML, and more |
| Signal handling | ON by default (v5) — Ctrl+C cancels the run; WithoutSignalHandling() opts out |
| Typo suggestions | "did you mean?" for flags and subcommands (Levenshtein distance) |
| Constructor validation | Missing handlers, duplicate names, invalid flags — caught at AddCommand time |
| Runtime validation | required, values, and validate tags enforced for flag, env, and default values; string min/max mean length |
| Batteries included | ON by default in v5: strict validation, signals + graceful shutdown, strict config keys, version/doctor commands, hints — WithoutBatteries() drops the set |
| Machine-readable | myapp describe prints a versioned JSON contract of every command and flag; Describe() for programmatic access |
| Errors that teach | Every known failure gets an actionable Hint: line (and a hint field in JSON error output) |
| Flow context | BranchingFlowContext — track command path and share values across hierarchy |
| Config files | WithConfigFile(paths...) — JSON/YAML/TOML auto-loading with flag override |
| Counting flags | count:"true" for -v/-vv/-vvv verbosity patterns |
| Extensible types | RegisterTypeCodec() for custom flag types with full parse/validate support |
| Middleware | TimingMiddleware, RecoveryMiddleware, or write your own; spinner/telemetry/flight-recorder available as sub-modules |
| Interactive prompts | WithPromptOnMissing() with prompt:"Question?" tag via huh |
| Markdown help | glamour.WithHelp() renders Long/Example as styled markdown via glamour |
| Color control | --no-color flag + NO_COLOR env var + cli.NoColor() accessor |
| Shell completion | Dynamic completion via WithCompletion(fn) |
| Positional args | WithExactArgs, WithMinimumArgs, WithRangeArgs, WithNoArgs, or custom |
| Zero panics | All functions return errors; no Must* panic variants |
| Cobra escape hatch | ConfigFromContext[T], WithPostFlagParse, RegisterLocalCommandFlags — raw cobra + cmdguard runtime |
| Scoped flags | local:"true" — root-only flags not inherited by subcommands |
| Hidden flags | hidden:"true" — exclude from --help without losing functionality |
| Verified | 89.3% core coverage, race-detected, fuzz-tested; check-all gates every push |
Dependency Injection
Register services on the CLI scope and invoke them in handlers:
cli, _ := v5.NewCLI[AppConfig]("myapp", "...", AppConfig{})
scope := cli.Scope()
// Register (lazy initialization)
v5.Provide(scope, func(i do.Injector) (*Database, error) {
return &Database{DSN: "postgres://..."}, nil
})
// Invoke in handlers
v5.NewCommand("query", v5.NoFlags{},
func(ctx context.Context, cfg *AppConfig, flags v5.NoFlags) error {
db, _ := v5.Invoke[*Database](cli.Scope())
return db.Query(ctx)
},
)
Services can implement HealthCheck(ctx context.Context) (the do.HealthcheckerWithContext interface, wired into DoctorCommand) and Shutdown (called on the SIGINT/SIGTERM path, reverse invocation order).
Environment Variables
type DBFlags struct {
Host string `flag:"host" env:"DB_HOST" default:"localhost" help:"Database host"`
Port int `flag:"port" env:"DB_PORT" default:"5432" help:"Database port"`
Password string `flag:"password" env:"DB_PASSWORD" help:"Database password"`
}
cli, _ := v5.NewCLI[AppConfig]("myapp", "...", AppConfig{},
v5.WithEnvPrefix("MYAPP_"), // reads MYAPP_DB_HOST, MYAPP_DB_PORT, etc.
)
Priority chain: explicit flag → env var → config file → default value.
Rich Output
import "github.com/larsartmann/go-output"
v5.OutputTable(output.FormatTable, headers, rows) // Aligned terminal table
v5.OutputTable(output.FormatJSON, headers, rows) // JSON array
v5.OutputTable(output.FormatYAML, headers, rows) // YAML
format, _ := output.ParseFormat("csv")
v5.OutputTable(format, headers, rows)
All 16 formats: table, json, csv, tsv, markdown, xml, yaml, html, d2, tree, mermaid, dot, jsonl, asciidoc, toml, plantuml.
Subcommands
listCmd, _ := v5.NewCommand("list", v5.NoFlags{}, listHandler,
v5.WithShort("List users"),
)
createCmd, _ := v5.NewCommand("create", v5.NoFlags{}, createHandler,
v5.WithShort("Create a user"),
)
userCmd, _ := v5.NewParentCommand[AppConfig]("user",
"User management", v5.NoFlags{},
v5.WithSubcommands(listCmd, createCmd),
v5.WithShort("User management"),
)
v5.AddCommand(cli, userCmd)
Registering many commands? The v5 Builder collects constructor errors so you
never write an error ladder, then attaches atomically:
listCmd, err := v5.NewCommand("list", v5.NoFlags{}, listHandler, v5.WithShort("List users"))
createCmd, err2 := v5.NewCommand("create", v5.NoFlags{}, createHandler, v5.WithShort("Create a user"))
b := v5.NewBuilder(cli)
b.Check(err)
b.Check(err2)
v5.AddParent(b, "user", "User management", v5.NoFlags{},
v5.WithSubcommands(listCmd, createCmd), v5.WithShort("User management"))
err = b.Build() // first collected construction error, or nil after attaching all
Lifecycle Hooks
v5.NewCommand("deploy", &Flags{}, runHandler,
v5.WithPreRunE[AppConfig, *Flags](func(ctx context.Context, cfg *AppConfig, flags *Flags) error {
return validateConfig(flags)
}),
v5.WithPostRunE[AppConfig, *Flags](func(ctx context.Context, cfg *AppConfig, flags *Flags) error {
return cleanup()
}),
)
PostRunE only fires on success — Cobra semantics. For cleanup that must run
even on failure, use WithCleanup[T]
which fires after every RunE regardless of outcome.
Raw Cobra Subcommands (Escape Hatch)
cmdguard's Command[T,F] is great for new commands, but real apps often mix
raw *cobra.Command subcommands (gradual migration, third-party commands, or
commands that don't fit the typed-flags pattern). cmdguard provides three APIs
to bridge raw cobra commands with the cmdguard runtime:
// 1. Register raw subcommands on cmdguard's root
cli.RootCommand().AddCommand(myRawCmd)
// 2. Access resolved config from any cobra command context
func(cmd *cobra.Command, _ []string) error {
cfg, ok := v5.ConfigFromContext[AppConfig](cmd.Context())
if !ok { return errors.New("config not initialized") }
// use cfg.Field...
}
// 3. Run initialization (DI, logging, session) after flag parsing
cli, _ := v5.NewCLI[AppConfig]("app", "...", AppConfig{},
v5.WithPostFlagParse[AppConfig](func(cmd *cobra.Command, cfg *AppConfig) error {
// Flags are parsed, config is resolved, context is stored.
// Initialize DI, set up logging, store session for subcommands.
return initDI(cfg)
}),
)
Scoped flags (local:"true") prevent root-only flags from polluting every
subcommand's --help. Use cli.RegisterLocalCommandFlags(cmd) on subcommands
that need the root's execution-flag group.
Built-in Value Types
| Type | Validation |
|---|---|
Duration |
Wraps time.Duration |
Enum[T] |
Validated against allowed values |
LogLevel |
debug / info / warn / error |
URL |
Validated URL string |
Email |
RFC 5322 email validation |
Port |
1–65535 range |
FilePath |
Path cleaning and existence checks |
HostPort |
host:port validation |
Add your own with RegisterTypeCodec():
v5.RegisterTypeCodec(reflect.TypeFor[MyType](), v5.TypeCodecFunc{
ParseFunc: func(value string, _ v5.FlagTag) (any, error) { return MyType{Value: value}, nil },
DefaultFunc: func(_ v5.FlagTag) any { return MyType{} },
})
Flag Tags Reference
type Flags struct {
Name string `flag:"name" short:"n" default:"World" help:"Name"`
Verbose int `flag:"verbose" short:"v" help:"Verbosity" count:"true"`
Host string `flag:"host" default:"localhost" env:"DB_HOST" help:"DB host"`
Mode string `flag:"mode" required:"true" help:"Required!"`
Build string `flag:"build" local:"true" default:"full" help:"Root-only flag"`
Debug string `flag:"debug" hidden:"true" help:"Hidden from --help"`
}
| Tag | Purpose | Example |
|---|---|---|
flag |
Flag name (required) | flag:"name" |
short |
Short flag | short:"n" |
default |
Default value | default:"World" |
help |
Help text | help:"Name to greet" |
env |
Environment variable | env:"DB_HOST" |
required |
Mark as required | required:"true" |
validate |
Runtime validation after parsing | validate:"email,min=5" |
values |
Restrict to a fixed set of values | values:"a,b,c" |
count |
Counting flag | count:"true" |
local |
Root-only, not inherited by subcommands | local:"true" |
hidden |
Exclude from --help but stay functional | hidden:"true" |
Command Options
| Option | Purpose |
|---|---|
WithShort(short) |
Short description |
WithLong(long) |
Long description |
WithExample(example) |
Example usage |
WithAliases(aliases...) |
Alternative names |
(flags passed positionally to NewCommand) |
— |
WithPreRunE[T, F](fn) |
Pre-validation hook |
WithPostRunE[T, F](fn) |
Post-success cleanup |
WithHidden(bool) |
Hide from help |
WithDeprecated(msg) |
Deprecation message |
WithGroupID(id) |
Help group name |
WithExactArgs(n) |
Require exactly n positional args |
WithMinimumArgs(n) |
Require at least n positional args |
WithMaximumArgs(n) |
Allow at most n positional args |
WithValidArgs(args...) |
Restrict args to allowed values |
WithSubcommands(cmds...) |
Attach child commands (parent) |
WithRangeArgs(min, max) |
Require between min and max args |
WithNoArgs() |
Reject any positional args |
WithStrictPositionalArgs() |
Reject undeclared positional args (inert when an explicit validator like WithExactArgs is set) |
WithArgsPassthrough() |
Accept any positionals, ignore extras |
WithArgs(fn) |
Custom cobra.PositionalArgs |
WithPromptOnMissing() |
Interactive prompting for missing flags |
WithCompletion(fn) |
Dynamic shell completion |
CLI Options
cli, _ := v5.NewCLI[AppConfig]("myapp", "My app", AppConfig{},
v5.WithCLIVersion("1.0.0"),
v5.WithEnvPrefix("MYAPP_"),
v5.WithSignalHandling(),
v5.WithFang(true), // Styled help output
v5.WithMiddleware[AppConfig](myMiddleware), // Wrap all handlers
v5.WithStrictValidation(), // Require WithShort on commands
v5.WithConfigValidation[AppConfig](validateFn), // Validate config after parsing
v5.WithPostFlagParse[AppConfig](initFn), // DI init / session storage after flags
)
| Option | Purpose |
|---|---|
WithCLIVersion(v) |
Version string |
WithCLILong(desc) |
Long description |
WithSilenceErrors() |
Suppress error printing (advanced; fang handles this) |
WithSilenceUsage() |
Suppress usage on error (default; kept for compatibility) |
WithoutSilenceUsage() |
Re-enable usage-on-error (opt-in) |
WithFang(bool) |
Styled help output |
WithEnvPrefix(prefix) |
Prefix for env vars |
WithSignalHandling() |
Cancel context on SIGINT/SIGTERM (default ON in v5; WithoutSignalHandling() opts out) |
WithGracefulShutdown() |
Additionally shut down DI services on the signal path (default ON in v5; WithoutGracefulShutdown() opts out) |
WithMiddleware[T](mw...) |
Middleware for all commands |
WithGroup(id, title) |
Help group on root |
WithConfigValidation[T](fn) |
Validate config after flag parsing |
WithPostFlagParse[T](fn...) |
Post-parse hook: DI init, session storage |
WithCleanup[T](fn...) |
Post-RunE cleanup that fires even when RunE errors |
WithStrictValidation() |
Require WithShort on all commands (default ON in v5; WithoutStrictValidation() opts out) |
WithStrictConfigKeys() |
Reject unknown config-file keys (default ON in v5; WithoutStrictConfigKeys() opts out) |
WithoutBatteries() |
Drop the whole v5 production set (strict, signals, shutdown, strict keys, hints, doctor) in one call |
WithDraconianValidation() |
Strict + require WithExample on leaf commands |
WithConfigFile(paths...) |
Auto-load JSON config from first found path |
WithConfigFileLoader(l, paths...) |
Load config with custom loader (YAML/TOML) |
glamour.WithHelp() |
Render markdown in command help text (glamour sub-module) |
telemetry.WithTelemetry[T](tracer) |
OpenTelemetry spans for all commands (telemetry sub-module) |
flightrecorder.WithFlightRecorder[T](cfg) |
Runtime trace snapshots on slow/error (flightrecorder sub-module) |
Error Handling
// All v5 functions return errors — zero panics in library code
cli, err := v5.NewCLI[Config]("app", "...", Config{})
cmd, err := v5.NewCommand("test", NoFlags{}, handler)
// Sentinel errors for errors.Is()
errors.Is(err, v5.ErrInvalidCommand)
errors.Is(err, v5.ErrMissingHandler)
errors.Is(err, v5.ErrDuplicateCommand)
// Rich error types with context
v5.NewCommandError(name, err)
v5.NewFlagError(name, err)
v5.NewFlagErrorWithSuggestion(name, err, suggestion) // includes typo fix
v5.NewExitError(code, err) // custom exit code
// ExitCoder interface — check with errors.As
var exitCoder v5.ExitCoder
errors.As(err, &exitCoder)
exitCoder.ExitCode() // returns custom exit code
Config Files
WithConfigFile auto-detects JSON, YAML, and TOML by file extension. No extra imports needed.
cli, _ := v5.NewCLI[AppConfig]("myapp", "...", AppConfig{},
v5.WithConfigFile("~/.config/myapp/config.yaml", "/etc/myapp/config.json"),
)
Paths are tried in order; missing files are silently skipped. Supports $ENV and ~ expansion. Nested config structs are fully supported (case-insensitive Go field name matching).
Precedence: explicit flag → env var → config file → default value (highest to lowest priority).
Where did this value come from? The opt-in config explain command (WithConfigExplainCommand()) resolves every field to its source — flag, env var, config file, or tag default — in table or JSON form. Fields tagged secret:"true" are redacted to *** while still reporting their source, so provenance is auditable without leaking credentials. CLI.ExplainConfig() is the programmatic form.
Optional Sub-Modules
cmdguard's core stays lean — seven optional features live in standalone sub-modules so you import only what you need:
| Sub-module | Import path | Provides |
|---|---|---|
| glamour | github.com/larsartmann/cmdguard/glamour |
Markdown help rendering (WithHelp, RenderMarkdown) |
| prompts | github.com/larsartmann/cmdguard/prompts |
Interactive prompts via huh (Register) |
| spinner | github.com/larsartmann/cmdguard/spinner |
Terminal spinner middleware (Middleware) |
| telemetry | github.com/larsartmann/cmdguard/telemetry |
OpenTelemetry spans (WithTelemetry, Middleware) |
| flightrecorder | github.com/larsartmann/cmdguard/flightrecorder |
Runtime trace snapshots on slow/error (WithFlightRecorder, Middleware) |
| lint | github.com/larsartmann/cmdguard/lint |
cmdguard usage linter CG001-CG008 (cmdguard-lint CLI + BuildFlow provider) |
| schema | github.com/larsartmann/cmdguard/schema |
JSON Schema 2020-12 emitter for config structs (FromConfig, FromCLI) |
import (
"time"
"github.com/larsartmann/cmdguard/flightrecorder"
"github.com/larsartmann/cmdguard/spinner"
"github.com/larsartmann/cmdguard/telemetry"
)
cli, _ := v5.NewCLI[Config]("app", "...", Config{},
telemetry.WithTelemetry[Config](tracer),
v5.WithMiddleware[Config](spinner.Middleware[Config]("Working...")),
flightrecorder.WithFlightRecorder[Config](flightrecorder.Config{
CaptureOnSlow: true,
SlowThreshold: 200 * time.Millisecond,
CaptureOnError: true,
}),
)
BranchingFlowContext
Track the command execution path and share values across the hierarchy:
func handler(ctx context.Context, cfg *AppConfig, flags *Flags) error {
bfc, ok := v5.GetBranchingFlowContext(ctx)
if ok {
fmt.Println("Path:", bfc.PathString()) // "myapp.resource.list"
bfc.SetValue("key", "value") // propagates to children
val, _ := bfc.GetValue("key") // looks up hierarchy
_ = val
}
return nil
}
Color Output
cmdguard uses fang for styled help output via lipgloss. A --no-color flag is registered by default — pass it to disable color output. Lipgloss also respects the NO_COLOR environment variable automatically.
// Check if color is disabled
if cli.NoColor() {
// use plain output
}
cli, _ := v5.NewCLI[AppConfig]("myapp", "...", AppConfig{},
v5.WithFang(true), // styled help (default)
v5.WithFang(false), // plain text help
)
Version Command
cli, _ := v5.NewCLI[AppConfig]("myapp", "...", AppConfig{},
v5.WithCLIVersion("1.0.0"),
)
versionCmd, err := v5.VersionCommand[AppConfig](cli)
if err != nil {
log.Fatal(err)
}
v5.AddCommand(cli, versionCmd)
// $ myapp version
Test Helpers
The testutil package provides panic and assertion helpers for testing cmdguard CLIs:
import "github.com/larsartmann/cmdguard/v5/pkg/testutil"
testutil.AssertNoError(t, err)
testutil.AssertErrorIs(t, err, v5.ErrInvalidCommand)
testutil.AssertPanics(t, func() { /* ... */ })
See examples/taskctl/main_test.go for integration test patterns using ExecuteWithArgs.
Examples
examples/taskctl/— a production-grade task manager CLI demonstrating all features: DI, typed flags, middleware, subcommands, config files, rich output, and more.examples/config-explain/— the opt-inconfig explainprovenance command with a sample YAML config.examples/docs-generator/—GenerateDocsusage for publishing command-tree markdown.
Development
# Enter dev shell (Go 1.27, gopls, golangci-lint)
nix develop
# Run tests
go test ./... -count=1 -timeout 120s -race
# Lint
golangci-lint run ./...
# Format (Nix + Go via treefmt)
nix fmt
# Check everything
nix flake check
See CONTRIBUTING.md for full contribution guidelines.
Documentation
Full docs at cmdguard.lars.software
- Installation — Get started in 30 seconds
- Quick Start — Build a CLI in under a minute
- Type-Safe Flags — Struct tags reference
- Custom Value Types — Built-in types and RegisterTypeCodec
- Dependency Injection — samber/do/v2 integration
- Lifecycle & Signals — Graceful shutdown, WithCleanup, Doctor
- Error Handling — Zero panics, exit codes, sentinel errors
- Audit Log — DI audit trail in 11 export formats
- Migrating from Cobra — Step-by-step guide
- API Reference — Full API on pkg.go.dev
Local docs: Tutorial, Quick Start, Framework Comparison, Performance, CLI Design Principles, Domain Language, Error Reference.
Related Projects
| Project | Description |
|---|---|
| spf13/cobra | The CLI framework cmdguard wraps |
| samber/do | Dependency injection container |
| charm.land/fang | Styled output for Cobra |
| larsartmann/go-output | Rich output formats (16 formats) |
| samber-do-auditlog | DI audit logging integration |
| charm.land/huh | Interactive prompts (prompts sub-module) |
| charm.land/glamour | Markdown rendering (glamour sub-module) |
| charm.land/lipgloss | Terminal spinner (spinner sub-module) |
License
Directories
¶
| Path | Synopsis |
|---|---|
|
docs
|
|
|
examples
|
|
|
config-explain
command
Command config-explain demonstrates cmdguard's configuration features: config files, strict key checking, value provenance (`config explain`), and the secret:"true" redaction marker.
|
Command config-explain demonstrates cmdguard's configuration features: config files, strict key checking, value provenance (`config explain`), and the secret:"true" redaction marker. |
|
docs-generator
command
Command docs-generator demonstrates cmdguard's GenerateDocs API.
|
Command docs-generator demonstrates cmdguard's GenerateDocs API. |
|
taskctl
command
Package main demonstrates every major cmdguard feature in a production-grade task manager.
|
Package main demonstrates every major cmdguard feature in a production-grade task manager. |
|
pkg
|
|
|
cmdguard/v5
Package v5 provides a type-safe, dependency-injection-powered CLI framework built on Cobra.
|
Package v5 provides a type-safe, dependency-injection-powered CLI framework built on Cobra. |
|
testutil
Package testutil provides shared testing utilities for cmdguard tests.
|
Package testutil provides shared testing utilities for cmdguard tests. |
|
version
Package version holds the single source of truth for the example CLIs' version string.
|
Package version holds the single source of truth for the example CLIs' version string. |