Coder Social home page Coder Social logo

args's Introduction

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

args's People

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

args's Issues

Text after a newline in a Command's description is not displayed

Here's a repro:

import 'package:args/args.dart';
import 'package:args/command_runner.dart';

class FooCommand extends Command {
  String get name => 'foo';
  String get description => 'This is a \ntest';

  run() {}
}

main(args) {
  var runner = new CommandRunner('y', 'z');
  runner.addCommand(new FooCommand());

  print(runner.usage);
}

Expected:

Available commands:
  foo    This is a
           test.
  help   Display help information for y.

Actual:

Available commands:
  foo    This is a 
  help   Display help information for y.

ArgsResult should have a way to determine if the user actual set the value

Originally opened as dart-lang/sdk#16227

This issue was originally filed by [email protected]


Currently there is no way to differentiate between the user specifying the default value and the user not specifying anything, both result in the default value being in ArgResults. This causes a problem when you have default values and multiple sources of configuration information that you'd like to merge. For example if you would like to have a default configuration that you to allow be overridden by environment variables and command line arguments, with command line arguments having the highest priority.

Some argument styles don't work

<img src="https://avatars.githubusercontent.com/u/2164483?v=3" align="left" width="96" height="96"hspace="10"> Issue by kwalrath
Originally opened as dart-lang/sdk#12879


The args library docs say you have 4 ways to specify an option, but 2 of them don't work for me.

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

­2 results in null, and #­4 results in ' somevalue' (leading space).

Here's my test code.

  var parser = new ArgParser();
  parser.addOption('name', abbr: 'n');
  
  var results = parser.parse(['--name=somevalue0']);
  print(results['name']); // somevalue0

  results = parser.parse(['--name somevalue1']); // BROKEN
  print(results['name']); // somevalue1

  results = parser.parse(['-nsomevalue2']);
  print(results['name']); // somevalue2

  results = parser.parse(['-n somevalue3']); // SEMI-BROKEN
  print(results['name']); // somevalue3

Indicate the default value even when allowedHelp is passed

Currently, if allowedHelp and default are both passed to ArgParser.addOption(), the help output doesn't indicate what the default value is. For example:

-r, --runner                   The runner used to print test results.

          [compact]            A single line, updated continuously.
          [expanded]           A separate line for each update.

Output like the following would be better:

-r, --runner                   The runner used to print test results.

      [compact (default)]      A single line, updated continuously.
      [expanded]               A separate line for each update.

args parser cannot accept option arguments starting with a hyphen

<img src="https://avatars.githubusercontent.com/u/1381377?v=3" align="left" width="96" height="96"hspace="10"> Issue by hoylen
Originally opened as dart-lang/sdk#21958


What steps will reproduce the problem?

  1. Run the program below with arguments "-t -32"

dart bin/test-args-hyphen.dart -t -32

What is the expected output? What do you see instead?

Expected: Temperature is: -32

Got: FormatException: Missing argument for "temperature".

It treats the option argument as another option instead of the argument to the "-t" option.

What version of the product are you using?

1.8.3

On what operating system?

linux_x64

Please provide any additional information below.

// Test program

import 'package:args/args.dart';

void main(List<String> arguments) {

  var parser = new ArgParser(allowTrailingOptions: true);
  parser.addOption('temperature', abbr: 't', help: 'degrees');

  var results = parser.parse(arguments);

  print("Temperature is: ${results['temperature']}");;
}

//EOF

Pub / Args / Defining options / Unterminated string in example

Originally opened as dart-lang/sdk#19106

This issue was originally filed by [email protected]


URL: https://pub.dartlang.org/packages/args

This following code sample is missing a terminating quote mark.
Copying it -as is- into Dart Editor results in an syntax error.

