parseArguments static method

List<String> parseArguments(
  1. String command
)

Parses command into arguments. Uses space character to split the arguments. Supports single and double quote characters.

Implementation

static List<String> parseArguments(String command) {
  final List<String> argumentList = List<String>.empty(growable: true);
  StringBuffer currentArgument = new StringBuffer();

  bool singleQuoteStarted = false;
  bool doubleQuoteStarted = false;

  for (int i = 0; i < command.length; i++) {
    int? previousChar;
    if (i > 0) {
      previousChar = command.codeUnitAt(i - 1);
    } else {
      previousChar = null;
    }
    final currentChar = command.codeUnitAt(i);

    if (currentChar == ' '.codeUnitAt(0)) {
      if (singleQuoteStarted || doubleQuoteStarted) {
        currentArgument.write(String.fromCharCode(currentChar));
      } else if (currentArgument.length > 0) {
        argumentList.add(currentArgument.toString());
        currentArgument = new StringBuffer();
      }
    } else if (currentChar == '\''.codeUnitAt(0) &&
        (previousChar == null || previousChar != '\\'.codeUnitAt(0))) {
      if (singleQuoteStarted) {
        singleQuoteStarted = false;
      } else if (doubleQuoteStarted) {
        currentArgument.write(String.fromCharCode(currentChar));
      } else {
        singleQuoteStarted = true;
      }
    } else if (currentChar == '\"'.codeUnitAt(0) &&
        (previousChar == null || previousChar != '\\'.codeUnitAt(0))) {
      if (doubleQuoteStarted) {
        doubleQuoteStarted = false;
      } else if (singleQuoteStarted) {
        currentArgument.write(String.fromCharCode(currentChar));
      } else {
        doubleQuoteStarted = true;
      }
    } else {
      currentArgument.write(String.fromCharCode(currentChar));
    }
  }

  if (currentArgument.length > 0) {
    argumentList.add(currentArgument.toString());
  }

  return argumentList;
}