dart-lang / args Goto Github PK
View Code? Open in Web Editor NEWA command-line argument parsing library for Dart.
Home Page: https://pub.dev/packages/args
License: BSD 3-Clause "New" or "Revised" License
A command-line argument parsing library for Dart.
Home Page: https://pub.dev/packages/args
License: BSD 3-Clause "New" or "Revised" License
<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>
<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);
<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?
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
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.
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.
In analyzer_cli
and analysis_server
we work around this limitation by wrapping an ArgParser
and filtering out unknown options ourselves but it would be far better if this were in args
proper.
<img src="https://avatars.githubusercontent.com/u/264967?v=3" align="left" width="96" height="96"hspace="10"> Issue by amouravski
Originally opened as dart-lang/sdk#8389
zsh and bash both have a shell autocomplete capability, so that you can quickly complete flags, arguments, etc.
It'd be amazing if we could ingest an ArgParser and spit out zsh/bash completion files so that any dart script can autocomplete in this way.
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)
I want to write a subcommand that takes all its arguments and passes them unmodified through to another process. There doesn't seem to be a way to turn off ArgParser's error handling.
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
<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.
Pre-1.0 version numbers make it look like the package is not yet ready for use.
Instead of UsageError did you mean UsageException?
https://www.dartdocs.org/documentation/args/0.13.4+1/command_runner/CommandRunner/run.html
text:
The Future will throw a UsageError if args was invalid.
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.
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
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.
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.
I want a subcommand that has a different value for allowTrailingOptions than the default, but there's nowhere for me to override the creation of the ArgParser that ends up in _argParser in Command.
<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);
});
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.
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.
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.
<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
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
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.
<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#16178
Hiding options works:
parser.addOption('foo', hide: true)
hiding flags should work too, but there is no "hide" parameter:
parser.addFlag('foo', hide: true)
<img src="https://avatars.githubusercontent.com/u/17034?v=3" align="left" width="96" height="96"hspace="10"> Issue by kevmoo
Originally opened as dart-lang/sdk#20177
We'd like to lean on the pub site behavior of auto-linking to dartdocs.org
<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.
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.
<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)
Just ran into this
That's a rather strange omission IMO.
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
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:
$ foo.dart --help
Usage:
foo.dart [<options>] <valueHelp1> <valueHelp2> <restValueHelp>...
<valueHelp1> <help1>
<valueHelp2> <help2>
<restValueHelp> <restHelp>
Options:
...
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.
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)
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.
<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)
https://www.dartdocs.org/documentation/args/1.0.0/args/ArgParser/addOption.html doesn't define most of its arguments, for example valueHelp.
I guessed that addOption creates an Option under the hood but unfortunately the docs for Option (https://www.dartdocs.org/documentation/args/1.0.0/args/Option-class.html) also don't define the similarly named properties, including valueHelp.
Improves code display on github
<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
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.
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)
I wish you could have hidden subcommands that didn't appear in the help, the same way you can have hidden arguments and options.
<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?
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.
<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:
<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
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.
<img src="https://avatars.githubusercontent.com/u/188?v=3" align="left" width="96" height="96"hspace="10"> Issue by nex3
Originally opened as dart-lang/sdk#20042
It's not too difficult to handle argument length validation, but it would be nice if ArgParser had some built-in support for it, especially if it included automatically generating nice error messages.
<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#21921
See https://chromiumcodereview.appspot.com/785293004/
I would love to contribute to this package!
I can't seem to find a way to accept a list of files generated from a find command. Would I have to parse these myself from the parsedArgs.rest
list, or is there a supported way of doing this?
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
stdout.writeln(parser.usage); exit(0);
<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#12536
Unless there are plans to add parameters ?
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.