Skip to content

Commit 8d2947c

Browse files
authored
feat(cpp-client): Add a cross-platform method to get the filename from a path (deephaven#5836)
We needed something functionally similar to the Linux `basename()` method. We can behavior that meets our needs by using `std::filesystem::path(p).filename().string()`
1 parent dffd573 commit 8d2947c

File tree

3 files changed

+28
-0
lines changed

3 files changed

+28
-0
lines changed

cpp-client/deephaven/dhcore/include/public/deephaven/dhcore/utility/utility.h

+10
Original file line numberDiff line numberDiff line change
@@ -187,6 +187,16 @@ TimePointToEpochMillis(
187187
TimePointToStr(
188188
std::chrono::time_point<std::chrono::system_clock> time_point);
189189

190+
/**
191+
* This is a method that simply invokes std::filesystem::path(path).filename().string().
192+
* We put it here because it is sometimes useful, to provide functionality
193+
* similar to the POSIX basename() call. We deliberately do not inline it
194+
* because is generates a surprising amount of code.
195+
* @param path The path
196+
* @return The basename of the path, as returned by std::filesystem::path(path).filename().string()
197+
*/
198+
std::string Basename(std::string_view path);
199+
190200
template <class T> [[nodiscard]] std::string
191201
TypeName(const T& t) {
192202
return demangle(typeid(t).name());

cpp-client/deephaven/dhcore/src/utility/utility.cc

+5
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
*/
44
#include "deephaven/dhcore/utility/utility.h"
55

6+
#include <filesystem>
67
#include <ostream>
78
#include <string>
89
#include <vector>
@@ -144,6 +145,10 @@ TimePointToStr(
144145
return EpochMillisToStr(TimePointToEpochMillis(time_point));
145146
}
146147

148+
std::string Basename(std::string_view path) {
149+
return std::filesystem::path(path).filename().string();
150+
}
151+
147152
#ifdef __GNUG__
148153
std::string demangle(const char *name) {
149154
int status = -1;

cpp-client/deephaven/tests/src/utility_test.cc

+13
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
#include "deephaven/dhcore/utility/utility.h"
66

77
using deephaven::dhcore::utility::Base64Encode;
8+
using deephaven::dhcore::utility::Basename;
89
using deephaven::dhcore::utility::EpochMillisToStr;
910
using deephaven::dhcore::utility::ObjectId;
1011

@@ -28,4 +29,16 @@ TEST_CASE("ObjectId", "[utility]") {
2829
auto id = ObjectId("hello", reinterpret_cast<void *>(p));
2930
CHECK(id == "hello(0xdeadbeef)");
3031
}
32+
33+
TEST_CASE("Basename", "[utility]") {
34+
#ifdef __linux__
35+
CHECK("file.txt" == Basename("/home/kosak/file.txt"));
36+
CHECK(Basename("/home/kosak/").empty());
37+
#endif
38+
39+
#ifdef _WIN32
40+
CHECK("file.txt" == Basename(R"(C:\Users\kosak\file.txt)"));
41+
CHECK(Basename(R"(C:\Users\kosak\)").empty());
42+
#endif
43+
}
3144
} // namespace deephaven::client::tests

0 commit comments

Comments
 (0)