How to use mandatory field in dart args package

Viewed 111

I am trying to add a Mandatory field option for the argument in my dart script. I am using addOption() as visible in the code below. and to run the code in the terminal.

$dart args_demo.dart -h

If I run the code without mandatory: true in the method addOption(), I get no error and a help text is shown, everything works fine.

But, when I add this part mandatory: true in the method addOption(), and run the script with above command, I get this error massage

Unhandled exception:
FormatException: Option name is mandatory.
#0      Parser.parse.<anonymous closure> (package:args/src/parser.dart:101:9)
#1      _LinkedHashMapMixin.forEach (dart:collection-patch/compact_hash.dart:397:8)
#2      MapView.forEach (dart:collection/maps.dart:342:10)
#3      Parser.parse (package:args/src/parser.dart:95:22)
#4      ArgParser.parse (package:args/src/arg_parser.dart:335:42)
#5      main (file:///home/penguine/Desktop/codeTesting/argPackage/args_demo.dart:12:26)
#6      _delayEntrypointInvocation.<anonymous closure> (dart:isolate-patch/isolate_patch.dart:281:32)
#7      _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:184:12)

Please explain how can I use the mandatory field without getting error. thanks in advance.

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


void main(List<String> args){
  final parser = ArgParser()
    ..addSeparator('===options and flags and help===')
    ..addOption('name', abbr: 'n', help: 'Provide your name', mandatory: true)
    ..addFlag('help', abbr: 'h', help: 'Provide usage instruction', negatable: false)
    ..addOption('paas', help: 'what is your favorite PaaS', allowed: ['AWS', 'GCP', 'Heroku', 'MSA'], defaultsTo: 'GCP');

  final results = parser.parse(args);
  //print(results);

  if (results.wasParsed('help')){
    print(parser.usage);
    exit(0);
  }

  if (results.wasParsed('name')) {
    print('=>> ${results['name']}');
  }

  print('PAAS =>> ${results['paas']}');
}
1 Answers

Note that there is nothing special about the -h/--help option itself. It is a boolean flag like any other. Consequently, since you've made -n/--name mandatory, it is exactly that: it is always required, even if you're just trying to print usage text.

The way that -h/--help is handled provides its own clue how you can make an option conditionally required: check ArgResults.wasParsed() and explicitly fail if it's not provided:

  final results = parser.parse(args);

  if (results.wasParsed('help')){
    print(parser.usage);
    exit(0);
  }

  if (!results.wasParsed('name')) {
    stderr.writeln('--name is required.');
    exit(1);
  }

I agree that this behavior makes mandatory: true not very useful. It's a relatively recent addition to package:args, and I've filed https://github.com/dart-lang/args/issues/194.

Related