Guides/Build a CLI with commands

Build a CLI with commands

CliRunner and CliCommand in package:dart_tui/cli.dart replace CommandRunner and Command from args. This guide shows how to port an app, what the runner adds, how the help looks, which exit codes it uses, and how to test it.

build a cli with commands · dart_tui
Build a CLI with commands demo

The short version

CliRunner<T> extends args' CommandRunner<T>, and CliCommand<T> extends Command<T>. Rename the two classes and the app runs as before. You also get a Logger on every command, help in the layout of Cobra and gh, five global flags, and runAndExit, which prints errors and exits with a standard code. package:dart_tui/cli.dart also exports UsageException from args.

dart
import 'package:dart_tui/cli.dart';

Future<void> main(List<String> args) {
  final runner = CliRunner<int>('notes', 'Keep a short list of notes.',
      version: '1.0.0')
    ..addCommand(AddCommand());
  return runner.runAndExit(args);
}

The full app is example/cli_app/notes.dart. Run it with dart run example/cli_app/notes.dart --help.

Port an args app

Keep args in your pubspec.yaml. You still use ArgParser and ArgResults from it. dart_tui needs args: ^2.5.0, the lowest version with ArgResults.flag and ArgResults.option.

diff
-import 'package:args/command_runner.dart';
+import 'package:dart_tui/cli.dart';

