splitCommand static method

List<String> splitCommand(
  1. String command
)

Splitting the command while respecting the quoted strings

Implementation

static List<String> splitCommand(String command) {
  final List<String> result = [];
  final StringBuffer current = StringBuffer();
  bool inQuote = false;
  String quoteChar = '';

  for (int i = 0; i < command.length; i++) {
    final char = command[i];

    if (inQuote) {
      if (char == quoteChar) {
        inQuote = false;
        quoteChar = '';
      } else {
        current.write(char);
      }
    } else {
      if (char == '"' || char == "'") {
        inQuote = true;
        quoteChar = char;
      } else if (char == ' ') {
        if (current.isNotEmpty) {
          result.add(current.toString());
          current.clear();
        }
      } else {
        current.write(char);
      }
    }
  }

  if (current.isNotEmpty) {
    result.add(current.toString());
  }

  return result;
}