From: Joel Rosdahl Date: Sat, 24 Aug 2019 20:18:33 +0000 (+0200) Subject: Add util::dir_name X-Git-Tag: v4.0~814 X-Git-Url: http://git.ipfire.org/?a=commitdiff_plain;h=628ed0c956fef70c882bde022eadeada021ccbc1;p=thirdparty%2Fccache.git Add util::dir_name --- diff --git a/src/util.cpp b/src/util.cpp index b042d466f..cb3815eb2 100644 --- a/src/util.cpp +++ b/src/util.cpp @@ -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) { diff --git a/src/util.hpp b/src/util.hpp index e7e55f86f..4753d2a14 100644 --- a/src/util.hpp +++ b/src/util.hpp @@ -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); diff --git a/unittest/test_util.cpp b/unittest/test_util.cpp index 64268b089..0ba3ffc51 100644 --- a/unittest/test_util.cpp +++ b/unittest/test_util.cpp @@ -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");