]> git.ipfire.org Git - thirdparty/ccache.git/commitdiff
chore: Improve util::format_argv_for_logging
authorJoel Rosdahl <joel@rosdahl.net>
Sun, 16 Jul 2023 15:36:58 +0000 (17:36 +0200)
committerJoel Rosdahl <joel@rosdahl.net>
Tue, 18 Jul 2023 19:36:30 +0000 (21:36 +0200)
src/util/string.cpp
src/util/string.hpp
unittest/test_util_string.cpp

index fb3cdea4aa2138d77b402e22ed7c48fca1ee0c09..a9d61d1c6a48b8339c8ee4e8f637d794b2a81be0 100644 (file)
@@ -55,7 +55,8 @@ format_argv_for_logging(const char* const* argv)
     if (i != 0) {
       result += ' ';
     }
-    std::string arg(argv[i]);
+    std::string arg = replace_all(argv[i], "\\", "\\\\");
+    arg = replace_all(arg, "\"", "\\\"");
     if (arg.empty() || arg.find(' ') != std::string::npos) {
       arg = FMT("\"{}\"", arg);
     }
index f5a9ebc03fd060cd328ed13f79450f63504bef00..684f059e76af72a7b9b892635f5ff606bafa86da 100644 (file)
@@ -45,7 +45,8 @@ enum class SizeUnitPrefixType { binary, decimal };
 bool ends_with(std::string_view string, std::string_view suffix);
 
 // Format `argv` as a simple string for logging purposes. That is, the result is
-// not intended to be machine parsable. `argv` must be terminated by a nullptr.
+// not intended to be easily machine parsable. `argv` must be terminated by a
+// nullptr.
 std::string format_argv_for_logging(const char* const* argv);
 
 // Format a hexadecimal string representing `data`. The returned string will be
index 13b040dda06262f88ded6cc39ab2e1402529323a..4b1a2cc4ef170750967ce978c7d26d4a9c2d4d0c 100644 (file)
@@ -41,11 +41,35 @@ TEST_SUITE_BEGIN("util");
 
 TEST_CASE("util::format_argv_for_logging")
 {
-  const char* argv_0[] = {nullptr};
-  CHECK(util::format_argv_for_logging(argv_0) == "");
+  SUBCASE("nullptr")
+  {
+    const char* argv[] = {nullptr};
+    CHECK(util::format_argv_for_logging(argv) == "");
+  }
 
-  const char* argv_2[] = {"foo", "bar", nullptr};
-  CHECK(util::format_argv_for_logging(argv_2) == "foo bar");
+  SUBCASE("plain arguments")
+  {
+    const char* argv[] = {"foo", "bar", nullptr};
+    CHECK(util::format_argv_for_logging(argv) == "foo bar");
+  }
+
+  SUBCASE("argument with space")
+  {
+    const char* argv[] = {"foo bar", "fum", nullptr};
+    CHECK(util::format_argv_for_logging(argv) == "\"foo bar\" fum");
+  }
+
+  SUBCASE("argument with double quote")
+  {
+    const char* argv[] = {"foo\"bar", "fum", nullptr};
+    CHECK(util::format_argv_for_logging(argv) == "foo\\\"bar fum");
+  }
+
+  SUBCASE("argument with backslash")
+  {
+    const char* argv[] = {"foo\\bar", "fum", nullptr};
+    CHECK(util::format_argv_for_logging(argv) == "foo\\\\bar fum");
+  }
 }
 
 TEST_CASE("util::format_base16")