diff --git a/man/epubgrep.1.adoc b/man/epubgrep.1.adoc index acc19f3..4830e63 100644 --- a/man/epubgrep.1.adoc +++ b/man/epubgrep.1.adoc @@ -81,8 +81,12 @@ suppresses errors related to them. *--debug*:: Write debug output to the terminal and log file. + *--json*:: -Output JSON instead of plain text. +Output JSON instead of plain text. JSON will only output at the end of the +program. There will be an object named `generator` with the property +`epubgrep`, the value is the version of the program, as string. The rest is an +array named `matches`. == USAGE diff --git a/src/main.cpp b/src/main.cpp index b787321..f4e0090 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -220,7 +220,7 @@ int main(int argc, char *argv[]) std::async(std::launch::async, search_file, filepath)); DEBUGLOG << "Launched new thread"; - if (!matches_all.empty()) + if (!matches_all.empty() && !opts.json) { output::print_matches(matches_all[0], opts, input_files.size() == 1); @@ -231,13 +231,13 @@ int main(int argc, char *argv[]) DEBUGLOG << "Waiting for remaining threads to finish"; futures_cleanup(true); - for (const auto &matches : matches_all) + if (opts.json) { - if (opts.json) - { - output::json(matches); - } - else + output::json_all(matches_all); + } + else + { + for (const auto &matches : matches_all) { output::print_matches(matches, opts, input_files.size() == 1); } diff --git a/src/output.cpp b/src/output.cpp index e2cc422..2ea5ba3 100644 --- a/src/output.cpp +++ b/src/output.cpp @@ -16,6 +16,8 @@ #include "output.hpp" +#include "version.hpp" + #include #include #include // For compatibility with fmt 4. @@ -111,20 +113,27 @@ void print_matches(const std::vector &matches, } } -void json(const std::vector &matches) +void json_all(const std::vector> &matches_all) { nlohmann::json json; - for (const auto &match : matches) + json["generator"] = {{"epubgrep", version}}; + + for (const auto &matches : matches_all) { - json[match.filepath_epub].push_back( - {{"filepath", match.filepath_inside}, - {"match", match.text}, - {"context", match.context}, - {"headline", match.headline}, - {"page", match.page}}); + for (const auto &match : matches) + { + json["matches"].push_back( + {{"filepath_epub", match.filepath_epub}, + {"filepath_inside", match.filepath_inside}, + {"match", match.text}, + {"context", match.context}, + {"headline", match.headline}, + {"page", match.page}}); + } } - std::cout << json.dump(2) << '\n'; + + std::cout << json.dump() << '\n'; } } // namespace epubgrep::output diff --git a/src/output.hpp b/src/output.hpp index 3092646..376a1e4 100644 --- a/src/output.hpp +++ b/src/output.hpp @@ -28,7 +28,7 @@ namespace epubgrep::output void print_matches(const std::vector &matches, const options::options &opts, bool single_file); -void json(const std::vector &matches); +void json_all(const std::vector> &matches_all); } // namespace epubgrep::output