parseArguments function

List<String> parseArguments(
  1. ArgParser argParser,
  2. ArgResults? argResults,
  3. Set<String> options, {
  4. required Map<String, String> flagReplacements,
  5. required Set<String> initialArgs,
})

flagReplacements
Flags that are identified by an alternative name, but should be replaced with the original name.

eg. dart-coverage -> coverage

Implementation

List<String> parseArguments(
  ArgParser argParser,
  ArgResults? argResults,
  Set<String> options, {
  required Map<String, String> flagReplacements,
  required Set<String> initialArgs,
}) {
  if (argResults == null) return [];
  final args = <String>[...initialArgs];

  final arguments = [
    ...argResults.arguments,
  ];

  for (final option in options) {
    if (!argResults.wasParsed(option)) {
      continue;
    }

    final definedOption = argParser.findByNameOrAlias(option);
    if (definedOption == null) {
      throw Exception('Unknown option: $option');
    }

    final tempParser = AnyArgParser()..inject(definedOption);

    final result = tempParser.parse(arguments);
    final value = result[option];

    if (value == null) {
      continue;
    }

    // We to check if the option has a replacement
    dynamic option_ = option;

    if (flagReplacements.containsKey(option)) {
      option_ = flagReplacements[option];
    }

    if (value is List<String>) {
      args.addAll(['--$option_', ...value]);
    } else if (value is bool) {
      if (value) {
        args.add('--$option_');
      } else {
        args.add('--no-$option_');
      }
    } else {
      args.addAll(['--$option_', '$value']);
    }
  }

  args.removeWhere((e) => e.isEmpty);

  return args;
}