diff --git a/include/fmt/std.h b/include/fmt/std.h index 4a7df19c6bd64..0ba929fac54e2 100644 --- a/include/fmt/std.h +++ b/include/fmt/std.h @@ -20,8 +20,35 @@ # include FMT_BEGIN_NAMESPACE + +namespace detail { + +template +void write_escaped_path(basic_memory_buffer& quoted, + const std::filesystem::path& p) { + write_escaped_string(std::back_inserter(quoted), p.string()); +} +template <> +void write_escaped_path( + basic_memory_buffer& quoted, + const std::filesystem::path& p) { + write_escaped_string( + std::back_inserter(quoted), p.native()); +} + +} // namespace detail + template -struct formatter : basic_ostream_formatter { +struct formatter + : formatter> { + template + auto format(const std::filesystem::path& p, FormatContext& ctx) const -> + typename FormatContext::iterator { + basic_memory_buffer quoted; + detail::write_escaped_path(quoted, p); + return formatter>::format( + basic_string_view(quoted.data(), quoted.size()), ctx); + } }; FMT_END_NAMESPACE #endif diff --git a/test/std-test.cc b/test/std-test.cc index dcd75d5fe77bf..644cc9b074126 100644 --- a/test/std-test.cc +++ b/test/std-test.cc @@ -12,6 +12,8 @@ TEST(std_test, path) { #ifdef __cpp_lib_filesystem EXPECT_EQ(fmt::format("{:8}", std::filesystem::path("foo")), "\"foo\" "); + EXPECT_EQ(fmt::format("{}", std::filesystem::path("/path/to/foo\"bar.txt")), + "\"/path/to/foo\\\"bar.txt\""); #endif }