nix search: Add --json flag

This commit is contained in:
Eelco Dolstra 2017-07-18 17:30:09 +02:00
parent 90825dea51
commit b144c4d617
No known key found for this signature in database
GPG key ID: 8170B4726D7198DE

View file

@ -4,6 +4,8 @@
#include "eval-inline.hh" #include "eval-inline.hh"
#include "names.hh" #include "names.hh"
#include "get-drvs.hh" #include "get-drvs.hh"
#include "common-args.hh"
#include "json.hh"
#include <regex> #include <regex>
@ -19,7 +21,7 @@ std::string hilite(const std::string & s, const std::smatch & m)
+ std::string(m.suffix()); + std::string(m.suffix());
} }
struct CmdSearch : SourceExprCommand struct CmdSearch : SourceExprCommand, MixJSON
{ {
std::string re; std::string re;
@ -50,6 +52,8 @@ struct CmdSearch : SourceExprCommand
bool first = true; bool first = true;
auto jsonOut = json ? std::make_unique<JSONObject>(std::cout, true) : nullptr;
doExpr = [&](Value * v, std::string attrPath, bool toplevel) { doExpr = [&](Value * v, std::string attrPath, bool toplevel) {
debug("at attribute %s", attrPath); debug("at attribute %s", attrPath);
@ -86,18 +90,28 @@ struct CmdSearch : SourceExprCommand
|| !nameMatch.empty() || !nameMatch.empty()
|| !descriptionMatch.empty()) || !descriptionMatch.empty())
{ {
if (!first) std::cout << "\n"; if (json) {
first = false;
std::cout << fmt( auto jsonElem = jsonOut->object(attrPath);
"Attribute name: %s\n"
"Package name: %s\n" jsonElem.attr("pkgName", parsed.name);
"Version: %s\n" jsonElem.attr("version", parsed.version);
"Description: %s\n", jsonElem.attr("description", description);
hilite(attrPath, attrPathMatch),
hilite(name, nameMatch), } else {
parsed.version, if (!first) std::cout << "\n";
hilite(description, descriptionMatch)); first = false;
std::cout << fmt(
"Attribute name: %s\n"
"Package name: %s\n"
"Version: %s\n"
"Description: %s\n",
hilite(attrPath, attrPathMatch),
hilite(name, nameMatch),
parsed.version,
hilite(description, descriptionMatch));
}
} }
} }