diff --git a/include/fmt/std.h b/include/fmt/std.h index baa30e1fd608..0ba929fac54e 100644 --- a/include/fmt/std.h +++ b/include/fmt/std.h @@ -19,18 +19,43 @@ #ifdef __cpp_lib_filesystem # 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 <> -struct fmt::formatter : formatter { +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 + : formatter> { template auto format(const std::filesystem::path& p, FormatContext& ctx) const -> typename FormatContext::iterator { - return formatter::format(p.string(), ctx); + 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 FMT_BEGIN_NAMESPACE -template <> struct formatter : ostream_formatter {}; +template +struct formatter : basic_ostream_formatter {}; FMT_END_NAMESPACE #endif // FMT_STD_H_ diff --git a/test/std-test.cc b/test/std-test.cc index 6cda28910b7f..069c83871955 100644 --- a/test/std-test.cc +++ b/test/std-test.cc @@ -11,7 +11,9 @@ TEST(std_test, path) { #ifdef __cpp_lib_filesystem - EXPECT_EQ(fmt::format("{:8}", std::filesystem::path("foo")), "foo "); + EXPECT_EQ(fmt::format("{:8}", std::filesystem::path("foo")), "\"foo\" "); + EXPECT_EQ(fmt::format("{}", std::filesystem::path("foo\"bar.txt")), + "\"foo\\\"bar.txt\""); #endif }