runCliAdapter function

Future<int> runCliAdapter(
  1. ArgParser parser,
  2. List<String> args,
  3. Future<int> execute(
    1. ArgResults
    )
)

Runs a CLI adapter end-to-end:

  1. If args contains --help or -h, write parser.usage to stdout and return 0.
  2. Otherwise parse the args, writing ERROR: <message> to stderr and returning 1 on FormatException (which ArgParserException extends).
  3. On successful parse, invoke execute with the resulting ArgResults.

Centralises all --help interception and parser-error formatting so CLI adapter files don't repeat this boilerplate.

Implementation

Future<int> runCliAdapter(
  ArgParser parser,
  List<String> args,
  Future<int> Function(ArgResults) execute,
) async {
  if (args.contains('--help') || args.contains('-h')) {
    final usage = parser.usage;
    stdout.writeln(usage.isEmpty ? 'No options for this command.' : usage);
    return 0;
  }
  final ArgResults results;
  try {
    results = parser.parse(args);
  } on FormatException catch (e) {
    stderr.writeln('ERROR: ${e.message}');
    return 1;
  }
  return execute(results);
}