CURRENT
parser.addOption('mode', callback: (mode) => print('Got mode $mode));

REVISION
parser.addOption('mode', callback: (mode) => print('Got mode $mode'));

See screenshot.


Attachment:
args_definingOptions.jpg (121.31 KB)

ArgResults should either implement the Map interface or make the options Map accessible

Originally opened as dart-lang/sdk#12771

This issue was originally filed by [email protected]


Right now, the options Map is private. ArgResults defines the [] operator to allow Map-like read-only access.

This works fine. However, you end up passing the ArgResults object around, because pulling the values out of that ArgsResult object is quite a bit of work. This is inconvenient when it comes to testing, because creating an ArgResults object is more work than creating a Map.

Also, this kind of dependency is really weird. Whatever that function does, it probably has very little to do with argument parsing. It shouldn't take an ArgsResult object as argument.

args: deprecate `callback` and replace with `parse`

<img src="https://avatars.githubusercontent.com/u/444270?v=3" align="left" width="96" height="96"hspace="10"> Issue by seaneagan
Originally opened as dart-lang/sdk#20079


callback doesn't seem to provide much benefit over just accessing the value from the results. If it could perform validation and parsing into other types (e.g. int) and throw nice error messages, I think it would be more useful. Example:

Old:

  parser.addOption('x', callback: (x) => print('x: $x'));
  parser.addOption('y', callback: (y) => print('y: $y'));

  var results = parser.parse(arguments);

  var x = int.parse(results['x']);
  var y = int.parse(results['y']);
  print('x + y: ${x + y}');

New:

  parser.addOption('x', parse: int.parse);
  parser.addOption('y', parse: int.parse);

  var results = parser.parse(arguments);

  int x = results['x'];
  int y = results['y'];
  print('x: $x');
  print('y: $y');
  print('x + y: ${x + y}');

If --x or --y are not formatted as integers, this would lead to something like:

  foo.dart: --foo value "xyz" is invalid: FormatException: ...

Of course you could throw whatever error you want, for example you could use matchers:

  parser.addOption('foo', parse: (s) {
    var matchState = {};
    if(!isNumeric.matches(s, matchState) {
      throw isNumeric.describeMismatch(s, new StringDescription(), matchState);
    }
    return num.parse(s);
  });

README: options instead of argResults

In the README file, in the CommandRunner example, it reference the (old?) non-existing 'options' member, instead of the correct 'argResults' member. The example need to get updated.

Gracefully handle unspecified args with ArgParser

<img src="https://avatars.githubusercontent.com/u/5479?v=3" align="left" width="96" height="96"hspace="10"> Issue by sethladd
Originally opened as dart-lang/sdk#14786


It would be nice to have an option in ArgParser to ignore unspecified args.

Use Case:

Build system specifies its own options.
Build system uses another library that specifies its options.

I want to pass args to both the main build system and the included library:

build.dart --my-option --deploy

Support positional args

Positional arguments are fully supported in unscripted. It would be nice to upstream that to args.

Unscripted has an internal Positional type which shares some properties with Option, like help, valueHelp, allowed, parser (e.g. int.parse), which can be added to a Usage (unscripted's version of ArgParser) via an addPositional method.

It also has a Rest type which inherits from Positional and defines a "rest parameter" which defines homogeneous trailing positional arguments, and which has a required property which defines whether or not at least one value is required. It can be assigned to a Usage via a rest property since there can only be one of them.

Supporting positionals allows unscripted to have:

  • Nice error messages upon too many or not enough positionals, or non-allowed values for a positional.
  • Nice help text for positionals:
$ foo.dart --help

Usage:

  foo.dart [<options>] <valueHelp1> <valueHelp2> <restValueHelp>...

    <valueHelp1>       <help1>
    <valueHelp2>       <help2>
    <restValueHelp>    <restHelp>

Options:
  ...
  • Tab-completion support for positionals:

Unscripted does not support optional positionals since dart methods cannot yet have both optional named and optional positional arguments, and so supporting optional positionals would mean no "--" options could be added, but presumably args could support it.

Proposed API

parser
    ..addPositional(...)
    ..addPositional(...)
    ..startOptionalPositionals()
    ..addPositional(...)
    ..addPositional(...)
    ..addRest(...);

If addRest is called, and not startOptionalPositionals, then at least rest arg must be passed.

Also, in unscripted I'm considering disallowing adding both positionals and sub-commands to the same Usage (ArgParser in args case), since that can be ambiguous. I think right now args assumes anything which matches a sub-command name is the sub-command and not a positional value, but the user might have intended differently. And it would also make the cli invocation hard to read when it includes both positional values and a sub-command name, I don't think I've ever seen it in practice, so shouldn't hurt to disallow it.

(Moved from http://dartbug.com/20042)

Show usage help for the command that failed

From @munificent on September 28, 2016 15:53

If the user enters a bad option or flag for a command, but the command itself is valid, the usage help should be for that command. Right now, if you do:

$ pub get --bloof

You get:

Could not find an option named "bloof".

Usage: pub <command> [arguments]

Global options:
-h, --help             Print this usage information.
    --version          Print pub version.
    --[no-]trace       Print debugging information when an error occurs.
    --verbosity        Control output verbosity.

          [all]        Show all output including internal tracing messages.
          [error]      Show only errors.
          [io]         Also show IO operations.
          [normal]     Show errors, warnings, and user messages.
          [solver]     Show steps during version resolution.
          [warning]    Show only errors and warnings.

-v, --verbose          Shortcut for "--verbosity=all".

Available commands:
  build       Apply transformers to build a package.
  cache       Work with the system cache.
  deps        Print package dependencies.
  downgrade   Downgrade the current package's dependencies to oldest versions.
  get         Get the current package's dependencies.
  global      Work with global packages.
  help        Display help information for pub.
  publish     Publish the current package to pub.dartlang.org.
  run         Run an executable from a package.
  serve       Run a local web development server.
  upgrade     Upgrade the current package's dependencies to latest versions.
  uploader    Manage uploaders for a package on pub.dartlang.org.
  version     Print pub version.

Run "pub help <command>" for more information about a command.
See http://dartlang.org/tools/pub for detailed documentation.

It would be better as:

Could not find an option named "bloof".

Usage: pub get
-h, --help                 Print this usage information.
    --[no-]offline         Use cached packages instead of accessing the network.
-n, --dry-run              Report what dependencies would change but don't change any.
    --[no-]precompile      Precompile executables and transformed dependencies.
                           (defaults to on)

    --[no-]packages-dir    Generate a packages/ directory when installing packages.
                           (defaults to on)

Run "pub help" to see global options.
See http://dartlang.org/tools/pub/cmd/pub-get.html for detailed documentation.

Copied from original issue: dart-lang/pub#1453

Args Package: Inconsistent spacing in getUsage() string.

<img src="https://avatars.githubusercontent.com/u/1148886?v=3" align="left" width="96" height="96"hspace="10"> Issue by butlermatt
Originally opened as dart-lang/sdk#5202


import('package:args/args.dart');

void main() {
  var parser = new ArgParser();
  
  parser.addOption('test', help: 'A short help line. Only one line');
  parser.addOption('test2', help: 'Another short help line. Still one.\n\n');
  parser.addOption('works', help: 'This is multiline help\nNext should work');
  parser.addOption('fails', help: 'Theres a proper space before this');
  
  print(parser.getUsage());
}

If you notice when running the above code, any single line comments only have one new line after them in the usage. Even when I manually specify two. However once I have a multi-line help content it provides two new lines after the option in the string.

Personally I would like to see all help followed by two new lines to prevent clumping of commands when there is a one-line help vs multi-line.

CommandRunner.run no longer returns the results of Command.run in 0.13.6+1.

The patch "Print command help for "bin --help command"" introduced a change where the result of CommandRunner.run would no longer return the result of Command.Run in case of successful command resolution. Flutter was depending on this behavior to pass the exit code of the command just run. Each Command subclass would return that command's exit code.

This caused a regression depending on the version of the args package we happened to pull in. We are working around this by pinning the version of the package we use flutter/flutter#6765.

It can be argued that we should not have been depending on this behavior because it was not documented to be stable. So I am not sure what the resolution is. We do prefer the old behavior though.

Create parser.addHelp()

I think "help" is a special, well-known flag and has to have its own settings.

// Old
parser.addFlag('help', abbr: 'h', negatable: false, 
          help: "Displays this help information.");

// New 
parser.addHelp();

Behavior

  • Use default parameters
  • Execute by default stdout.writeln(parser.usage); exit(0);
  • Add an optional bool parameter to show help if the user does not pass any parameters (ej. dart command.dart)
  • Accept by default
    • --help
    • -h
    • help
    • ?
    • /?

args: define args using dart method signature

<img src="https://avatars.githubusercontent.com/u/444270?v=3" align="left" width="96" height="96"hspace="10"> Issue by seaneagan
Originally opened as dart-lang/sdk#12272


The args of a command line script seem to map nicely to the args of a dart method. It would be nice to be able to define script args using the same techniques as dart methods, and be able to automatically forward script args to said method. Presumably both of these could be done using a mirror on the method.

Say we have a script called 'greet.dart':

    import 'package:args/args.dart' as args;
    
    main() => args.forward(_main);

    greet(String salutation, String name, [String punctuation = '']) =>
        print('$salutation $name$punctuation);

where _main could be defined using String positional arguments:

    // example:
    // some_script.dart John Hi
    _main(String name, [String salutation = 'Hello']) =>
        greet(salutation, name);

or String or bool named arguments:

    // example:
    // some_script.dart --salutation Hi --exclaim John
    _main(String name, {String salutation: 'Hello ', bool exclaim: false}) =>
        greet(salutation, name, exclaim ? '!' : '');

or with the trailing positional parameter being a List<String>:

    // example:
    // some_script.dart --salutation Hi Bob Alice
    _main(List<String> rest, {String salutation: 'Hello '}) =>
        greet(salutation, rest.join(', '));

If dart ever gets true rest arguments those could be used instead.

To add "help", comments on each arg would make sense, but that is against the dart style guide. For this and other arg metadata, dart's metadata could be used:

    _main(
        String name, {
        @­Arg(abbr: 's', 'How to greet them')
        String salutation: 'Hello ',
        @­Arg(abbr: 'p', help: 'Whether to includ a "!"', allowedHelp: const {'': 'none', '!': 'exclamation'})
        String punctuation = ''}) =>
        greet(salutation, name, punctuation);

Args Package: addOption callback argument should pass string not bool

<img src="https://avatars.githubusercontent.com/u/1148886?v=3" align="left" width="96" height="96"hspace="10"> Issue by butlermatt
Originally opened as dart-lang/sdk#5199


What steps will reproduce the problem?

import('package:args/args.dart');

void main() {
  var parser = new ArgParser();
  parser.addOption('test',
    callback: (String testArgs) {
      print(testArgs);
    });
}

What is the expected output? What do you see instead?
The above code generates a warning in the editor that (String) -> Dynamic is not assignable to (bool) -> void
Expected that it would not generate warnings.

What version of the product are you using? On what operating system?
Revision 12144 64-Bit DartSDK running on Ubuntu Linux 64-bit.

Please provide any additional information below.
While deleting the annotation does remove the warning, in larger code when I'm passing the argument to another method that expects a string, it sees the argument as a bool and generates a warning.

Bool is expected on the addFlag method for callback, but I would expect that addOption would expect a string to be passed.

Add support for enums to addOption()

I think it would be nice to be able to use enums from Dart 1.9 as parameters to addOption()'s allowed values. Something like this:

enum Commands { start, stop, status }
addOption('cmd', abbr: 'c', allowed: Commands)

Provide an option not to add a newline after multiline option help

Consider:

$ flutter drive --help
Runs Flutter Driver tests for the current project.

Usage: flutter drive [arguments]
-h, --help                     Print this usage information.
    --[no-]checked             Toggle Dart's checked mode.
                               (defaults to on)

    --[no-]trace-startup       Start tracing during startup.
    --route                    Which route to load when starting the app.
-t, --target                   Target app path / main entry-point file.
                               (defaults to "lib/main.dart")

    --[no-]keep-app-running    Will keep the Flutter application running when done testing. By default Flutter Driver stops the application after tests are finished.
    --[no-]use-existing-app    Will not start a new Flutter application but connect to an already running instance. This will also cause the driver to keep the application running after tests are done.
    --debug-port               Listen to the given port for a debug connection.
                               (defaults to "8181")

Run "flutter help" to see global options.

The newlines after --checked and --target make it look like the options are grouped into three groups, which they are not.

package args - please update on pub.dartlang.org

Originally opened as dart-lang/sdk#8888

This issue was originally filed by [email protected]


Please update package 'args' on pub.dartlang.org to reflect the change in
https://codereview.chromium.org/12328104/patch/10002/6017

Currently (0.1.2.0_r19354), 'args' is broken:

import "package:args/args.dart";
main() => new ArgParser().parse(new Options().arguments);

Results in:
Unhandled exception:
Unsupported operation: Cannot clear a non-extendable array

­0 List.clear (dart:core-patch:294:5)

­1 Parser.parse (package:args/src/parser.dart:99:15)

­2 ArgParser.parse (package:args/args.dart:310:50)

­3 main (file:///home/karl/repositories/dartkart/test/test_args.dart:6:29)

ability to specify 'help' for commands

<img src="https://avatars.githubusercontent.com/u/444270?v=3" align="left" width="96" height="96"hspace="10"> Issue by seaneagan
Originally opened as dart-lang/sdk#15247


If we can add commands to a parser, we ought to be able to add 'help' text for those commands (as with options and flags), and get it back out in a nice format.

    parser.addCommand(... help: ...);

    print(parser.commandUsage);

Which might output something like:

start Starts the service
stop Stops the service
restart Restarts the service

The help text could be accessible via a field in the command's ArgParser:

    parser.commands['foo'].help

and this field could be reused to store a description of the overall script:

    parser.help

(or possibly s/help/description)

Don't throw an Error when calling `wasParsed()` for a non-supplied option.

The documentation for wasParsed() says that the method will return true|false depending on whether or not the option was parsed. However, in the case where the option was NOT parsed, an ArgumentError is thrown rather than returning false.

This duplicates the functionality of the [] operator on the same class, which is not only redundant, but makes testing for the existence of options more difficult. Consider the following if the bar option is not given:

var parser = new ArgParser();
parser.addCommand("foo")
  ..addOption('bar',
      abbr: 'b',
      help: 'the bar you love most (optional)');

ArgResults cliArgs = parser.parse(arguments);

if (cliArgs.command.name == 'foo') {
  if (cliArgs.command.wasParsed('bar')) { // -- bar arg was given
    // do something with bar

  } else { // -- no bar arg :(
    // do something else // -- this will never happen due to the thrown error
  }
}

The ONLY option here is to use a try/catch (most likely with an empty catch block) to test for the existence of options.

args: Merge allowedHelp into allowed

<img src="https://avatars.githubusercontent.com/u/444270?v=3" align="left" width="96" height="96"hspace="10"> Issue by seaneagan
Originally opened as dart-lang/sdk#15705


Currently it looks something like:

  var allowed = {
    'x': 'x help',
    'y': 'y help',
    'z': 'z help',
  }

  parser.addOption('foo', allowed: allowed.keys.toList(), allowedHelp: allowed);

Nicer would be:

  parser.addOption('foo', allowed: {
    'x': 'x help',
    'y': 'y help',
    'z': 'z help',
  });

So allowed: would allow Iterable<String> or Map<String, String>

Add `allowMultiple` param to `addFlag`

Currently only addOption has the allowMultiple param, but it can be useful to allow multiple flags as well. For example to specify a verbosity level many scripts use multiple verbose flags:

foo -vvv

The main use case is to count flag occurrences. For this, we could require negatable to be false when allowMultiple is true, and then have ArgResults['multi-flag'] return an int representing how many times the flag was passed.

Alternatively we could allow negatable to be true, and have ArgResults['multi-flag'] return a List<bool>, but I'm not sure what the use case for that would be.

Support "/" options on Windows, and "/?" for help

<img src="https://avatars.githubusercontent.com/u/46275?v=3" align="left" width="96" height="96"hspace="10"> Issue by munificent
Originally opened as dart-lang/sdk#19806


Right now, args follows Unix conventions (such as they are) for option syntax. Many Windows applications also do that, but Windows also has its own rough conventions. Some don't play nice with what args already supports, but I think we should allow:

  1. "/?" as an alias for "--help".
  2. Long and short options can start with "/" instead of "-" and "--". Combined short options are not supported, so "/foo" is always "--foo" and never "-f -o o".
  3. ":" as a parameter separator, as in "/output:somefile.txt". This will only be supported when the prefix is "/".

Add a merge method to ArgResults

There are cases where args might be supplied in two different places, and then we want to merge them. For example, myscript.dart might allow args to be passed in via the cmdline, and defaults may also be supplied in ~/.myscriptrc.

I would expect ArgResults.merge to basically behave the same as Map.addAll. Specifically, given resultsFromRc.merge(resultsFromCmdline), each arg in resultsFromCmdline that wasParsed is added to resultsFromRc, overwriting any existing values.

It is hard for a user to merge each List<String> before parsing them, and it's hard to implement this feature as a user since ArgResults does not expose a Map of all arguments that were parsed, or that exist with their default values.

Typo in args README and code snippet

<img src="https://avatars.githubusercontent.com/u/5479?v=3" align="left" width="96" height="96"hspace="10"> Issue by sethladd
Originally opened as dart-lang/sdk#20224


http://pub.dartlang.org/packages/args

parser.addOption('out', help: 'The output path', helpValue: 'path',

(notice the helpValue)

However, according to the docs:

void addOption(String name, {String abbr, String help, String valueHelp, List<String> allowed, Map<String, String> allowedHelp, String defaultsTo, Function void callback(value), bool allowMultiple: false, bool hide: false})

(notice valueHelp)

Args Package: Cannot provide <fill in> value for help in addOption

<img src="https://avatars.githubusercontent.com/u/1148886?v=3" align="left" width="96" height="96"hspace="10"> Issue by butlermatt
Originally opened as dart-lang/sdk#5201


Frequently, command line helps will do something like:

--out=<output dir> The rest of the help information indented over
                       here which refers to <output dir> argument.

However with the Args package, there is no way to show a 'fill in' option. I can specify allowed arguments and help specific to those allowed arguments. But I can't refer to a fill in value, which can sometimes make the documentation feel kind of awkward.

Doc request: Simple template for reading args from main()

I want to add args to my Dart program and would love a example main() function that I can simple cut, paste and modify.

The current documentation is very good w.r.t using the ArgParser but it is unclear how you get the args from main() to the parser.

args: default negatable to false

<img src="https://avatars.githubusercontent.com/u/444270?v=3" align="left" width="96" height="96"hspace="10"> Issue by seaneagan
Originally opened as dart-lang/sdk#16022


I can't prove this, but I feel like non-negatable is more common.

For example, --help, --verbose, --quiet, --version are all non-negatable. Also, since flags should generally default to false, specifying --no-foo is redundant. I would prefer to explicitly ask for this feature when I need it, but I'm not sure when that would be.

Support overriding the default negated name of a boolean flag.

It would be great to be able to use the args package in contexts where the naming convetion for negated flags are different which requires overriding the default negated flag name (--no-).

This could e.g. be done by adding an optional negatedName parameter to the addFlag method.

Print usage info for bad flags (not just bad commands)

From @kevmoo on April 14, 2016 20:51

When you provide a bad flag, you get very little help

> pub upgrade --verboseo
Could not find an option named "verboseo".

It'd be nice if it was like a bad command – where you get usage info,

> pub upgradeo --help
Could not find a command named "upgradeo".

Usage: pub <command> [arguments]

Global options:
-h, --help             Print this usage information.
    --version          Print pub version.
...

Copied from original issue: dart-lang/pub#1405

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.