From 342170a42790353b03bbc116cfa83e70c4bd4487 Mon Sep 17 00:00:00 2001 From: Qrox Date: Mon, 30 Dec 2019 02:03:34 +0800 Subject: [PATCH] Conserve escape sequences in json formatter & add json formatter to CMake lists --- CMakeLists.txt | 4 ++++ tools/format/CMakeLists.txt | 11 +++++++++++ tools/format/format.cpp | 12 ++++++++++-- 3 files changed, 25 insertions(+), 2 deletions(-) create mode 100644 tools/format/CMakeLists.txt diff --git a/CMakeLists.txt b/CMakeLists.txt index 30cd27aa63a00..e09dd28c2312d 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -19,6 +19,7 @@ option(USE_HOME_DIR "Use user's home directory for save files." "ON") option(LOCALIZE "Support for language localizations. Also enable UTF support." "ON") option(LANGUAGES "Compile localization files for specified languages." "") option(DYNAMIC_LINKING "Use dynamic linking. Or use static to remove MinGW dependency instead." "ON") +option(JSON_FORMAT "Build JSON formatter" "OFF") option(CATA_CLANG_TIDY_PLUGIN "Build Cata's custom clang-tidy plugin" "OFF") set(CATA_CLANG_TIDY_INCLUDE_DIR "" CACHE STRING "Path to internal clang-tidy headers required for plugin (e.g. ClangTidy.h)") set(CATA_CHECK_CLANG_TIDY "" CACHE STRING "Path to check_clang_tidy.py for plugin tests") @@ -354,6 +355,9 @@ if (NOT MSVC) add_subdirectory(src/chkjson) endif() add_subdirectory(tests) +if (JSON_FORMAT) + add_subdirectory(tools/format) +endif() if (CATA_CLANG_TIDY_PLUGIN) add_subdirectory(tools/clang-tidy-plugin) endif() diff --git a/tools/format/CMakeLists.txt b/tools/format/CMakeLists.txt new file mode 100644 index 0000000000000..465eeaae64bee --- /dev/null +++ b/tools/format/CMakeLists.txt @@ -0,0 +1,11 @@ +include(ExternalProject) + +add_executable( + json_formatter + format.cpp + ${CMAKE_SOURCE_DIR}/src/json.cpp + ) + +ADD_DEFINITIONS(-DCATA_IN_TOOL) + +INCLUDE_DIRECTORIES( ${CMAKE_SOURCE_DIR}/src ) diff --git a/tools/format/format.cpp b/tools/format/format.cpp index 320c7f2aa3cae..06b1e45446f0a 100644 --- a/tools/format/format.cpp +++ b/tools/format/format.cpp @@ -94,8 +94,16 @@ static void format( JsonIn &jsin, JsonOut &jsout, int depth, bool force_wrap ) } else if( jsin.test_object() ) { format_collection( jsin, jsout, depth, write_object, force_wrap ); } else if( jsin.test_string() ) { - std::string str = jsin.get_string(); - jsout.write( str ); + // The string may contain escape sequences which we want to keep in the output. + const int start_pos = jsin.tell(); + jsin.get_string(); + const int end_pos = jsin.tell(); + std::string str = jsin.substr( start_pos, end_pos - start_pos ); + str = str.substr( str.find( '"' ) ); + str = str.substr( 0, str.rfind( '"' ) + 1 ); + jsout.write_separator(); + *jsout.get_stream() << str; + jsout.set_need_separator(); } else if( jsin.test_number() ) { // Have to introspect into the string to distinguish integers from floats. // Otherwise they won't serialize correctly.