]> git.ipfire.org Git - thirdparty/ccache.git/commitdiff
Add util::dir_name
authorJoel Rosdahl <joel@rosdahl.net>
Sat, 24 Aug 2019 20:18:33 +0000 (22:18 +0200)
committerJoel Rosdahl <joel@rosdahl.net>
Thu, 5 Sep 2019 20:04:43 +0000 (22:04 +0200)
src/util.cpp
src/util.hpp
unittest/test_util.cpp

index b042d466fe164e81a100764067801c578bf270de..cb3815eb26fe4ff28f283db46b164b53b20ddab1 100644 (file)
@@ -1776,6 +1776,22 @@ base_name(const std::string& path)
   return n == std::string::npos ? path : path.substr(n + 1);
 }
 
+std::string
+dir_name(const std::string& path)
+{
+  size_t n = path.rfind('/');
+#ifdef _WIN32
+  size_t n2 = path.rfind('\\');
+  if (n2 != std::string::npos && n2 > n) {
+    n = n2;
+  }
+#endif
+  if (n == std::string::npos) {
+    return ".";
+  }
+  return n == 0 ? "/" : path.substr(0, n);
+}
+
 std::string
 read_file(const std::string& path)
 {
index e7e55f86fc0f9fcbd82cba38f9387d8a8bb128f2..4753d2a1428b02a96bb5c03ec0b507f21ff80e40 100644 (file)
@@ -27,6 +27,9 @@ namespace util {
 // Get base name of path.
 std::string base_name(const std::string& path);
 
+// Get directory name of path.
+std::string dir_name(const std::string& path);
+
 // Read file data as a string.
 std::string read_file(const std::string& path);
 
index 64268b0894728fcf5ae1a439afcba8a2234337f1..0ba3ffc5188177f6148f0b47ef3be1637dc40518 100644 (file)
@@ -30,6 +30,16 @@ TEST_CASE("util::base_name")
   CHECK(util::base_name("/foo/bar/f.txt") == "f.txt");
 }
 
+TEST_CASE("util::dir_name")
+{
+  CHECK(util::dir_name("") == ".");
+  CHECK(util::dir_name(".") == ".");
+  CHECK(util::dir_name("foo") == ".");
+  CHECK(util::dir_name("/") == "/");
+  CHECK(util::dir_name("/foo") == "/");
+  CHECK(util::dir_name("/foo/bar/f.txt") == "/foo/bar");
+}
+
 TEST_CASE("util::read_file and util::write_file")
 {
   util::write_file("test", "foo\nbar\n");