Parsing CLI arguments with the args package

As we're going to write a WebSockets server, we might want to control it with some options passed from the command line, for example, a port number where the WebSockets server is listening or a command to stop the server when running in the background.

Let's create a new project with the Console Application template, add the args package to its dependencies, and start writing the WebSockets sever by defining its CLI options.

We'll create an instance of ArgParser and define possible options with the addOption() and addFlag()methods. Flags are options that can only have true/false values:

// bin/server.dart
import 'package:args/args.dart';
import 'dart:io';

main(List<String> args) async {
  ArgParser parser = new ArgParser();
  
  // This is probably self-explanatory.
  parser
    ..addOption('port', abbr: 'p', defaultsTo: '8888')
    ..addOption('pid-file', defaultsTo: 'var/websockets.pid',
        help: 'Path for a file with process ID')
    ..addOption('cmd', abbr: 'c', defaultsTo: 'start',
        allowed: ['start', 'stop'],)
    ..addFlag('help', abbr: 'h', negatable: false);
    
  var argResults = parser.parse(args);
  
  if (argResults['help']) {
    print(parser.usage);
  } else if (argResults['cmd'] == 'stop') {
    // Stop server by sending a SIGTERM signal.
  } else {
    // Start the WebSockets server.
  }
}

For example, an option definition with the following code allows us to use the CLI arguments --port 1234, --port=1234, -p 1234 or -p1234:

parser.addOption('port', abbr: 'p') 

As a flag, we have:

parser.addFlag('help', abbr: 'h', negatable: false);

In our case, -h or --help mean true and omitting the flag is false. This format of arguments is often called "GNUism".

The actual processing of CLI arguments happens in the ArgParser.parse() method, which returns a map-like object with parsed values. Note that we don't necessarily need to use arguments passed from the CLI and we can process a custom list of strings.

A big advantage of ArgParser is that it can automatically generate usage help for you in the ArgParser.usage property. If you run our app with the --help or -h argument, it dumps all possible options and flags with their defaults, descriptions, and allowed values:

$ dart bin/server.dart --help
-p, --port           (defaults to "8888")
    --pid-file       Path for a file with process ID
                     (defaults to "var/websockets.pid")

-c, --cmd            [start (default), stop]
-h, --help           

We don't need to worry about the -c option right now and start writing the WebSockets server first.

Apart from options and flags, the args package also supports creating commands similarly to git commit or apt-get install. However, args gets quite confusing with commands, so I would recommend that you try the unscripted package (https://pub.dartlang.org/packages/unscripted) instead, because it lets you map commands directly to class methods and make the configuration more readable.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.16.212.217