diff --git a/include/dwarfs/util.h b/include/dwarfs/util.h index d36649d9..5b550e42 100644 --- a/include/dwarfs/util.h +++ b/include/dwarfs/util.h @@ -71,4 +71,6 @@ bool getenv_is_enabled(char const* var); void setup_default_locale(); +std::string_view basename(std::string_view path); + } // namespace dwarfs diff --git a/src/dwarfs/error.cpp b/src/dwarfs/error.cpp index f01a58f9..30989408 100644 --- a/src/dwarfs/error.cpp +++ b/src/dwarfs/error.cpp @@ -34,6 +34,7 @@ #include "dwarfs/error.h" #include "dwarfs/terminal.h" +#include "dwarfs/util.h" namespace dwarfs { @@ -50,7 +51,7 @@ namespace { } // namespace error::error(std::string const& s, char const* file, int line) noexcept - : what_{fmt::format("{} [{}:{}]", s, file, line)} + : what_{fmt::format("{} [{}:{}]", s, basename(file), line)} , file_{file} , line_{line} {} diff --git a/src/dwarfs/logger.cpp b/src/dwarfs/logger.cpp index e245ec0b..3ef24a4d 100644 --- a/src/dwarfs/logger.cpp +++ b/src/dwarfs/logger.cpp @@ -21,7 +21,6 @@ #include #include -#include #include #include @@ -250,8 +249,7 @@ void stream_logger::set_threshold(level_type threshold) { } std::string get_logger_context(char const* path, int line) { - auto base = ::strrchr(path, std::filesystem::path::preferred_separator); - return fmt::format("[{0}:{1}] ", base ? base + 1 : path, line); + return fmt::format("[{0}:{1}] ", basename(path), line); } std::string get_current_time_string() { diff --git a/src/dwarfs/util.cpp b/src/dwarfs/util.cpp index 65b298f4..26a20975 100644 --- a/src/dwarfs/util.cpp +++ b/src/dwarfs/util.cpp @@ -342,4 +342,12 @@ void setup_default_locale() { } } +std::string_view basename(std::string_view path) { + auto pos = path.find_last_of("/\\"); + if (pos == std::string_view::npos) { + return path; + } + return path.substr(pos + 1); +} + } // namespace dwarfs diff --git a/test/error_test.cpp b/test/error_test.cpp index 879480a9..8af49575 100644 --- a/test/error_test.cpp +++ b/test/error_test.cpp @@ -59,10 +59,10 @@ TEST(error_test, runtime_error) { test_throw_runtime_error(true); FAIL() << "expected runtime_error to be thrown"; } catch (const runtime_error& e) { - EXPECT_EQ(fmt::format("my test error [{}:{}]", e.file(), e.line()), - std::string(e.what())); EXPECT_EQ("error_test.cpp", std::filesystem::path(e.file()).filename().string()); + EXPECT_EQ(fmt::format("my test error [error_test.cpp:{}]", e.line()), + std::string(e.what())); EXPECT_EQ(expected_line, e.line()); } catch (...) { FAIL() << "expected runtime_error, got "