Migrating from Cobra
Why migrate
Section titled “Why migrate”cmdguard v5 wraps Cobra, so raw *cobra.Command trees keep running inside a cmdguard root. You can adopt the root CLI first and convert commands one at a time. What you gain as you convert:
- Typed flags from struct tags instead of
cmd.Flags().GetString(...)calls. - Construction that returns errors instead of panicking, with validation at registration time.
- Error display owned by the framework: printed once, usage suppressed, exit code mapped.
- A DI scope, config-file loading, and production defaults without extra wiring.
Cobra and cmdguard side by side
Section titled “Cobra and cmdguard side by side”| Task | Cobra | cmdguard v5 |
|---|---|---|
| Define a flag | cmd.Flags().StringP("name", "n", "World", "Name") |
Name string `flag:"name" short:"n" default:"World" help:"Name"` |
| Read a value | cmd.Flags().GetString("name") plus error check |
flags.Name, typed |
| Required flag | MarkFlagRequired plus your own check |
required:"true" tag, enforced after parsing |
| Enum or range check | hand-written | values:"a,b,c", validate:"min=1,max=100" |
| Add a subcommand | parent.AddCommand(child) |
NewParentCommand plus WithSubcommands(...) |
| Handler | RunE(cmd, args) |
func(ctx, *AppConfig, Flags) error |
| Positional args | the args parameter |
v5.ArgsFromContext(ctx) |
| Shared services | package globals | v5.Provide / v5.Invoke on cli.Scope() |
| Env var fallback | os.Getenv in the handler |
env:"VAR_NAME" tag |
| Exit code | os.Exit(1) |
v5.ExitCode, v5.NewExitError, ExecuteAndExit |
Strategy 1: cmdguard root, keep the Cobra tree
Section titled “Strategy 1: cmdguard root, keep the Cobra tree”Wrap the existing tree without rewriting it:
type AppConfig struct { Verbose bool `flag:"verbose" short:"v" default:"false" help:"Verbose output"`}
func main() { cli, err := v5.NewCLI[AppConfig]("myapp", "My application", AppConfig{}) if err != nil { fmt.Fprintln(os.Stderr, err) os.Exit(1) }
// Existing Cobra commands keep working unchanged. cli.RootCommand().AddCommand(greetCmd)
cli.ExecuteAndExit(context.Background())}AddCommand and AddCommands accept only cmdguard commands: AddableCommand[T] is sealed, so a raw *cobra.Command is not accepted there. cli.RootCommand() is the escape hatch for Cobra trees.
Legacy commands added this way inherit the root’s persistent flags, cmdguard’s error printing, the exit-code mapping, and signal handling. They do not get typed flag parsing or DI injection.
Strategy 2: convert one command
Section titled “Strategy 2: convert one command”Before, in plain Cobra:
var env stringvar dryRun bool
deployCmd := &cobra.Command{ Use: "deploy", Short: "Deploy the application", RunE: func(cmd *cobra.Command, args []string) error { if env == "" { return errors.New("--env is required") } fmt.Printf("deploying to %s (dry-run=%v)\n", env, dryRun) return nil },}deployCmd.Flags().StringVarP(&env, "env", "e", "", "Target environment")deployCmd.Flags().BoolVarP(&dryRun, "dry-run", "d", false, "Simulate the deployment")_ = deployCmd.MarkFlagRequired("env")After, in cmdguard v5:
type DeployFlags struct { Env string `flag:"env" short:"e" required:"true" help:"Target environment"` DryRun bool `flag:"dry-run" short:"d" default:"false" help:"Simulate the deployment"`}
deployCmd, err := v5.NewCommand("deploy", DeployFlags{}, func(ctx context.Context, cfg *AppConfig, flags DeployFlags) error { fmt.Printf("deploying to %s (dry-run=%v)\n", flags.Env, flags.DryRun) return nil }, v5.WithShort("Deploy the application"),)The flag struct is passed and received by value. required:"true" replaces MarkFlagRequired and its manual check. Construction errors surface from NewCommand; registration errors surface from AddCommand, AddCommands, or Builder.Build.
Register it with v5.AddCommand(cli, deployCmd), or collect constructor errors with v5.NewBuilder(cli), v5.Try(b, deployCmd, err), and b.Build().
Strategy 3: escape hatches around raw Cobra
Section titled “Strategy 3: escape hatches around raw Cobra”| Need | API |
|---|---|
| Resolved root config inside a raw handler | v5.ConfigFromContext[AppConfig](cmd.Context()) (*AppConfig, bool) |
| Positional args inside a typed handler | v5.ArgsFromContext(ctx) []string |
| Work after flag parsing and config validation | v5.WithPostFlagParse[AppConfig](func(cmd *cobra.Command, cfg *AppConfig) error) |
| Teardown that must run even when the handler fails | v5.WithCleanup[AppConfig](func(cmd *cobra.Command, cfg *AppConfig, runErr error) error) |
| Root-only flags on a specific subcommand | cli.RegisterLocalCommandFlags(cmd) error |
| The underlying root command | cli.RootCommand() *cobra.Command |
func(cmd *cobra.Command, args []string) error { cfg, ok := v5.ConfigFromContext[AppConfig](cmd.Context()) if !ok { return errors.New("config not initialized") } return run(cmd.Context(), cfg, args)}ConfigFromContext is populated by the root’s PersistentPreRunE. A raw subcommand that defines its own PersistentPreRunE replaces the root’s hook, because Cobra runs only the first persistent hook it finds, so ConfigFromContext returns false there. WithPostFlagParse runs from the same root hook, so it is skipped in that case too. Convert the command, or do the initialization directly in its RunE.
Flag scoping
Section titled “Flag scoping”A flag’s home decides its scope:
| Where the field lives | Scope |
|---|---|
Root T struct, plain field |
Persistent, inherited by every subcommand |
Root T struct with local:"true" |
Root only |
A command’s own F struct |
That command only, rejected elsewhere |
type AppConfig struct { Verbose bool `flag:"verbose" short:"v" default:"false" help:"Verbose output"` Build string `flag:"build" default:"full" local:"true" help:"Root only"`}
type ScanFlags struct { Depth int `flag:"depth" default:"3" help:"Scan depth"`}With those types, scan --depth 5 works, scan --build fails with “unknown flag”, and --verbose works everywhere. Migrating an old root-only flag means adding local:"true" and calling cli.RegisterLocalCommandFlags(cmd) on each command that still needs it.
Defaults you inherit on day one
Section titled “Defaults you inherit on day one”| Default | Effect | Opt out |
|---|---|---|
| Strict validation | Every cmdguard command needs WithShort (ErrMissingShort) |
WithoutStrictValidation() |
| Signal handling | SIGINT/SIGTERM cancel the execution context |
WithoutSignalHandling() |
| Graceful DI shutdown | Services shut down on the signal path | WithoutGracefulShutdown() |
| Strict config keys | Unknown config keys fail with ErrConfigUnknownKey |
WithoutStrictConfigKeys() |
| Error hints | A Hint: line under classified errors |
WithoutErrorHints() |
| Auto commands | doctor, plus version when WithCLIVersion is set |
WithoutBatteries() |
SilenceUsage is also on by default, so a failed command prints its error without dumping the help text.
Replace your hand-rolled…
Section titled “Replace your hand-rolled…”Even a 100/100 cmdguard adopter still hand-rolled its exit-code ladder and a
version command — both shipped features. If a CLI concern has you writing
plumbing, delete it:
| You are maintaining… | Delete it, use… |
|---|---|
fmt.Fprintln(os.Stderr, …) + os.Exit(1) ladder |
cli.ExecuteAndExit(ctx) — error printed exactly once, exit code mapped |
A hand-rolled version cobra command |
WithCLIVersion("1.0.0") — the command registers itself |
| An ad-hoc “is the DB up?” self-check | auto-registered doctor + do.HealthcheckerWithContext services |
| “did you mean?” typo handling (or a TODO about it) | automatic — flag and command suggestions ship by default (lst suggests list) |
| Manual SIGINT handling and service teardown | WithGracefulShutdown() — ON by default in v5, reverse invocation order |
| A config loader with precedence bugs | WithConfigFile(paths…) — flag → env → file → default, strict keys on |
| Usage dump on every error (cobra’s default) | SilenceUsage is true by default; WithoutSilenceUsage() opts back in |
Every claim above is replayable — verify before trusting. In a checkout of the cmdguard repo:
# Zero panics: no Must* constructors exist in library coderg -n 'func Must' pkg/ --glob '!*_test.go' # prints nothing
# Duplicate commands rejected at registration (constructor validation)GOEXPERIMENT=jsonv2 go test ./pkg/cmdguard/v5 -run 'TestAddCommands_AtomicOnDuplicate' -count=1
# DI underneath: samber/do/v2 in the module graphrg -n 'samber/do' go.mod
# The machine contract, live from the flagship example(cd examples/taskctl && GOEXPERIMENT=jsonv2 go run . describe | head -8)Gotchas
Section titled “Gotchas”PostRunEdoes not run whenRunEfails. UseWithCleanup[T], which runs on both paths and joins cleanup errors witherrors.Join.- Raw Cobra commands do not receive DI. Invoke services manually with
v5.Invoke[*Database](cli.Scope()), or convert the command. NoFlagsis a distinct named type. Passv5.NoFlags{}rather thanstruct{}{}.- Do not print the error returned by
ExecuteorExecuteWithArgs. cmdguard printed it once already. - A command with no handler fails at
NewCommandwithErrMissingHandler; parent commands useNewParentCommandinstead.
Where to go next
Section titled “Where to go next”- Quick Start: the minimal v5 program.
- Type-Safe Flags: every struct tag and its precedence.
- Dependency Injection: services for the commands you keep as raw Cobra.
- Migrating from v4 to v5: if the project already uses cmdguard.