extractQuotedContent function
Extract quoted content from a command string. Returns strings with different levels of quote stripping.
Implementation
QuoteExtraction extractQuotedContent(String command, {bool isJq = false}) {
final withDoubleQuotes = StringBuffer();
final fullyUnquoted = StringBuffer();
final unquotedKeepQuoteChars = StringBuffer();
var inSingleQuote = false;
var inDoubleQuote = false;
var escaped = false;
for (var i = 0; i < command.length; i++) {
final char = command[i];
if (escaped) {
escaped = false;
if (!inSingleQuote) withDoubleQuotes.write(char);
if (!inSingleQuote && !inDoubleQuote) fullyUnquoted.write(char);
if (!inSingleQuote && !inDoubleQuote) {
unquotedKeepQuoteChars.write(char);
}
continue;
}
if (char == r'\' && !inSingleQuote) {
escaped = true;
if (!inSingleQuote) withDoubleQuotes.write(char);
if (!inSingleQuote && !inDoubleQuote) fullyUnquoted.write(char);
if (!inSingleQuote && !inDoubleQuote) {
unquotedKeepQuoteChars.write(char);
}
continue;
}
if (char == "'" && !inDoubleQuote) {
inSingleQuote = !inSingleQuote;
unquotedKeepQuoteChars.write(char);
continue;
}
if (char == '"' && !inSingleQuote) {
inDoubleQuote = !inDoubleQuote;
unquotedKeepQuoteChars.write(char);
if (!isJq) continue;
}
if (!inSingleQuote) withDoubleQuotes.write(char);
if (!inSingleQuote && !inDoubleQuote) fullyUnquoted.write(char);
if (!inSingleQuote && !inDoubleQuote) {
unquotedKeepQuoteChars.write(char);
}
}
return QuoteExtraction(
withDoubleQuotes: withDoubleQuotes.toString(),
fullyUnquoted: fullyUnquoted.toString(),
unquotedKeepQuoteChars: unquotedKeepQuoteChars.toString(),
);
}