Code Monkey home page Code Monkey logo

args's Issues

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>

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 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

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.

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.

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)

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

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.

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.

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)

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.

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: 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.

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.

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.

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

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.

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.

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.

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)

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

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)

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.

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)

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 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.

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)

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.

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 "/".

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.

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
    • ?
    • /?

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.