Skip to content

Lifecycle & Signal Handling

v5 turns the production defaults on at NewCLI. Every one has an opt-out.

Battery Default Opt-out
Strict command validation on WithoutStrictValidation()
Signal handling on WithoutSignalHandling()
Graceful DI shutdown on WithoutGracefulShutdown()
Strict config keys on WithoutStrictConfigKeys()
Actionable error hints on WithoutErrorHints()
Hidden describe command on WithoutDescribeCommand()
Auto doctor command on WithoutBatteries()
Auto version command on when WithCLIVersion is set WithoutBatteries()

WithoutBatteries() drops the whole production set. WithBatteries() remains as an explicit reinforcement that re-enables it after a Without* opt-out.

Signal handling is on by default (WithSignalHandling()): SIGINT and SIGTERM cancel the execution context. Handlers observe cancellation through ctx.Done() or ctx.Err().

func(ctx context.Context, cfg *AppConfig, _ v5.NoFlags) error {
select {
case <-ctx.Done():
return ctx.Err() // SIGINT or SIGTERM received
case result := <-work:
return process(result)
}
}

WithoutSignalHandling() disables context cancellation and with it graceful shutdown. WithoutGracefulShutdown() keeps cancellation but skips DI teardown.

Graceful shutdown fires only when the run was signal-cancelled. A normally completing Execute never tears down the DI scope. Services implementing do.ShutdownerWithError are stopped during scope shutdown; samber/do stops services with no dependents first, in parallel batches.

type Database struct{ conn *sql.DB }
func (db *Database) Shutdown() error {
return db.conn.Close() // runs on SIGINT/SIGTERM
}

Register the service with v5.Provide(cli.Scope(), func(i do.Injector) (*Database, error) { ... }). For explicit teardown after normal completion, call cli.Shutdown(ctx).

ExecuteWithArgs can be called repeatedly on one CLI: every execution resets flag state and the typed config to the post-constructor snapshot, so values from an earlier run never leak into a later one. Because normal completion does not shut the scope down, tests and embedded runners are safe.

Hook Scope Fires
WithPreRunE[T, F] per command after flags are parsed, before RunE
WithPostRunE[T, F] per command after a successful RunE only
WithCleanup[T] CLI-wide after every RunE, success or error
WithPostFlagParse[T] CLI-wide after flag parsing and config validation, before handlers

Cobra does not run PostRunE when RunE returns an error. WithCleanup covers that gap: it fires after every RunE including failures and also wraps raw cobra subcommands added to the tree. Cleanup errors join with errors.Join and never swallow the original run error.

package main
import (
"context"
"errors"
"fmt"
"os"
"time"
"github.com/larsartmann/cmdguard/v5/pkg/cmdguard/v5"
"github.com/spf13/cobra"
)
type AppConfig struct {
Timeout time.Duration `flag:"timeout" default:"5s" help:"Work timeout"`
}
func main() {
cli, err := v5.NewCLI[AppConfig]("worker", "Example worker", AppConfig{},
v5.WithCLIVersion("1.0.0"),
v5.WithCleanup[AppConfig](func(cmd *cobra.Command, cfg *AppConfig, runErr error) error {
fmt.Fprintf(os.Stderr, "cleanup %s: runErr=%v\n", cmd.Name(), runErr)
return nil
}),
)
if err != nil {
fmt.Fprintf(os.Stderr, "creating CLI: %v\n", err)
os.Exit(1)
}
work, err := v5.NewCommand("work", v5.NoFlags{},
func(ctx context.Context, cfg *AppConfig, _ v5.NoFlags) error {
select {
case <-ctx.Done():
return ctx.Err()
case <-time.After(cfg.Timeout):
fmt.Println("work finished")
return nil
}
},
v5.WithShort("Do the work"),
)
b := v5.NewBuilder(cli)
v5.Try(b, work, err)
if buildErr := b.Build(); buildErr != nil {
fmt.Fprintf(os.Stderr, "registering commands: %v\n", buildErr)
os.Exit(1)
}
err = cli.Execute(context.Background())
err = errors.Join(err, cli.Shutdown(context.Background()))
os.Exit(v5.ExitCode(err))
}

WithPostFlagParse[T] is the replacement for hand-wrapped PersistentPreRunE; it runs after parsing and config validation but before any handler.

version is registered automatically when WithCLIVersion is set, and doctor is registered always. A consumer-defined command with either name wins over the built-in.

Terminal window
$ worker version
worker 1.0.0
$ worker doctor
✓ database ok
✓ cache ok
2 passed, 0 failed

DoctorCommand checks every DI service implementing do.HealthcheckerWithContext and accepts custom checks:

docCmd, err := v5.DoctorCommand(cli,
v5.WithDoctorCheck("external-api", func(ctx context.Context) error {
return pingExternalAPI(ctx)
}),
)

Custom checks run after the DI health checks and appear as one report line each.