-class BuildCommand extends Command<int> {
+class BuildCommand extends CliCommand<int> {
   // name, description, argParser and run() stay as they are.
 }

-final runner = CommandRunner<int>('tool', 'Builds and ships projects.');
+final runner = CliRunner<int>('tool', 'Builds and ships projects.');

The logger

The runner has a logger. Every CliCommand reads the same one as logger. Pass your own with CliRunner(..., logger: Logger(...)). See Migrating from mason_logger for its methods.

dart
class AddCommand extends CliCommand<int> {
  @override
  String get name => 'add';
  @override
  String get description => 'Add a note.';

  @override
  Future<int> run() async {
    final text = await logger.prompt('What should the note say?');
    final progress = logger.progress('Saving');
    // ... do the work ...
    progress.complete('Saved');
    logger.detail('Only shown with --verbose.');
    return 0;
  }
}
A CliCommand that is not added to a CliRunner throws a StateError when you read logger.

Group commands and add examples

category is the Command.category getter from args. Commands with the same category appear under one heading. The headings and the commands in each are sorted by name. Commands with no category come first, under Commands:. Hidden commands and aliases are not listed. examples is new in CliCommand: a list of command lines shown at the end of that command's help. usageFooter on the runner or on a command adds a last line.

dart
class DoneCommand extends CliCommand<int> {
  @override
  String get name => 'done';
  @override
  String get description => 'Mark a note as done.';
  @override
  String get category => 'Write';
  @override
  String get invocation => 'notes done <number>';
  @override
  List<String> get examples => ['notes done 2'];

  @override
  int run() => 0;
}

Global flags

The runner adds these flags to its own parser. They apply while run runs, and the runner restores the logger afterwards.

FlagWhat it does
-v, --verboseSets Level.verbose: detail lines show, and a stack trace shows on an unexpected error.
-q, --quietSets Level.quiet. Errors still show.
--[no-]color--no-color turns colour off. --color turns it on, even in a pipe, as FORCE_COLOR=1 does.
--plainThe logger's prompts ask plain line questions, as in plain mode.
--versionPrints <name> version <version> and exits. Only added when you pass version:.

The clash rule. The runner skips a global flag when its argParser, or the parser of any command (at any depth), already has an option with that name. For --color it also checks no-color. Your option wins. When the abbreviation -v or -q is taken, the flag is added without it. So a --verbose flag you define yourself keeps its meaning, and the runner does not set Level.verbose for it.

Help

notes --help, notes help <command> and a run with no command print help to stdout. The layout has the description, Usage:, commands grouped by category in aligned columns, flags with their defaults and allowed values, Examples:, and the footer. Flags of the runner show under Global flags: in a command's help.

text
Builds and ships projects.

Usage:
  tool <command> [arguments]

Commands:
  completion   Set up shell completion.
  status       Show what changed since the last deploy.

Project:
  build        Compile the project.
  deploy       Upload the latest build to the server.

Flags:
  -h, --help             Print this usage information.
  -c, --config=<value>   Read settings from this file. (default: tool.yaml)
  -v, --verbose          Show all log output, and stack traces on errors.
  -q, --quiet            Hide log output. Errors still show.
      --[no-]color       Force colour on, even in pipes, or off with --no-color.
      --plain            Ask prompts as plain lines, without the terminal UI.
      --version          Print the version and exit.

Run "tool help <command>" for more information about a command.

Docs: https://example.com/tool

Help wraps to the terminal width, or 80 columns when there is no terminal. Pass usageLineLength: to set it. Text wraps at word boundaries, and a flag's help continues under its own column.

Colour follows the logger. There is none in a pipe, with NO_COLOR set, with --no-color, or in plain mode. The text and line breaks are the same with or without colour, so you can diff the plain output.

Task lists

logger.tasks runs a list of tasks and shows them as a live list, like pnpm install or docker pull. Each Task has a title and a run function. run gets a TaskContext. Use task.title = ... to change the title, task.log(line) to show a line of output under the task, task.skip('reason') to end the task as skipped, and task.tasks([...]) to run nested steps. You can nest to any depth. Tasks show in the order you declare them, even when they run at the same time. concurrency is how many run at once. The default is 1. A Task with enabled: () => false is skipped, not run.

dart
await logger.tasks([
  Task(
    'Check',
    (task) => task.tasks(concurrency: 3, [
      Task('Resolve dependencies', (task) async {
        task.log('Resolving args 2.7.0');
        // ... do the work ...
      }),
      Task('Run tests', (task) async {
        task.log('+97: test/renderer_test.dart');
        if (failed) throw Exception('1 test failed');
      }),
      Task('Analyze', (task) async { /* ... */ }),
    ]),
  ),
  Task('Build', (task) => task.tasks([
    Task('Compile', (task) async {
      for (final target in ['linux-x64', 'macos-arm64']) {
        task.title = 'Compile $target';
        // ... do the work ...
      }
      task.title = 'Compile 2 targets';
    }),
  ])),
  Task('Publish', (task) => task.skip('dry run')),
]);

The full flow is example/cli_tasks.dart. Run it with dart run example/cli_tasks.dart, or add --fail to make a test fail. A task that finishes well collapses to one line. A task that fails stays open and shows its output. This is the last frame of a run, first when all tasks pass, then with --fail, and then the same run with the output piped, which is plain mode.

Terminal, all tasks pass
text
✓ Check (0.6s)
✓ Build (1.4s)
↓ Publish skipped: dry run
✓ 8 tasks, 1 skipped (2.0s)
Plain (pipe, CI, ACCESSIBLE=1, --plain), shortened
text
Check > Run tests | +97: test/renderer_test.dart
✓ Check > Analyze (0.3s)
✓ Check > Run tests (0.5s)
✓ Check (0.6s)
Build > Archive | Wrote release.tar.gz (8.2 MB)
✓ Build > Archive (0.6s)
✓ Build (1.4s)
- Publish skipped: dry run
✓ 8 tasks, 1 skipped (2.0s)
Terminal, a test fails
text
✗ Check (0.6s)
  ✓ Resolve dependencies (0.6s)
  ✗ Run tests (0.6s)
    +12: test/cli_logger_test.dart
    +48: test/cli_runner_test.dart
    -1: test/cli_tasks_test.dart: summary line
    +97: test/renderer_test.dart
    Exception: 1 test failed
  ✓ Analyze (0.2s)
↓ Build skipped
↓ Publish skipped
✗ 1 of 6 failed (0.6s)
Plain (pipe, CI, ACCESSIBLE=1, --plain), shortened
text
Check > Run tests | -1: test/cli_tasks_test.dart: summary line
✓ Check > Resolve dependencies (0.6s)
✗ Check > Run tests: Exception: 1 test failed
✗ Check
- Build skipped
- Publish skipped
✗ 1 of 6 failed (0.6s)

While the tasks run, the live list looks like this. ⠧ is a spinner, and · is a task that has not started.

text
⠧ Check
  ⠧ Resolve dependencies
    › Got dependencies
  ⠧ Run tests
    › +97: test/renderer_test.dart
  ✓ Analyze (0.2s)
· Build
· Publish
dart_tui
example/cli_tasks.dart
example/cli_tasks.dart

Failures. With exitOnError: true, the default, a failure starts no new tasks. The tasks that did not start show as skipped. The tasks that run now finish, the list draws its last frame, and logger.tasks throws TasksFailed. It lists every failure. A nested one reads Parent > Child. CliRunner.runAndExit turns TasksFailed into exit code 70 with one line. With exitOnError: false, every task runs, and logger.tasks returns when all are done. It does not throw. The failures show in the last frame.

Plain mode. In a pipe, in CI, with ACCESSIBLE=1 and with --plain, there are no escape codes. The logger writes one line for each task that ends: ✓ Build (1.2s), ✗ Test: <error> or - Lint skipped: <reason>. A line from task.log starts with the task title and | .

Log levels. With --quiet, or any level above info, only failures and the summary show, on stderr. With --verbose, every line from task.log is also printed above the list.

Limits. The live list is never taller than the terminal height minus 1. Tasks that are done fold into one line, … n done. Each line is cut to the terminal width minus 1. The list does not read stdin, does not set raw mode, does not install signal handlers and does not hide the cursor. When you press Ctrl+C, the last frame stays on screen. A logger.progress started inside a task writes a plain start line and an end line above the list. Calling logger.tasks while another list runs on the same logger throws a StateError.

Run and exit codes

run(args) works as in args: it returns the command's result, and errors reach you as exceptions. runAndExit(args) is for main. It runs, prints errors, flushes the logger and exits.

OutcomeExit codeOutput
The command returns an intThat int
The command returns anything else0
UsageException (unknown command, bad option, usageException(...) in a command)64A one-line Error: ... on stderr, then "Did you mean" names when there are any, then the usage of the command.
Any other error70A one-line Error: ... on stderr. The stack trace shows only with --verbose.
text
$ notes lsit
Error: Could not find a command named "lsit".

Did you mean this?
  list

Usage:
  notes <command> [arguments]
  ...

Test your CLI

Build the runner with a Logger that writes to CaptureSink objects from package:dart_tui/testing.dart. Pass exit: to catch the exit code, and usageLineLength: to fix the width. Compare help with a golden file using expectScreen. The testing guide covers the tester.

dart
import 'package:dart_tui/cli.dart';
import 'package:dart_tui/testing.dart';
import 'package:test/test.dart';

// NotesRunner is the runner from example/cli_app/notes.dart.
final class Exit implements Exception {
  Exit(this.code);
  final int code;
}

void main() {
  late CaptureSink out, err;
  late NotesRunner app;

  setUp(() {
    out = CaptureSink();
    err = CaptureSink();
    app = NotesRunner(
      logger: Logger(
        stdout: out,
        stderr: err,
        environment: const {'ACCESSIBLE': '1'},
        exit: (code) => throw Exit(code),
      ),
      usageLineLength: 80,
    );
  });

  test('help matches the golden file', () {
    expectScreen(app.usage, 'test/goldens/help.txt');
  });

  test('a typo exits with 64', () async {
    await expectLater(
      app.runAndExit(['lsit']),
      throwsA(isA<Exit>().having((e) => e.code, 'code', 64)),
    );
    expect(err.text, contains('Did you mean this?\n  list'));
  });
}

Shell completions

A runner with at least one command of its own adds a completion command. It supports bash, zsh and fish. Tab completes commands, flags, and the allowed values of options. Your commands can add values only the app knows, such as note numbers.

notes completion [bash|zsh|fish] prints the script. notes completion install [shell] and notes completion uninstall [shell] add and remove it. With no shell named, the command uses $SHELL. -y, --yes skips the question in the zsh install.

ShellLoad it yourselfOr run `notes completion install`
bashAdd eval "$(notes completion bash)" to ~/.bashrc. It also works on the bash 3.2 of macOS, where source <(...) does not.Writes ${XDG_DATA_HOME:-~/.local/share}/bash-completion/completions/notes. The bash-completion package (version 2) loads it on demand. On macOS: brew install bash-completion@2. No rc file changes.
zshAdd source <(notes completion zsh) to ~/.zshrc, after compinit.Writes _notes to ${XDG_DATA_HOME:-~/.local/share}/notes/zsh/, then adds one block to ${ZDOTDIR:-~}/.zshrc. Then run exec zsh.
fishRun notes completion fish | source.Writes ${XDG_CONFIG_HOME:-~/.config}/fish/completions/notes.fish. Open a new shell.

Only the zsh install edits an rc file. The block sits between # >>> notes completion >>> and # <<< notes completion <<<. It puts the directory on fpath and calls compdef, or runs compinit when it has not run. Before the edit, the command prints the lines and asks. --yes skips the question. In plain mode (a pipe, CI, ACCESSIBLE=1 or --plain), it never edits the file. It prints the lines for you to add. Install twice changes nothing. Uninstall removes what install added: the script, the zsh directory when it is empty, and the rc block. Your .zshrc is then byte for byte what it was.

What Tab completes

- Commands and aliases, with their descriptions. Hidden commands are left out. - Flags for the command the typed words reach, and the global flags: --name, -a, and --no-name for negatable flags. - Values from allowed, after --opt= and after --opt . allowedHelp gives the descriptions. - help <command>. - The shell's file completion, for an option with no allowed values and no values from the hook. zsh and fish show descriptions. bash shows only the values.

Complete your own values

Override completeValue in a CliCommand. option is the option name, or empty for a positional argument. partial is the text typed so far. An entry can add a description after a tab. The runner keeps only entries that start with partial. Return nothing to get file completion. This is the hook of notes done:

dart
/// Tab after "notes done" lists the open notes: "2\tCall Sam".
@override
Iterable<String> completeValue(String option, String partial) => [
      if (option.isEmpty)
        for (final (i, note) in load().indexed)
          if (note['done'] != true) '${i + 1}\t${note['text']}',
    ];
The hook runs on every Tab. Keep it fast. Never prompt, read stdin or print. Completion skips the normal parse, so argResults and globalResults are null in the hook. The notes app reads the default ~/.notes.json. It does not see a -f on the line.

How it works

The script runs notes __complete <words...> on each Tab. The command prints one value<TAB>description line per candidate, then :<directive>. :4 means no file completion. :0 means the shell's default files. This is the protocol of Cobra. The script does not change when your commands change, so it never goes stale. On any error, the command prints nothing and exits with 0.

The script calls the executable name (executableName of the runner) from PATH. So dart run bin/notes.dart gets no completions. Compile the app with dart compile exe bin/notes.dart -o ~/.local/bin/notes. Or run dart pub global activate with an executables: entry in pubspec.yaml. That puts notes in ~/.pub-cache/bin.

To turn it off, pass CliRunner(..., completions: false). A command of yours named completion or __complete wins, as with the global flags. A runner with no commands of its own adds neither.

When Tab does nothing

- Run command -v notes. The shell must find the executable. - Run notes __complete ''. It must print lines that end with :4. - zsh: compinit must run before source <(...). Add autoload -Uz compinit && compinit. After an install, run exec zsh. Delete ~/.zcompdump if an old one is cached. - bash: complete -p notes shows whether the script is loaded. Without the bash-completion package, use the eval line.

Limits

- Styled help is only for CliCommand. A plain args Command added to a CliRunner still prints args' own help. - --plain and --color apply to the runner's Logger and its prompts. They do not change promptSelect and the other one-shot helpers when you call them directly. - Text added with ArgParser.addSeparator is not shown, because args does not expose it. - Completions do not support PowerShell yet. It comes with Windows support. - bash shows no descriptions. - A value glued to a short option (-phigh) is not completed. - The hook does not see the earlier words.

Related