• Stars
    star
    214
  • Rank 184,678 (Top 4 %)
  • Language
    Dart
  • License
    BSD 3-Clause "New...
  • Created almost 10 years ago
  • Updated 3 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

A command-line argument parsing library for Dart.

Dart CI pub package package publisher

Parses raw command-line arguments into a set of options and values.

This library supports GNU and POSIX style options, and it works in both server-side and client-side apps.

Defining options

First create an ArgParser:

var parser = ArgParser();

Then define a set of options on that parser using addOption() and addFlag(). Here's the minimal way to create an option named "name":

parser.addOption('name');

When an option can only be set or unset (as opposed to taking a string value), use a flag:

parser.addFlag('name');

Flag options, by default, accept a 'no-' prefix to negate the option. You can disable the 'no-' prefix using the negatable parameter:

parser.addFlag('name', negatable: false);

Note: From here on out, "option" refers to both regular options and flags. In cases where the distinction matters, we'll use "non-flag option."

Options can have an optional single-character abbreviation, specified with the abbr parameter:

parser.addOption('mode', abbr: 'm');
parser.addFlag('verbose', abbr: 'v');

Options can also have a default value, specified with the defaultsTo parameter. The default value is used when arguments don't specify the option.

parser.addOption('mode', defaultsTo: 'debug');
parser.addFlag('verbose', defaultsTo: false);

The default value for non-flag options can be any string. For flags, it must be a bool.

To validate a non-flag option, you can use the allowed parameter to provide an allowed set of values. When you do, the parser throws an ArgParserException if the value for an option is not in the allowed set. Here's an example of specifying allowed values:

parser.addOption('mode', allowed: ['debug', 'release']);

You can use the callback parameter to associate a function with an option. Later, when parsing occurs, the callback function is invoked with the value of the option:

parser.addOption('mode', callback: (mode) => print('Got mode $mode'));
parser.addFlag('verbose', callback: (verbose) {
  if (verbose) print('Verbose');
});

The callbacks for all options are called whenever a set of arguments is parsed. If an option isn't provided in the args, its callback is passed the default value, or null if no default value is set.

If an option is mandatory but not provided, the results object throws an [ArgumentError][ArgumentError] on retrieval.

parser.addOption('mode', mandatory: true);

Parsing arguments

Once you have an ArgParser set up with some options and flags, you use it by calling ArgParser.parse() with a set of arguments:

var results = parser.parse(['some', 'command', 'line', 'args']);

These arguments usually come from the arguments to main(). For example:

main(List<String> args) {
  // ...
  var results = parser.parse(args);
}

However, you can pass in any list of strings. The parse() method returns an instance of ArgResults, a map-like object that contains the values of the parsed options.

var parser = ArgParser();
parser.addOption('mode');
parser.addFlag('verbose', defaultsTo: true);
var results = parser.parse(['--mode', 'debug', 'something', 'else']);

print(results.option('mode')); // debug
print(results.flag('verbose')); // true

By default, the parse() method allows additional flags and options to be passed after positional parameters unless -- is used to indicate that all further parameters will be positional. The positional arguments go into ArgResults.rest.

print(results.rest); // ['something', 'else']

To stop parsing options as soon as a positional argument is found, allowTrailingOptions: false when creating the ArgParser.

Specifying options

To actually pass in options and flags on the command line, use GNU or POSIX style. Consider this option:

parser.addOption('name', abbr: 'n');

You can specify its value on the command line using any of the following:

--name=somevalue
--name somevalue
-nsomevalue
-n somevalue

Consider this flag:

parser.addFlag('name', abbr: 'n');

You can set it to true using one of the following:

--name
-n

You can set it to false using the following:

--no-name

Multiple flag abbreviations can be collapsed into a single argument. Say you define these flags:

parser
  ..addFlag('verbose', abbr: 'v')
  ..addFlag('french', abbr: 'f')
  ..addFlag('iambic-pentameter', abbr: 'i');

You can set all three flags at once:

-vfi

By default, an option has only a single value, with later option values overriding earlier ones; for example:

var parser = ArgParser();
parser.addOption('mode');
var results = parser.parse(['--mode', 'on', '--mode', 'off']);
print(results.option('mode')); // prints 'off'

Multiple values can be parsed with addMultiOption(). With this method, an option can occur multiple times, and the parse() method returns a list of values:

var parser = ArgParser();
parser.addMultiOption('mode');
var results = parser.parse(['--mode', 'on', '--mode', 'off']);
print(results.multiOption('mode')); // prints '[on, off]'

By default, values for a multi-valued option may also be separated with commas:

var parser = ArgParser();
parser.addMultiOption('mode');
var results = parser.parse(['--mode', 'on,off']);
print(results.multiOption('mode')); // prints '[on, off]'

