args
v2.7.0Library for defining parsers for parsing raw command-line arguments into a set of options and values using GNU and POSIX style options.
Package archive: https://pubdev.letsnova.ru/api/archives/args/2.7.0.tar.gz
dart pub add argsReadme
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
Changelog
2.7.0
- Remove sorting of the
allowedHelpargument in usage output. Ordering will depend on key order for the passedMap. - Fix the repository URL in
pubspec.yaml. - Added option
hideNegatedUsagetoArgParser.flag()allowing a flag to benegatablewithout showing it in the usage text. - Fixed #101, adding check for mandatory when using
.option().
2.6.0
- Added source argument when throwing a
ArgParserException. - Fix inconsistent
FormatExceptionmessages - Require Dart 3.3
- Move to
dart-lang/coremonorepo.
2.5.0
- Introduce new typed
ArgResultsflag(String),option(String), andmultiOption(String)methods. - Require Dart 3.0.
2.4.2
- Change the validation of
mandatoryoptions; they now perform validation when the value is retrieved (from theArgResultsobject), instead of when the args are parsed. - Require Dart 2.19.
2.4.1
- Add a
CONTRIBUTING.mdfile; move the publishing automation docs from the readme into the contributing doc. - Added package topics to the pubspec file.
2.4.0
- Command suggestions will now also suggest based on aliases of a command.
- Introduce getter
Command.suggestionAliasesfor names that cannot be used as aliases, but will trigger suggestions.
2.3.2
- Require Dart 2.18
2.3.1
- Switch to using package:lints.
- Address an issue with the readme API documentation (#211).
- Populate the pubspec
repositoryfield.
2.3.0
- Add the ability to group commands by category in usage text.
2.2.0
- Suggest similar commands if an unknown command is encountered, when using the
CommandRunner.- The max edit distance for suggestions defaults to 2, but can be configured
using the
suggestionDistanceLimitparameter on the constructor. You can set it to0to disable the feature.
- The max edit distance for suggestions defaults to 2, but can be configured
using the
2.1.1
- Fix a bug with
mandatoryoptions which caused a null assertion failure when used within a command.
2.1.0
- Add a
mandatoryargument to require the presence of an option. - Add
aliasesnamed argument toaddFlag,addOption, andaddMultiOption, as well as a publicfindByNameOrAliasmethod onArgParser. This allows you to provide aliases for an argument name, which eases the transition from one argument name to another.
2.0.0
- Stable null safety release.
2.0.0-nullsafety.0
-
Migrate to null safety.
-
BREAKING Remove APIs that had been marked as deprecated:
- Instead of the
allowMultiandsplitCommasarguments toArgParser.addOption(), useArgParser.addMultiOption(). - Instead of
ArgParser.getUsage(), useArgParser.usage. - Instead of
Option.abbreviation, useOption.abbr. - Instead of
Option.defaultValue, useOption.defaultsTo. - Instead of
OptionType.FLAG/SINGLE/MULTIPLE, useOptionType.flag/single/multiple.
- Instead of the
-
Add a more specific function type to the
callbackargument ofaddOption.
1.6.0
- Remove
helpfrom the list of commands in usage. - Remove the blank lines in usage which separated the help for options that happened to span multiple lines.
1.5.4
- Fix a bug with option names containing underscores.
- Point towards
CommandRunnerin the docs forArgParser.addCommandsince it is what most authors will want to use instead.
1.5.3
- Improve arg parsing performance: use queues instead of lists internally to get linear instead of quadratic performance, which is important for large numbers of args (>1000). And, use simple string manipulation instead of regular expressions for a 1.5x improvement everywhere.
- No longer automatically add a 'help' option to commands that don't validate their arguments (fix #123).
1.5.2
- Added support for
usageLineLengthinCommandRunner
1.5.1
- Added more comprehensive word wrapping when
usageLineLengthis set.
1.5.0
- Add
usageLineLengthto control word wrapping usage text.
1.4.4
- Set max SDK version to
<3.0.0, and adjust other dependencies.
1.4.3
- Display the default values for options with
allowedHelpspecified.
1.4.2
- Narrow the SDK constraint to only allow SDK versions that support
FutureOr.
1.4.1
- Fix the way default values for multi-valued options are printed in argument usage.
1.4.0
-
Deprecated
OptionType.FLAG,OptionType.SINGLE, andOptionType.MULTIPLEin favor ofOptionType.flag,OptionType.single, andOptionType.multiplewhich follow the style guide. -
Deprecated
Option.abbreviationandOption.defaultValuein favor ofOption.abbrandOption.defaultsTo. This makes all ofOption's fields match the corresponding parameters toArgParser.addOption(). -
Deprecated the
allowMultipleandsplitCommasarguments toArgParser.addOption()in favor of a separateArgParser.addMultiOption()method. This allows us to provide more accurate type information, and to avoid adding flags that only make sense for multi-options in places where they might be usable for single-value options.
1.3.0
- Type
Command.run()'s return value asFutureOr<T>.
1.2.0
- Type the
callbackparameter toArgParser.addOption()asFunctionrather thanvoid Function(value). This allows strong-mode users to writecallback: (String value) { ... }rather than having to manually castvalueto aString(or aList<String>withallowMultiple: true).
1.1.0
-
ArgParser.parse()now takes anIterable<String>rather than aList<String>. -
ArgParser.addOption()'sallowedoption now takes anIterable<String>rather than aList<String>.
1.0.2
- Fix analyzer warning
1.0.1
- Fix a fuzzy arrow type warning.
1.0.0
-
Breaking change: The
allowTrailingOptionsargument tonew ArgumentParser()defaults totrueinstead offalse. -
Add
new ArgParser.allowAnything(). This allows any input, without parsing any options.
0.13.7
-
Add explicit support for forwarding the value returned by
Command.run()toCommandRunner.run(). This worked unintentionally prior to 0.13.6+1. -
Add type arguments to
CommandRunnerandCommandto indicate the return values of therun()functions.
0.13.6+1
- When a
CommandRunneris passed--helpbefore any commands, it now prints the usage of the chosen command.
0.13.6
-
ArgParser.parse()now throws anArgParserException, which implementsFormatExceptionand has a field that lists the commands that were parsed. -
If
CommandRunner.run()encounters a parse error for a subcommand, it now prints the subcommand's usage rather than the global usage.
0.13.5
- Allow
CommandRunner.argParserandCommand.argParserto be overridden in strong mode.
0.13.4+2
- Fix a minor documentation error.
0.13.4+1
- Ensure that multiple-value arguments produce reified
List<String>s.
0.13.4
-
By default, only the first line of a command's description is included in its parent runner's usage string. This returns to the default behavior from before 0.13.3+1.
-
A
Command.summarygetter has been added to explicitly control the summary that appears in the parent runner's usage string. This getter defaults to the first line of the description, but can be overridden if the user wants a multi-line summary.
0.13.3+6
- README fixes.
0.13.3+5
- Make strong mode clean.
0.13.3+4
- Use the proper
usagegetter in the README.
0.13.3+3
- Add an explicit default value for the
allowTrailingOptionsparameter tonew ArgParser(). This doesn't change the behavior at all; the option already defaulted tofalse, and passing innullstill works.
0.13.3+2
- Documentation fixes.
0.13.3+1
- Print all lines of multi-line command descriptions.
0.13.2
- Allow option values that look like options. This more closely matches the
behavior of
getopt, the de facto standard for option parsing.
0.13.1
- Add
ArgParser.addSeparator(). Separators allow users to group their options in the usage text.
0.13.0
- Breaking change: An option that allows multiple values will now
automatically split apart comma-separated values. This can be controlled with
the
splitCommasoption.
0.12.2+6
- Remove the dependency on the
collectionpackage.
0.12.2+5
- Add syntax highlighting to the README.
0.12.2+4
- Add an example of using command-line arguments to the README.
0.12.2+3
- Fixed implementation of ArgResults.options to really use Iterable
instead of Iterable cast to Iterable .
0.12.2+2
-
Updated dependency constraint on
unittest. -
Formatted source code.
-
Fixed use of deprecated API in example.
0.12.2+1
- Fix the built-in
helpcommand forCommandRunner.
0.12.2
-
Add
CommandRunnerandCommandclasses which make it easy to build a command-based command-line application. -
Add an
ArgResults.argumentsfield, which contains the original argument list.
0.12.1
- Replace
ArgParser.getUsage()withArgParser.usage, a getter.ArgParser.getUsage()is now deprecated, to be removed in args version 1.0.0.
0.12.0+2
- Widen the version constraint on the
collectionpackage.
0.12.0+1
- Remove the documentation link from the pubspec so this is linked to pub.dev by default.
0.12.0
-
Removed public constructors for
ArgResultsandOption. -
ArgResults.wasParsed()can be used to determine if an option was actually parsed or the default value is being returned. -
Replaced
isFlagandallowMultiplefields in theOptionclass with a three-valueOptionTypeenum. -
Options may define
valueHelpwhich will then be shown in the usage.
0.11.0
- Move handling trailing options from
ArgParser.parse()intoArgParseritself. This lets subcommands have different behavior for how they handle trailing options.
0.10.0+2
- Usage ignores hidden options when determining column widths.
