]> git.ipfire.org Git - thirdparty/ccache.git/commitdiff
Add util::base_name
authorJoel Rosdahl <joel@rosdahl.net>
Sat, 24 Aug 2019 20:17:51 +0000 (22:17 +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 5ab75757542a0fcce9c05bc41005bbee77448779..b042d466fe164e81a100764067801c578bf270de 100644 (file)
@@ -1763,6 +1763,19 @@ time_seconds(void)
 
 namespace util {
 
+std::string
+base_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
+  return n == std::string::npos ? path : path.substr(n + 1);
+}
+
 std::string
 read_file(const std::string& path)
 {
index 00b42673a275bbd84d8892d58c82c435d822fb59..e7e55f86fc0f9fcbd82cba38f9387d8a8bb128f2 100644 (file)
@@ -24,6 +24,9 @@
 
 namespace util {
 
+// Get base name of path.
+std::string base_name(const std::string& path);
+
 // Read file data as a string.
 std::string read_file(const std::string& path);
 
index 588a1ba474766c3ad067ed2f27de446bd7b1aae8..64268b0894728fcf5ae1a439afcba8a2234337f1 100644 (file)
 
 #include <catch.hpp>
 
+TEST_CASE("util::base_name")
+{
+  CHECK(util::base_name("") == "");
+  CHECK(util::base_name(".") == ".");
+  CHECK(util::base_name("foo") == "foo");
+  CHECK(util::base_name("/") == "");
+  CHECK(util::base_name("/foo") == "foo");
+  CHECK(util::base_name("/foo/bar/f.txt") == "f.txt");
+}
+
 TEST_CASE("util::read_file and util::write_file")
 {
   util::write_file("test", "foo\nbar\n");