This can be disabled by passing splitCommas: false.

Defining commands

In addition to options, you can also define commands. A command is a named argument that has its own set of options. For example, consider this shell command:

$ git commit -a

The executable is git, the command is commit, and the -a option is an option passed to the command. You can add a command using the addCommand method:

var parser = ArgParser();
var command = parser.addCommand('commit');

It returns another ArgParser, which you can then use to define options specific to that command. If you already have an ArgParser for the command's options, you can pass it in:

var parser = ArgParser();
var command = ArgParser();
parser.addCommand('commit', command);

The ArgParser for a command can then define options or flags:

command.addFlag('all', abbr: 'a');

You can add multiple commands to the same parser so that a user can select one from a range of possible commands. When parsing an argument list, you can then determine which command was entered and what options were provided for it.

var results = parser.parse(['commit', '-a']);
print(results.command.name);   // "commit"
print(results.command['all']); // true

Options for a command must appear after the command in the argument list. For example, given the above parser, "git -a commit" is not valid. The parser tries to find the right-most command that accepts an option. For example:

var parser = ArgParser();
parser.addFlag('all', abbr: 'a');
var command = parser.addCommand('commit');
command.addFlag('all', abbr: 'a');

var results = parser.parse(['commit', '-a']);
print(results.command['all']); // true

Here, both the top-level parser and the "commit" command can accept a "-a" (which is probably a bad command line interface, admittedly). In that case, when "-a" appears after "commit", it is applied to that command. If it appears to the left of "commit", it is given to the top-level parser.

Dispatching Commands

If you're writing a command-based application, you can use the CommandRunner and Command classes to help structure it. CommandRunner has built-in support for dispatching to Commands based on command-line arguments, as well as handling --help flags and invalid arguments.

When using the CommandRunner it replaces the ArgParser.

In the following example we build a dart application called dgit that takes commands commit and stash.

The CommandRunner takes an executableName which is used to generate the help message.

e.g. dgit commit -a

File dgit.dart

void main(List<String> args) {
  var runner = CommandRunner("dgit", "A dart implementation of distributed version control.")
    ..addCommand(CommitCommand())
    ..addCommand(StashCommand())
    ..run(args);
}

When the above run(args) line executes it parses the command line args looking for one of the commands (commit or stash).

If the CommandRunner finds a matching command then the CommandRunner calls the overridden run() method on the matching command (e.g. CommitCommand().run).

Commands are defined by extending the Command class. For example:

class CommitCommand extends Command {
  // The [name] and [description] properties must be defined by every
  // subclass.
  final name = "commit";
  final description = "Record changes to the repository.";

  CommitCommand() {
    // we can add command specific arguments here.
    // [argParser] is automatically created by the parent class.
    argParser.addFlag('all', abbr: 'a');
  }

  // [run] may also return a Future.
  void run() {
    // [argResults] is set before [run()] is called and contains the flags/options
    // passed to this command.
    print(argResults.flag('all'));
  }
}

CommandRunner Arguments

The CommandRunner allows you to specify both global args as well as command specific arguments (and even sub-command specific arguments).

Global Arguments

Add argments directly to the CommandRunner to specify global arguments:

Adding global arguments

var runner = CommandRunner('dgit',  "A dart implementation of distributed version control.");
// add global flag
runner.argParser.addFlag('verbose', abbr: 'v', help: 'increase logging');

Command specific Arguments

Add arguments to each Command to specify Command specific arguments.

  CommitCommand() {
    // we can add command specific arguments here.
    // [argParser] is automatically created by the parent class.
    argParser.addFlag('all', abbr: 'a');
  }

SubCommands

Commands can also have subcommands, which are added with addSubcommand. A command with subcommands can't run its own code, so run doesn't need to be implemented. For example:

class StashCommand extends Command {
  final String name = "stash";
  final String description = "Stash changes in the working directory.";

  StashCommand() {
    addSubcommand(StashSaveCommand());
    addSubcommand(StashListCommand());
  }
}

Default Help Command

CommandRunner automatically adds a help command that displays usage information for commands, as well as support for the --help flag for all commands. If it encounters an error parsing the arguments or processing a command, it throws a UsageException; your main() method should catch these and print them appropriately. For example:

runner.run(arguments).catchError((error) {
  if (error is! UsageException) throw error;
  print(error);
  exit(64); // Exit code 64 indicates a usage error.
});

Displaying usage

You can automatically generate nice help text, suitable for use as the output of --help. To display good usage information, you should provide some help text when you create your options.

To define help text for an entire option, use the help: parameter:

parser.addOption('mode', help: 'The compiler configuration',
    allowed: ['debug', 'release']);
