Documentation
¶
Overview ¶
Package cmd defines the commands of an application binary: the built-in ones (run, serve, migrate, routes:list, …) and your own. Register them on the app and let it dispatch os.Args:
app.Command("reports:send", "Email the weekly report", func(ctx context.Context, args *cmd.Args) error {
fs := flag.NewFlagSet("reports:send", flag.ContinueOnError)
dry := fs.Bool("dry-run", false, "print instead of sending")
if err := args.Parse(fs); err != nil {
return err
}
…
})
app.Execute() // ./app reports:send --dry-run
A command runs with the app booted, and the app is closed after it returns. The context is canceled on SIGINT or SIGTERM; a second signal ends the program.
Index ¶
Constants ¶
This section is empty.
Variables ¶
var ErrUsage = errors.New("usage error")
ErrUsage matches errors caused by how a command was invoked (errors.Is); the binary prints the command's usage and exits with status 2.
Functions ¶
Types ¶
type Args ¶
type Args struct {
// Name is the command's name.
Name string
// Args are the arguments after the name.
Args []string
// Stdout and Stderr are the command's output streams.
Stdout, Stderr io.Writer
}
Args is a command's invocation.
func (*Args) Parse ¶
Parse parses a.Args with fs. It returns an error matching ErrUsage for bad flags; the binary prints it with the command's usage. For -h after other arguments it prints the flags to Stderr and returns flag.ErrHelp (exit status 0). (-h as the first argument never reaches the command: the binary prints the command's usage.)
type Command ¶
type Command struct {
// Name is how the command is invoked: "migrate:rollback".
Name string
// Usage lists the arguments, for help: "[--step=N] [--force]".
Usage string
// Description is one line for the command list.
Description string
// Run does the work. Return an error matching [ErrUsage] (from
// [Args.Parse] or [Usagef]) for bad arguments (exit status 2); other
// errors exit with status 1.
Run func(ctx context.Context, args *Args) error
// ManagesApp says Run boots, runs and stops the app itself, as run and
// serve do. Other commands run between Boot and Close.
ManagesApp bool
// ChangesSchema says Run changes the database's structure (migrate,
// search:reindex): checks that the schema matches the settings,
// which would stop the app at boot, don't stop it.
ChangesSchema bool
}
Command is a named action of the application binary.
func Running ¶ added in v0.3.0
Running returns the command in ctx (WithCommand), if any: packages that check things when the app boots ask it, for commands that fix what they check.