CLI applications

A command-line tool is the second Go Elemental application type, beside the web service. It follows the same import direction and composition root as a web service, with one difference that shapes the rest: a CLI runs one command per process, so its graph is built per command, and a command brings up only the dependencies it declares. A CLI builds on go-cli-sdk, whose cli package documentation states the dispatcher's API, and starts from go-cli-sdk-template, which scaffolds the layout below.

This page states the conventions particular to a CLI, and links the rest where it is stated: The composition root states why a CLI's configuration is a node of its graph, Domain package files how a domain package splits its API by dependency profile and lays out its commands, and Tests and documentation where the composition root's fixtures live.

The composition root's layer files

cmd/<name>/main.go derives go-core's signal context, passes it, cli.Streams over the process's standard streams, and the arguments to the composition root, and exits with the code the run returns. It loads nothing.

internal/app has one file per layer:

There is no config.go, no commands.go, and no initializer: each layer file fills its own part of the graph and mounts its own commands, so adding a command touches its layer file and its package, and nothing else. The composition root's fixtures live in an internal apptest package, as go-cli-sdk-template's Builds and Halt do.

A command builds only what it declares

Exit codes and command words

Scenarios are opt-in

A scenario is a narrated, guided tour of the tool's own commands, a different kind of thing from a command that does one operation and prints its result, and not every CLI has them. The template ships none.

A CLI that opts in keeps its scenarios in one root-level package named scenarios, and runs them on go-cli-sdk's scenario runner, never one of its own. Its scenario.go mounts scenario.Commands(scenarios...) at the root, and the root's Footer calls scenario.WriteListing with the same scenarios. <tool> scenario <name> runs one scenario, which declares its nodes like any other command and builds only those. <tool> scenario alone prints its help, and that help and the root's both end with the listing, so a CLI has no list command.

Keyboard shortcuts

Settings