parser.addFlag('verbose', help: 'Show additional diagnostic info');

For non-flag options, you can also provide a help string for the parameter:

parser.addOption('out', help: 'The output path', valueHelp: 'path',
    allowed: ['debug', 'release']);

For non-flag options, you can also provide detailed help for each expected value by using the allowedHelp: parameter:

parser.addOption('arch', help: 'The architecture to compile for',
    allowedHelp: {
      'ia32': 'Intel x86',
      'arm': 'ARM Holding 32-bit chip'
    });

To display the help, use the usage getter:

print(parser.usage);

The resulting string looks something like this:

--mode            The compiler configuration
                  [debug, release]

--out=<path>      The output path
--[no-]verbose    Show additional diagnostic info
--arch            The architecture to compile for
      [arm]       ARM Holding 32-bit chip
      [ia32]      Intel x86

More Repositories

1

sdk

The Dart SDK, including the VM, JS and Wasm compilers, analysis, core libraries, and more.
Dart
10,110
star
2

language

Design of the Dart language
TeX
2,652
star
3

dart-pad

An online Dart editor with support for console, web, and Flutter apps
Dart
1,702
star
4

pub

The pub command line tool
Dart
1,040
star
5

http

A composable API for making HTTP requests in Dart.
Dart
1,021
star
6

site-www

Source for Dart website
Dart
944
star
7

shelf

Web server middleware for Dart
Dart
920
star
8

build

A build system for Dart written in Dart
Dart
785
star
9

pub-dev

The pub.dev website
Dart
785
star
10

dart_style

An opinionated formatter/linter for Dart code
Dart
645
star
11

dart-vim-plugin

Syntax highlighting for Dart in Vim
Vim Script
637
star
12

mockito

Mockito-inspired mock library for Dart
Dart
632
star
13

linter

Linter for Dart.
Dart
628
star
14

samples

A collection of Dart code samples by Dart DevRel
Dart
602
star
15

test

A library for writing unit tests in Dart.
Dart
492
star
16

source_gen

Automatic source code generation for Dart
Dart
484
star
17

dartdoc

API documentation tool for Dart.
Dart
473
star
18

markdown

A Dart markdown library
Dart
444
star
19

code_builder

A fluent API for generating valid Dart source code
Dart
428
star
20

web_socket_channel

StreamChannel wrappers for WebSockets.
Dart
418
star
21

leak_tracker

A framework for memory leak tracking for Dart and Flutter applications.
Dart
387
star
22

collection

The collection package for Dart contains a number of separate libraries with utility functions and classes that makes working with collections easier.
Dart
375
star
23

ffigen

FFI binding generator
Dart
364
star
24

logging

A Dart package for debug and error logging.
Dart
332
star
25

async

A Dart package that contains tools to work with asynchronous computations.
Dart
320
star
26

wasm

Utilities for loading and running WASM modules from Dart code
Dart
309
star
27

html

Dart port of html5lib. For parsing HTML/HTML5 with Dart. Works in the client and on the server.
Dart
276
star
28

crypto

A set of cryptographic functions implemented in pure Dart.
Dart
275
star
29

path

A string-based path manipulation library.
Dart
223
star
30

webdev

A CLI for Dart web development.
Dart
212
star
31

oauth2

An OAuth2 client library for Dart.
Dart
211
star
32

pana

Package ANAlysis for Dart
Dart
205
star
33

setup-dart

A GitHub Action to install and setup a Dart SDK.
Dart
188
star
34

yaml

A Dart YAML parser.
Dart
169
star
35

jnigen

Experimental bindings generator for Java bindings through dart:ffi and JNI.
Dart
154
star
36

homebrew-dart

Dart team's official tap for homebrew.
Ruby
153
star
37

native

Dart packages related to FFI and native assets bundling.
Dart
153
star
38

http2

A HTTP/2 implementation for dart.
Dart
153
star
39

sample-pop_pop_win

"Pop, Pop, Win!" is an implementation of Minesweeper in Dart.
Dart
149
star
40

usage

A Google Analytics wrapper for command-line, web, and Flutter apps.
Dart
143
star
41

watcher

A file system watcher library for Dart.
Dart
138
star
42

mime

Dart package for working with MIME type definitions and for processing streams of MIME multipart media types.
Dart
132
star
43

stack_trace

A package for manipulating stack traces and printing them readably.
Dart
128
star
44

web

Lightweight browser API bindings built around JS static interop.
Dart
128
star
45

gcloud

High-level interfaces to Google Cloud Platform APIs
Dart
126
star
46

platform

A generic platform abstraction for Dart
Dart
125
star
47

stream_transform

Dart utility methods to create StreamTransfomer instances to manipulate Streams
Dart
123
star
48

