]> git.ipfire.org Git - thirdparty/ccache.git/commitdiff
Fix Util::dir_name for Windows paths
authorJoel Rosdahl <joel@rosdahl.net>
Tue, 29 Dec 2020 18:06:17 +0000 (19:06 +0100)
committerJoel Rosdahl <joel@rosdahl.net>
Tue, 29 Dec 2020 19:37:12 +0000 (20:37 +0100)
Util::dir_name does not understand “C:\”-style Windows path so add such
knowledge.

src/Util.cpp
unittest/test_Util.cpp

index caaed55435f3cd1927cf485345a28e5ff05c0ccd..2aaaa0a82b4a8479dcc3cf463dc5bf312360a635 100644 (file)
@@ -413,9 +413,19 @@ dir_name(string_view path)
 #endif
   size_t n = path.find_last_of(delim);
   if (n == std::string::npos) {
+    // "foo" -> "."
     return ".";
+  } else if (n == 0) {
+    // "/" -> "/" (Windows: or "\\" -> "\\")
+    return path.substr(0, 1);
+#ifdef _WIN32
+  } else if (n == 2 && path[1] == ':') {
+    // Windows: "C:\\foo" -> "C:\\" or "C:/foo" -> "C:/"
+    return path.substr(0, 3);
+#endif
   } else {
-    return n == 0 ? "/" : path.substr(0, n);
+    // "/dir/foo" -> "/dir" (Windows: or "C:\\dir\\foo" -> "C:\\dir")
+    return path.substr(0, n);
   }
 }
 
index ff4da6c33759c8e338ce8d4cee7e499f4de7e437..0d3cae367590f9ccc89bac6d3925f43d82427b27 100644 (file)
@@ -146,6 +146,16 @@ TEST_CASE("Util::dir_name")
   CHECK(Util::dir_name("/") == "/");
   CHECK(Util::dir_name("/foo") == "/");
   CHECK(Util::dir_name("/foo/bar/f.txt") == "/foo/bar");
+
+#ifdef _WIN32
+  CHECK(Util::dir_name("C:/x/y") == "C:/x");
+  CHECK(Util::dir_name("X:/x/y") == "X:/x");
+  CHECK(Util::dir_name("C:\\x\\y") == "C:\\x");
+  CHECK(Util::dir_name("C:/x") == "C:/");
+  CHECK(Util::dir_name("C:\\x") == "C:\\");
+  CHECK(Util::dir_name("C:/") == "C:/");
+  CHECK(Util::dir_name("C:\\") == "C:\\");
+#endif
 }
 
 TEST_CASE("Util::strip_ansi_csi_seqs")