Invocation.parse constructor

Invocation.parse(
  1. List<String> arguments
)

Parses arguments as typed after dpk.

Throws a UsageException for an unknown option before the command.

Implementation

factory Invocation.parse(List<String> arguments) {
  String? directory;
  String? cacheDirectory;
  var verbose = false;
  var quiet = false;
  bool? color;
  var help = false;
  var version = false;

  var index = 0;
  String takeValue(String option) {
    if (index + 1 >= arguments.length) {
      throw UsageException('Option "$option" needs a value.', usageHint);
    }
    index++;
    return arguments[index];
  }

  while (index < arguments.length) {
    final argument = arguments[index];
    if (argument == '--') {
      index++;
      break;
    }
    if (!argument.startsWith('-') || argument == '-') {
      break;
    }

    switch (argument) {
      case '-C' || '--directory':
        directory = takeValue(argument);
      case '--cache-dir':
        cacheDirectory = takeValue(argument);
      case '-v' || '--verbose':
        verbose = true;
      case '-q' || '--quiet':
        quiet = true;
      case '--color':
        color = true;
      case '--no-color':
        color = false;
      case '-h' || '--help':
        help = true;
      case '--version':
        version = true;
      case _ when argument.startsWith('--directory='):
        directory = argument.substring('--directory='.length);
      case _ when argument.startsWith('--cache-dir='):
        cacheDirectory = argument.substring('--cache-dir='.length);
      case _ when argument.startsWith('-C') && argument.length > 2:
        directory = argument.substring(2);
      default:
        throw UsageException(
          'Unknown option "$argument". dpk options go before the command, '
          'and options after the command belong to the command.',
          usageHint,
        );
    }
    index++;
  }

  final command = index < arguments.length ? arguments[index] : null;
  return Invocation(
    directory: directory,
    cacheDirectory: cacheDirectory,
    verbose: verbose,
    quiet: quiet,
    color: color,
    help: help,
    version: version,
    command: command,
    commandArguments: command == null
        ? const []
        : arguments.sublist(index + 1),
  );
}