Quick Start
Your First cmdguard CLI
Section titled “Your First cmdguard CLI”Create a main.go with typed flags, a command, and proper exit codes:
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.NewCLI[AppConfig]("myapp", "My CLI application", AppConfig{}) if err != nil { fmt.Fprintf(os.Stderr, "Failed to create CLI: %v\n", err) os.Exit(1) }
greetCmd, 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"), )
b := v5.NewBuilder(cli) v5.Try(b, greetCmd, err) if err := b.Build(); err != nil { fmt.Fprintf(os.Stderr, "Failed to register command: %v\n", err) os.Exit(1) }
cli.ExecuteAndExit(context.Background())}Run It
Section titled “Run It”$ go run main.go greet -n "cmdguard" --shoutHELLO, CMDGUARD!What Just Happened?
Section titled “What Just Happened?”NewCLI[AppConfig]— created the root CLI with your config struct as a type parameter. In v5 the production batteries are ON by default: strict command validation, signal handling with graceful DI shutdown, strict config keys, actionable error hints, and auto-registereddoctor(plusversionwhen a CLI version is set). Each has aWithout*opt-out.NewCommand("greet", GreetFlags{}, handler)— created a command with its own typed flag struct (by value, parsed into the handler’s third parameter)NewBuilder+Try+Build()— the v5 registration path: constructor errors are collected (no error ladder) andBuild()attaches atomicallyExecuteAndExit(ctx)— ran the CLI and exited with the correct code
Subcommands
Section titled “Subcommands”Group related commands under a parent:
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)Migrating from v4? Run the codemod — it rewrites module paths, import aliases, and the renames mechanically.
Next Steps
Section titled “Next Steps”- Type-Safe Flags — all available struct tags
- Dependency Injection — register and invoke services
- Error Handling — exit codes, sentinel errors, and the print contract