parseCliAssigns function

Map<String, String> parseCliAssigns(
  1. String cli
)

Parses cli command arguments into a Map of key-value assignments

It extract the command name and then processes the arguments.

  • export command: arguments are semicolon-separated.
  • set command: arguments are ampersand-separated (&& handled).
  • other commands: arguments are space-separated by default.

Invalid assignment entries are skipped.

final ssh = r'ssh --port=2222 --identity-file=~/.ssh/my_priv_key user@192.168.1.100'
print(parseCliAssigns(ssh)); // {--prot: 2222, --identity-file: ~/.ssh/my_priv_key}
print(parseCliAssigns('export SESSDIR=/tmp/sess;DEBUG=1')); // {SESSDIR: /tmp/tmp, DEBUG: 1}
print(parseCliAssigns('set SESSDIR=C:\tmp\sess&&DEBUG=1')); // {SESSDIR: C:\tmp\sess, DEBUG: 1}

Implementation

Map<String, String> parseCliAssigns(String cli) {
  final assigns = <String>[];

  var exec = '';
  var args = cli.split(spaceDelimiter);
  if (args.isNotEmpty) {
    exec = args.removeAt(0);
    assigns.addAll(args);
  }

  if (exec == 'export') {
    if (cli.contains(semicolonDelimiter)) {
      cli = cli
          .replaceAll(semicolonDelimiter, spaceDelimiter)
          .replaceAll('export', spaceDelimiter);
    }
    args = cli.trimLeft().split(spaceDelimiter);
    assigns
      ..clear()
      ..addAll(args);
  }

  if (exec == 'set') {
    final lineDelimiter = r'&&';
    if (cli.contains(lineDelimiter)) {
      cli = cli
          .replaceAll(lineDelimiter, spaceDelimiter)
          .replaceAll('set', spaceDelimiter);
    }
    args = cli.trimLeft().split(spaceDelimiter);
    assigns
      ..clear()
      ..addAll(args);
  }

  return parseAssigns(assigns);
}