npx skills add ...
npx skills add dart-lang/skills --skill dart-build-cli-app
Architectural patterns, entrypoint structure, exit codes, stream routing, and subprocess spawning for Dart command-line interface (CLI) applications. Use when building CLI tools, console utilities, scripts, argument parsing with `package:args` (ArgParser or CommandRunner), handling exit codes, configuring executables in pubspec.yaml, spawning Dart subprocesses, or compiling native CLI binaries. Don't use for Flutter UI widgets, web applications, or standalone HTTP backend servers.
npx skills add dart-lang/skills --skill dart-build-cli-app
exit(N))Calling dart:io's exit(int code) invokes Platform::Exit(code) in the C++ runtime. It immediately terminates the OS process without unwinding the Dart stack:
--pause-isolates-on-exit, the VM Service pauses isolates before shutdown to allow IDE inspection. exit() terminates the OS process before the VM Service can pause or inspect state.package:coverage queries execution lines over VM Service RPCs during the paused-on-exit state. exit() destroys the process before RPC extraction, yielding 0% coverage.stdout and stderr are buffered asynchronous IOSink streams. exit() drops unflushed bytes.finally blocks (closing locks, deleting temp directories) are bypassed.Rule: Avoid calling exit(code) directly during normal execution; set exitCode = code or return an integer exit code from CommandRunner<int> (from package:args) and allow the asynchronous main() function to return naturally. Do not call exit() on unhandled errors; throw an unhandled Error or exception so the runtime unwinds cleanly and exits with a non-zero status.
Standard POSIX exit codes (/usr/include/sysexits.h):
0: Success (EX_OK / ExitCode.success.code)64: Command-line usage error (EX_USAGE / ExitCode.usage.code)65: Data format error (EX_DATAERR / ExitCode.data.code)70: Internal software crash (EX_SOFTWARE / ExitCode.software.code)78: Configuration error (EX_CONFIG / ExitCode.config.code)Note: Prefer importing package:io/io.dart and using ExitCode constants
(e.g., ExitCode.usage.code, ExitCode.software.code) rather than magic
integer literals. For minimal standalone scripts without package dependencies,
standard POSIX integer literals (0, 64, 70) may be used.
bin/ vs. lib/src/)Keep bin/*.dart files strictly as minimal entrypoint trampolines (instantiate runner, pass args, await exit code). Place all command definitions, argument parsers, formatters, and business logic inside lib/src/.
bin/ cannot be cleanly imported via package: URIs. Moving logic into lib/src/ allows the entire command runner, subcommand hierarchy, and business logic to be unit-tested in-memory in milliseconds (< 2ms) without spawning OS subprocesses.stdout. Write warnings, error messages, and debug logs exclusively to stderr.FormatException, UsageException, or ArgumentError thrown when
accessing a missing mandatory: true option via results.option(...)), both
the error message and the usage text must write to stderr, and exit code
64 (EX_USAGE / ExitCode.usage.code) must be returned. stdout should
ONLY receive usage help when the user explicitly requests it via --help or
-h.print() in Error Handlers: print() routes to stdout. Use stderr.writeln() for all failure notifications. For standard output, prefer stdout.writeln() over print() to comply with the avoid_print lint rule (unless analysis_options.yaml explicitly configures avoid_print: false).NO_COLOR: Verify stdout.hasTerminal, stdout.supportsAnsiEscapes, and !Platform.environment.containsKey('NO_COLOR') before emitting ANSI color or cursor escape codes:
--json or --machine flags are passed, format data as JSON to stdout and route logs to stderr.executables:)Scaffold new command-line projects using dart create -t console <package_name>, which initializes the standard bin/ and lib/ layout. Always declare executables in pubspec.yaml under executables: to map command names to scripts in bin/, enabling clean invocation via dart run <command> (without specifying bin/...dart) and configuring global binary symlinks for dart install:
package:build_version)Avoid hardcoding --version strings in bin/*.dart or manually synchronizing constant files. Use package:build_version to generate lib/src/version.dart containing const packageVersion = 'x.y.z'; directly from pubspec.yaml during builds.
Store transient cache files in .dart_tool/<package_name>/. Never write persistent cache files directly to the project root.
Import package:args to manage command-line arguments:
ArgParser directly with addFlag() and addOption().CommandRunner<int> and extend Command<int> for each subcommand, returning POSIX exit codes directly.results.flag('name'), results.option('name'), and results.multiOption('name') (available in package:args 2.5+) instead of map indexing operator [] to eliminate manual type casts (as bool, as String?).package:build_cli to generate strongly-typed options classes. Leverage named default overrides (e.g. {String? hostDefaultOverride}) to cleanly merge configuration files with CLI flags.Chain.capture(): The Dart VM natively preserves asynchronous stack frames across await suspension points. Chain.capture wraps the event loop in custom Zones, incurring substantial allocation overhead and trapping errors across Zone boundaries.Trace.from(st).terse: Use static utilities from package:stack_trace on uncaught errors without capturing zones:When spawning Dart SDK subprocesses or executing other Dart tools (e.g., dart format, dart test, build_runner):
Platform.resolvedExecutable or Platform.executable points to the dart command-line executable: In standalone AOT-compiled binaries (dart install / dart compile exe), resolvedExecutable points to the compiled application binary itself, causing recursive self-invocation loops or flag rejection crashes.package:cli_util: Resolve the Dart SDK executable using cli_util.dartExecutable or cli_util.sdkPath instead of writing custom PATH or directory scrapers.If your CLI alters terminal modes, displays spinners, or opens listening sockets:
ProcessSignal.sigterm.watch() throws UnsupportedError. Guard sigterm with if (!Platform.isWindows).stdin.echoMode = false or stdin.lineMode = false, check if (!stdin.hasTerminal) return; first, and install a SIGINT listener and finally block to restore them so user keystrokes remain visible after exit.\x1B[?25l), always restore cursor visibility (\x1B[?25h) on exit or cancellation.HttpServer or ServerSocket instances (server.close(force: true)) on termination signals to immediately release OS ports.Structure testing across two distinct layers:
< 5ms): Test command classes, option parsing, and business logic directly by importing package:<pkg>/src/... in test/.package:test_process and package:test_descriptor to verify end-to-end binary execution, process I/O streaming, and OS exit codes:Dart 3.12+ standardizes CLI distribution around dart run and dart install (moving away from dart pub global activate):
dart run <package>@<version> [args] downloads and runs the CLI on demand.dart install <package> compiles the package entrypoint to a fast native standalone binary in ~/.dart/install/bin/.dart run <command> (resolves via executables: in pubspec.yaml) or dart run bin/cli.dart.dart build cli. Outputs bundle to build/cli/_/bundle/.dart compile exe bin/cli.dart -o <output_path>.pubspec.yaml under executables:.bin/*.dart as a thin entrypoint; place command logic in lib/src/.exitCode = N; avoid raw exit(N).stderr.results.flag(), results.option(), and results.multiOption() for type safety.useAnsi (checking stdout.hasTerminal, supportsAnsiEscapes, and NO_COLOR) before emitting ANSI codes.cli_util.dartExecutable, never Platform.resolvedExecutable.test_process.// bin/my_cli.dart — Thin entrypoint trampoline
import 'dart:io';
import 'package:my_cli/src/cli.dart';
Future<void> main(List<String> args) async {
exitCode = await runCli(args);
}