Skip to content

Commit

Permalink
fix: ignore empty args when splitting commands (fix #3239)
Browse files Browse the repository at this point in the history
  • Loading branch information
Bionus committed Jul 3, 2024
1 parent 2756a63 commit b34eb95
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 2 deletions.
14 changes: 12 additions & 2 deletions src/lib/src/functions.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,14 @@ QString lastErrorString()
}


/**
* Re-implementation of QProcess::splitCommand that supports both single and double quotes.
*
* For example, `"a b" 'c d' e` will be turned into ("a b", "c d", "e").
*
* @param command The command to split into a list of process arguments.
* @return The list of arguments to start the process with.
*/
QStringList splitCommand(const QString &command)
{
QStringList args;
Expand Down Expand Up @@ -114,8 +122,10 @@ QStringList splitCommand(const QString &command)

// If we finally reached a space outside a quoted argument, we flush
if (!inQuote && c.isSpace()) {
args += tmp;
tmp.clear();
if (!tmp.isEmpty()) {
args += tmp;
tmp.clear();
}
} else {
tmp += c;
}
Expand Down
28 changes: 28 additions & 0 deletions src/lib/tests/src/functions-test.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
#include <QFile>
#include <QFileInfo>
#include <QFont>
#include <QProcess>
#include <QRect>
#include <QSettings>
#include <QTemporaryFile>
Expand Down Expand Up @@ -491,6 +492,13 @@ TEST_CASE("Functions")
REQUIRE(splitCommand("a b c") == QStringList { "a", "b", "c" });
}

SECTION("Multiple spaces")
{
REQUIRE(splitCommand(" ") == QStringList {});
REQUIRE(splitCommand(" a ") == QStringList { "a" });
REQUIRE(splitCommand(" a b c ") == QStringList { "a", "b", "c" });
}

SECTION("Backslash escape")
{
REQUIRE(splitCommand("a\\ b c") == QStringList { "a b", "c" });
Expand Down Expand Up @@ -523,6 +531,26 @@ TEST_CASE("Functions")
REQUIRE(splitCommand("a \"'b' c\"") == QStringList { "a", "'b' c" });
REQUIRE(splitCommand("a \"'b' \"\"\" c\"") == QStringList { "a", "'b' \" c" });
}

SECTION("Consistent with QProcess::splitCommand")
{
static const QStringList tests {
"",
" ",
"a",
" a ",
"a b c",
" a b c ",
"\"a b\" c",
"a \"b c\"",
"\"a b c\"",
"\"a b \"\"\" c\"",
};

for (const QString &str : tests) {
REQUIRE(splitCommand(str) == QProcess::splitCommand(str));
}
}
}

SECTION("getKeySequence")
Expand Down

0 comments on commit b34eb95

Please sign in to comment.