parseRedisCommandLine function

List<String> parseRedisCommandLine(
  1. String line
)

A command line split as redis-cli does: on spaces, with "..." and '...' quoting (backslash escapes inside double quotes).

Implementation

List<String> parseRedisCommandLine(String line) {
  final args = <String>[];
  final current = StringBuffer();
  var quote = '';
  var started = false;
  for (var i = 0; i < line.length; i++) {
    final char = line[i];
    if (quote.isNotEmpty) {
      if (char == quote) {
        quote = '';
      } else if (char == r'\' && quote == '"' && i + 1 < line.length) {
        final next = line[++i];
        current.write(switch (next) {
          'n' => '\n',
          'r' => '\r',
          't' => '\t',
          _ => next,
        });
      } else {
        current.write(char);
      }
    } else if (char == '"' || char == "'") {
      quote = char;
      started = true;
    } else if (char == ' ' || char == '\t') {
      if (started) {
        args.add(current.toString());
        current.clear();
        started = false;
      }
    } else {
      current.write(char);
      started = true;
    }
  }
  if (quote.isNotEmpty) {
    throw const FormatException('Unbalanced quotes.');
  }
  if (started) {
    args.add(current.toString());
  }
  return args;
}