parseArguments static method

List<String> parseArguments(
  1. String command
)

Parses the given command into arguments.

Implementation

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

  var singleQuoteStarted = false;
  var doubleQuoteStarted = false;

  for (var i = 0; i < command.length; i++) {
    var previousChar;
    if (i > 0) {
      previousChar = command.codeUnitAt(i - 1);
    } else {
      previousChar = null;
    }
    var 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 = 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;
}