updated splitCommand method

This commit is contained in:
sahankj2000 2024-05-03 14:34:01 +05:30
parent 571b0f34f2
commit 1521887e89

View File

@ -252,66 +252,31 @@ public class NBCLIScenarioPreprocessor {
private static final Pattern WordAndMaybeAssignment = Pattern.compile("(?<name>\\w[-_\\d\\w.]+)((?<oper>=+)(?<val>.+))?");
public static List<String> splitCommand(String cmd) {
List<String> cmdSplit = new ArrayList<>();
Stack<Character> stack = new Stack<>();
StringBuilder builder = new StringBuilder();
for (char c : cmd.toCharArray()) {
switch (c) {
case ' ':
if (!stack.isEmpty() && (stack.peek() == '\'' || stack.peek() == '\"')) {
builder.append(c);
} else if (!builder.isEmpty()) {
cmdSplit.add(builder.toString());
builder.delete(0, builder.length());
}
break;
case '\"':
case '\'':
if (!stack.isEmpty()) {
if (stack.peek() == c) {
stack.pop();
} else if (stack.peek() == '\\') {
stack.pop();
builder.append(c);
} else {
stack.push(c);
}
} else {
stack.push(c);
}
break;
case '\\':
if (!stack.isEmpty() && stack.peek() == c) {
stack.pop();
builder.append(c);
} else {
stack.push(c);
}
break;
default:
builder.append(c);
public static String[] splitCommand(String cmd) {
// split command by honoring single quotes, double quotes and escape characters
String[] namedStepPieces = cmd.split(" +(?=([^\"]*\"[^\"]*\")*[^\"]*$)(?=([^']*'[^']*')*[^']*$)");
Pattern pattern1 = Pattern.compile("(?<!\\\\)\"");
Pattern pattern2 = Pattern.compile("(?<!\\\\)'");
for (int i = 0; i < namedStepPieces.length; i++) {
// check if the quotes are balanced
String stepPiece = namedStepPieces[i];
boolean balanced = pattern1.matcher(stepPiece).results().count() % 2 == 0;
balanced = balanced && (pattern2.matcher(stepPiece).results().count() % 2 == 0);
if (!balanced) {
throw new BasicError("Unclosed quote found in scenario cmd '" + cmd + "'");
}
// remove single quotes, double quotes and escape character
stepPiece = pattern1.matcher(stepPiece).replaceAll("");
stepPiece = pattern2.matcher(stepPiece).replaceAll("");
namedStepPieces[i] = stepPiece.replaceAll(Matcher.quoteReplacement("\\(?!\\)"), "");
}
if (!stack.isEmpty()) {
if (stack.peek() == '\'') {
throw new BasicError("Unclosed single quote found in scenario cmd '" + cmd + "'");
} else if (stack.peek() == '\"') {
throw new BasicError("Unclosed double quote found in scenario cmd '" + cmd + "'");
} else {
throw new BasicError("Unused escape character \"\\\" found in scenario cmd '" + cmd + "'");
}
}
if (!builder.isEmpty()) {
cmdSplit.add(builder.toString());
}
return cmdSplit;
return namedStepPieces;
}
private static LinkedHashMap<String, SCNamedParam> parseStep(String cmd, String stepName, String scenarioName) {
LinkedHashMap<String, SCNamedParam> parsedStep = new LinkedHashMap<>();
List<String> namedStepPieces = splitCommand(cmd);
String[] namedStepPieces = splitCommand(cmd);
for (String commandFragment : namedStepPieces) {
Matcher matcher = WordAndMaybeAssignment.matcher(commandFragment);