runAndExit method
Runs args like run, then sets io.exitCode, flushes logger and
its output, and exits.
Exit codes: the command's result when it is an int, else 0; 64 for a
UsageException, with a one-line error, "did you mean" suggestions and
the command's usage on stderr; 70 for any other exception, with a
one-line error (and the stack trace with --verbose) on stderr.
Implementation
Future<Never> runAndExit(Iterable<String> args) async {
if (_completing(args)) {
await _printCompletions(args.skip(1).toList());
try {
await logger._out.flush();
} catch (_) {}
logger._exit(0);
}
int finish(int code) {
io.exitCode = code;
logger.flush();
return code;
}
int report(Object error, StackTrace stack) => finish(_report(error, stack));
int code;
try {
code = await _scoped(args, (results) async {
try {
final result = await runCommand(results);
return finish(result is int ? result : 0);
} catch (error, stack) {
// Inside the scope, so --no-color and --verbose apply.
return report(error, stack);
}
});
} catch (error, stack) {
code = report(error, stack);
}
for (final sink in [logger._out, logger._err]) {
try {
await sink.flush();
} catch (_) {}
}
logger._exit(code);
}