# Commands

Source: https://docs.anetos.dev/main/guides/commands/

Your application builds to one binary. Its first argument picks what it
does: run the app (the default), run only some process types, migrate the
database, list the routes, or run commands of your own.

## Before you start

The app calls `app.Execute()` at the end of `main`, as projects made by
`anetos new` do:

```go
// illustrative
func main() {
	app, err := anetos.New()
	if err != nil {
		log.Fatal(err)
	}
	// connect the database, add the server and routes, …
	app.Execute()
}
```

## Steps

### 1. Run the app

```sh
./blog                      # the default: run every component
./blog run --only=web      # only the components of these process types
./blog serve                # the same as run --only=web
./blog help                 # every command
./blog help migrate         # one command's arguments
```

`run` starts the components and stops them gracefully on Ctrl-C or
`SIGTERM`. Components without a process type run in every process (see
[the runtime supervisor](https://docs.anetos.dev/main/concepts/runtime-supervisor/index.md)).

### 2. Use the built-in commands

| Command | Added by |
|---|---|
| `run [--only=type,…]` | Every app |
| `serve`, `route:list` | `web.NewServer` |
| `openapi` | `openapi.Register` ([Describe an API with OpenAPI](https://docs.anetos.dev/main/guides/openapi/index.md)) |
| `types` | `typescript.Register` ([Generate TypeScript types for the frontend](https://docs.anetos.dev/main/guides/typescript/index.md)) |
| `migrate`, `migrate:rollback`, `migrate:reset`, `migrate:fresh`, `migrate:status`, `db:seed`, `search:reindex` | `migrate.New` ([Migrations](https://docs.anetos.dev/main/guides/migrations/index.md), [Search](https://docs.anetos.dev/main/guides/search/index.md)) |
| `cache:clear` | `cache.New` ([Cache](https://docs.anetos.dev/main/guides/cache/index.md)) |
| `ai:embed` | `ai.EmbeddingsFor` ([Search by meaning](https://docs.anetos.dev/main/guides/semantic-search/index.md)) |
| `queue:work`, `queue:failed`, `queue:retry`, `queue:forget`, `queue:flush`, `queue:clear` | `queue.New` ([Queues](https://docs.anetos.dev/main/guides/queues/index.md)) |
| `pubsub:publish` | `pubsub.New` ([Pub/sub listeners](https://docs.anetos.dev/main/guides/pubsub/index.md)) |
| `schedule:list`, `schedule:run`, `schedule:test`, `schedule:work` | `schedule.New` ([Scheduling](https://docs.anetos.dev/main/guides/scheduling/index.md)) |

A name may be shortened, each part between colons, while it stays
unique among the commands with as many parts: `./app r:l` is
`route:list`, `./app mi` is `migrate`, `./app m:s` is
`migrate:status`. An ambiguous one lists what it could be and exits
with status 2. In scripts and deploy files, write the whole name: a
command added later can make a short one ambiguous, or change what it
runs.

### 3. Add your own

```go
app.Command("blog:stats", "Print how many authors and posts there are", func(ctx context.Context, args *cmd.Args) error {
	authors, err := db.Query[Author](ctx).Count()
	if err != nil {
		return err
	}
	posts, err := db.Query[Post](ctx).Count()
	if err != nil {
		return err
	}
	fmt.Fprintf(args.Stdout, "%d authors, %d posts\n", authors, posts)
	return nil
})
```

(Copied from [`examples/database`](https://github.com/anetos-dev/anetos/blob/main/examples/database/main.go), region `custom-command`.)

A command runs with the app booted: its context carries what the app
provides (the database here), and the app is closed afterwards, so
shutdown hooks run. The context is canceled on Ctrl-C.

For flags, parse `args.Args` with a `flag.FlagSet` through `args.Parse`,
which reports bad flags as usage errors (the binary prints them with the
command's usage and exits with status 2):

```go
// illustrative
app.Command("reports:send", "Email the weekly report", func(ctx context.Context, args *cmd.Args) error {
	fs := flag.NewFlagSet("reports:send", flag.ContinueOnError)
	dryRun := fs.Bool("dry-run", false, "print the report instead of sending it")
	if err := args.Parse(fs); err != nil {
		return err
	}
	if fs.NArg() > 0 {
		return cmd.Usagef("unexpected argument %q", fs.Arg(0))
	}
	return reports.Send(ctx, *dryRun)
})
```

`app.AddCommand(cmd.Command{…})` takes a `Usage` line for help (list the
flags there) and returns an error instead of panicking. `-h` or `--help`
right after the command's name never reaches it: the binary prints its
usage and description. Later in the arguments, `args.Parse` handles it
and prints the flags.

## How it works

`app.Execute()` reads `os.Args`: no arguments (or only flags) means
`run`; `help`, `-h` and `--help` list the commands. It exits with status
0 on success, 1 when the command fails (also when a signal interrupts it
before it finishes), and 2 for usage errors (an unknown command, a bad
flag, a `cmd.Usagef` error). `run` and `serve` exit with 0 when a signal
stops the app, since that is how they end. A second Ctrl-C ends the
program at once. Commands that manage the app themselves (`run`,
`serve`: `ManagesApp` in `cmd.Command`) boot, run and stop it; the others
run between `app.Boot` and `app.Close`, which also runs if the command
panics. `help` doesn't boot the app, so it works without a database;
commands that boot it (`route:list` too) need the database reachable.

> **Coming from another framework?** This is the job of Django's
> `manage.py`, Laravel's `artisan` or Rails' `bin/rails`, built into your
> binary: `./blog migrate`, and custom commands are functions registered
> on the app instead of classes. Code generators (`make:*`) live in the
> `anetos` tool instead, since they write source.

## Testing it

`app.ExecuteArgs(ctx, args, stdout, stderr)` runs a command without
exiting and returns the exit status, as
[`examples/database`](https://github.com/anetos-dev/anetos/blob/main/examples/database/main_test.go) does. An
app runs one command: create a new one per call.

## Common problems

| Symptom | Cause | Fix |
|---|---|---|
| `unknown command "migrate"` | `migrate.New` wasn't called before `Execute` | Call it while setting up the app |
| `"m:r" could be migrate:reset, migrate:rollback` | A short name that fits several commands | Write more of it, or the whole name |
| `command "x" registered twice` | Two commands with one name (`app.Command` panics, `app.AddCommand`, `migrate.New` and `web.NewServer` return the error) | Register each once |
| `unknown process type "…"` | `--only` names a process type no background component has and no package declared (the error lists the known ones) | Check `help run` and the process types of your background components (`web`, `worker`, `scheduler`, `listener`) |
| `the process type workers was renamed worker in v0.5` | A deploy file, Procfile or cron line still names a process type's name before v0.5 (`http`, `workers`, `listeners`) | Use `web`, `worker` or `listener` |

## Next steps

- [`anetos` tool reference](https://docs.anetos.dev/main/reference/cli/index.md)
- [Migrations](https://docs.anetos.dev/main/guides/migrations/index.md)
