Works as a replacement for the legacy util function.
#include <algorithm>
#include <fstream>
+using nonstd::string_view;
+
namespace {
void
std::vector<std::string> directories;
dirent* de;
while ((de = readdir(d))) {
- nonstd::string_view name(de->d_name);
+ string_view name(de->d_name);
if (name == "" || name == "." || name == ".." || name == "CACHEDIR.TAG"
|| name == "stats" || name.starts_with(".nfs")) {
continue;
return n == 0 ? "/" : path.substr(0, n);
}
+nonstd::string_view
+get_extension(nonstd::string_view path)
+{
+#ifndef _WIN32
+ const char stop_at_chars[] = "./";
+#else
+ const char stop_at_chars[] = "./\\";
+#endif
+ size_t pos = path.find_last_of(stop_at_chars);
+ if (pos == string_view::npos || path.at(pos) == '/') {
+ return string_view();
+#ifdef _WIN32
+ } else if (path.at(pos) == '\\') {
+ return string_view();
+#endif
+ } else {
+ return path.substr(pos);
+ }
+}
+
nonstd::string_view
get_truncated_base_name(nonstd::string_view path, size_t max_length)
{
// Get base name of path.
nonstd::string_view base_name(nonstd::string_view path);
+// Return the file extension (including the dot) as a view into `path`.
+// If `path` has no file extension, an empty string_view is returned.
+nonstd::string_view get_extension(nonstd::string_view path);
+
// Return a shortened view into the base name of `path``. This view starts at
// the beginning of the base name and ends at either the position the first dot,
// or `max_length`, or the length of the base name, whichever is the shortest.
CHECK(Util::base_name("/foo/bar/f.txt") == "f.txt");
}
+TEST_CASE("Util::get_extension")
+{
+ CHECK(Util::get_extension("") == "");
+ CHECK(Util::get_extension(".") == ".");
+ CHECK(Util::get_extension("...") == ".");
+ CHECK(Util::get_extension("foo") == "");
+ CHECK(Util::get_extension("/") == "");
+ CHECK(Util::get_extension("/foo") == "");
+ CHECK(Util::get_extension("/foo/bar/f") == "");
+ CHECK(Util::get_extension("f.txt") == ".txt");
+ CHECK(Util::get_extension("f.abc.txt") == ".txt");
+ CHECK(Util::get_extension("/foo/bar/f.txt") == ".txt");
+ CHECK(Util::get_extension("/foo/bar/f.abc.txt") == ".txt");
+}
+
TEST_CASE("Util:get_truncated_base_name")
{
CHECK(Util::get_truncated_base_name("", 5) == "");