cli

package
v0.3.0 Latest Latest
Warning

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

Go to latest
Published: Oct 25, 2026 License: MIT Imports: 14 Imported by: 0

README

Native Cobra console

This package builds and validates Cobra command trees. Commands receive already constructed services; app owns configuration and resource lifetime. The console guide covers application commands, arguments, streams, errors and administration.

Try an independent command

go run ./examples/cli greet --name Ada

Expect Hello, Ada!. This example builds a native tree through cli.New without constructing the full app or opening PostgreSQL/Redis.

For an application command, select your configured profile:

APP_ENV_FILE=.env.quickstart.example go run ./cmd/cli help

App construction is intentional even for help and completion. The root shows full nested paths; help identity show supplies detailed per-command help.

Register a module group

Keep command constructors in internal/modules/<module>/delivery/cli, accepting the owner contract, such as service.UserService. In the module's Register function:

if targets.RootCommand != nil {
    targets.RootCommand.AddCommand(modulecli.New(users))
}

This Identity registration fragment borrows the constructed users service. Adding a command requires no separate app catalog. Use native Cobra flags, aliases and argument validators; services still validate business values.

Own one invocation

Rule Reason
Use cmd.Context() Preserve cancellation, logging and tracing
Use command input/output streams Support redirection and test capture
Return errors from RunE Let the entry point report once after cleanup
Join work before returning App may close borrowed clients afterward
Build fresh trees Cobra flags/state are mutable and not concurrency-safe

cli.New validates its initial commands; cli.Validate checks the finished tree after module additions. They reject duplicate names/aliases, reused command pointers and invalid ownership. Automatic Cobra error/usage printing is disabled; the executable reports returned errors once.

app.Execute closes resources after success, error or panic. Ordinary commands do not start HTTP/metrics listeners, task workers, local event consumers or schedules. Resource clients can still maintain connections and export telemetry. Only serve starts service runners.

Scheduled commands and queue administration

Scheduled commands use fresh factories registered in ScheduledCommands; workers never execute the interactive tree. Central app schedules choose the timing. See scheduling.

NewQueueCommand borrows an Asynq Inspector. Queue CLI administration is always available in the application; the optional web dashboard is a separate setting. Native inspector operations use client timeouts and do not take a context.

GoChannel events published by an ordinary CLI command cannot reach another process. Enqueue a durable task for work that must survive command exit; queue acceptance does not establish business completion.

Focused Cobra tests live here. App execution tests live in tests/app; business command behavior belongs in the external module suites.

Documentation

Overview

Package cli assembles module commands into a Cobra command tree. Applications own dependency construction, signal handling, and exit codes.

Index

Constants

View Source
const CommandTask = "app.command"

CommandTask is the persisted task type for allowlisted command invocations.

Variables

This section is empty.

Functions

func New

func New(cfg Config, commands ...*cobra.Command) (*cobra.Command, error)

New validates and attaches fresh, unparented module commands to a root command. It does not open dependencies or start services. The caller owns the returned tree and should construct a fresh one per invocation; Cobra trees are mutable and must not execute concurrently. Errors are returned without being printed.

func NewQueueCommand

func NewQueueCommand(inspector *asynq.Inspector) *cobra.Command

NewQueueCommand builds native Asynq administration commands without I/O. Administrative commands are opt-in. They borrow the same bounded Redis client as workers and are intentionally absent from public HTTP routes. The inspector must be non-nil and remain open until command execution finishes.

func Validate

func Validate(root *cobra.Command) error

Validate checks a completed command tree after modules have added commands. Call it before the first execution: Cobra adds its own help and completion commands during execution. Validation does not execute commands or attach them.

Types

type Config

type Config struct {
	Use     string
	Short   string
	Version string
	In      io.Reader
	Out     io.Writer
	Err     io.Writer
}

Config describes the root command and its streams. Nil streams use the process standard streams. Version is optional and enables Cobra's --version flag.

type ScheduledCommands

type ScheduledCommands struct {
	// contains filtered or unexported fields
}

ScheduledCommands is an explicit allowlist and native Asynq handler. Its zero value is ready to use. Install it with mux.Handle(CommandTask, commands). Register sequentially during assembly, then treat it as immutable. Each factory must return a fresh standalone command with no parent and no shared flag state. Commands borrow services, honor context cancellation and never exit the process.

func (*ScheduledCommands) ProcessTask

func (c *ScheduledCommands) ProcessTask(ctx context.Context, task *asynq.Task) error

ProcessTask runs one fresh command instance. The registry is read-only after registration, so different invocations can execute concurrently without sharing Cobra state. Unknown tasks and malformed payloads skip retries.

func (*ScheduledCommands) Register

func (c *ScheduledCommands) Register(name string, factory func() *cobra.Command) error

func (*ScheduledCommands) Task

func (c *ScheduledCommands) Task(name string, args ...string) (*asynq.Task, error)

Task creates a durable command invocation. Arguments are passed as tokens, never interpreted by a shell. Name must have been explicitly registered.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL