Command Line Subcommands in Dart

Here’s the translation of the Go code to Dart, formatted in Markdown suitable for Hugo:

Our first program demonstrates how to use command-line subcommands with their own set of flags. Here’s the full source code:

import 'package:args/args.dart';

void main(List<String> arguments) {
  // We declare subcommands using ArgParser
  var parser = ArgParser();

  // Define the 'foo' subcommand
  var fooCommand = ArgParser()
    ..addFlag('enable', abbr: 'e', defaultsTo: false, help: 'enable')
    ..addOption('name', abbr: 'n', help: 'name');

  // Define the 'bar' subcommand
  var barCommand = ArgParser()
    ..addOption('level', abbr: 'l', help: 'level', valueHelp: 'integer');

  // Add subcommands to the main parser
  parser.addCommand('foo', fooCommand);
  parser.addCommand('bar', barCommand);

  // The subcommand is expected as the first argument to the program
  if (arguments.isEmpty) {
    print("expected 'foo' or 'bar' subcommands");
    return;
  }

  // Check which subcommand is invoked
  var command = parser.parse(arguments).command;

  if (command != null) {
    switch (command.name) {
      // For every subcommand, we parse its own flags and
      // have access to remaining arguments
      case 'foo':
        var results = command.parse(arguments.skip(1));
        print("subcommand 'foo'");
        print("  enable: ${results['enable']}");
        print("  name: ${results['name']}");
        print("  rest: ${results.rest}");
        break;
      case 'bar':
        var results = command.parse(arguments.skip(1));
        print("subcommand 'bar'");
        print("  level: ${results['level']}");
        print("  rest: ${results.rest}");
        break;
      default:
        print("expected 'foo' or 'bar' subcommands");
    }
  } else {
    print("expected 'foo' or 'bar' subcommands");
  }
}

To run the program, save it as command_line_subcommands.dart and use dart run.

First, invoke the foo subcommand:

$ dart run command_line_subcommands.dart foo --enable --name=joe a1 a2
subcommand 'foo'
  enable: true
  name: joe
  rest: [a1, a2]

Now try bar:

$ dart run command_line_subcommands.dart bar --level 8 a1
subcommand 'bar'
  level: 8
  rest: [a1]

But bar won’t accept foo’s flags:

$ dart run command_line_subcommands.dart bar --enable a1
Could not find an option named "enable".

Usage: command_line_subcommands.dart bar [options]
-h, --help    Print this usage information.
-l, --level   level

Run "command_line_subcommands.dart help" to see global options.

This example demonstrates how to use the args package in Dart to create a command-line application with subcommands. Each subcommand can have its own set of flags and options. The program parses the arguments and executes the appropriate subcommand based on the input.

Next, we’ll look at environment variables, another common way to parameterize programs.