lints

Official Dart lint rules; the core and recommended set of lints suggested by the Dart team.
Dart
116
star
49

coverage

Dart coverage data manipulation and formatting
Dart
103
star
50

sse

Dart Server Sent Events package
Dart
96
star
51

csslib

A library for parsing CSS.
Dart
95
star
52

benchmark_harness

The official benchmark harness for Dart
Dart
94
star
53

appengine

Dart support for App Engine managed VMs
Dart
93
star
54

fake_async

Fake asynchronous events for deterministic testing.
Dart
90
star
55

convert

Conversion utilities
Dart
72
star
56

matcher

A declarative API for specifying expectations.
Dart
71
star
57

json_rpc_2

A Dart implementation of the JSON-RPC 2.0 spec.
Dart
71
star
58

characters

A package for characters represented as unicode extended grapheme clusters
Dart
69
star
59

dart-docker

Docker images for the Dart programming language (https://dart.dev)
Dart
68
star
60

pub_semver

A package for working with Pub/semver-style versions and version constraints
Dart
65
star
61

i18n

A general mono-repo for Dart i18n and l10n packages.
Dart
63
star
62

cli_util

A library to help in building Dart command-line apps
Dart
60
star
63

string_scanner

A class for parsing strings using a sequence of patterns.
Dart
60
star
64

glob

Bash-style filename globbing for Dart.
Dart
56
star
65

pubspec_parse

Simple package for parsing pubspec.yaml files with a type-safe API and rich error reporting
Dart
51
star
66

pool

A class for managing a finite pool of resources.
Dart
51
star
67

stream_channel

An abstraction for two-way communication channels.
Dart
50
star
68

io

Utilities for the Dart VM's dart:io.
Dart
49
star
69

macros

A Dart mono-repo for macro development.
Dart
48
star
70

fixnum

Fixed-width integer library for Dart.
Dart
45
star
71

clock

A fakeable wrapper for dart:core clock APIs.
Dart
41
star
72

ecosystem

This repository is home to general Dart Ecosystem tools and packages.
Dart
41
star
73

http_parser

A platform-independent Dart package for parsing and serializing HTTP formats.
Dart
39
star
74

site-shared

Content shared across Dart websites
JavaScript
38
star
75

co19

A Dart language and library conformance test suite
Dart
37
star
76

typed_data

Utility functions and classes that makes working with typed data lists easier in Dart
Dart
34
star
77

source_span

A library for identifying source spans and locations.
Dart
29
star
78

tools

This repository is home to tooling related Dart packages.
Dart
29
star
79

http_multi_server

A dart:io HttpServer wrapper that handles requests from multiple servers.
Dart
28
star
80

yaml_edit

A library for YAML manipulation with comment and whitespace preservation.
Dart
27
star
81

native_synchronization

Low-level synchronization primitives built using dart:ffi.
Dart
26
star
82

os_detect

Dart multi-platform operating system identification
Dart
24
star
83

dartbug.com

The redirect service for Dart issues and bugs.
Dart
23
star
84

bazel_worker

Dart integration for Bazel build system
Dart
23
star
85

boolean_selector

A flexible syntax for boolean expressions.
Dart
23
star
86

dart-syntax-highlight

Tools and documentation for how Dart code is formatted
Dart
22
star
87

api.dart.dev

Dart API docs
Python
19
star
88

grpc_cronet

Flutter dart:grpc implementation that uses the Cronet native library.
Dart
18
star
89

dart_ci

Tools used by Dart's continuous integration (CI) testing that aren't needed by Dart SDK contributors. Mirrored from dart.googlesource.com/dart_ci. Do not land pull requests on Github.
Dart
18
star
90

source_maps

A package to programmatically manipulate source maps.
Dart
16
star
91

term_glyph

Useful glyphs and Windows-safe equivalents
Dart
16
star
92

package_config

Support for working with Package Resolution Configuration files
Dart
16
star
93

test_process

A Dart package for testing subprocesses
Dart
16
star
94

browser_launcher

Provides a standardized way to launch web browsers.
Dart
16
star
95

timing

A Dart package for tracking time spent in child operations
Dart
14
star
96

root_certificates

The set of root certificates trusted by dart:io's default SecurityContext. Taken from Mozilla's NSS library.
C++
11
star
97

test_descriptor

Provides a convenient, easy-to-read API for defining and verifying directory structures in tests
Dart
10
star
98

dartlang_project_templates

Project templates for new repos under the dart-lang organization
Dart
8
star
99

source_map_stack_trace

Convert stack traces generated by dart2js-compiled code into readable native Dart stack traces
Dart
8
star
100

.github

GitHub default community health file for dart-lang repos
7
star