diff --git a/lix/legacy/nix-env.cc b/lix/legacy/nix-env.cc index 956ef2804..1a9f72877 100644 --- a/lix/legacy/nix-env.cc +++ b/lix/legacy/nix-env.cc @@ -961,15 +961,14 @@ static VersionDiff compareVersionAgainstSet( static void queryJSON(EvalState & state, Globals & globals, std::vector & elems, bool printOutPath, bool printDrvPath, bool printMeta) { - using nlohmann::json; - json topObj = json::object(); + JSON topObj = JSON::object(); for (auto & i : elems) { try { if (i.hasFailed()) continue; auto drvName = DrvName(i.queryName(state)); - json &pkgObj = topObj[i.attrPath]; + JSON &pkgObj = topObj[i.attrPath]; pkgObj = { {"name", drvName.fullName}, {"pname", drvName.name}, @@ -980,8 +979,8 @@ static void queryJSON(EvalState & state, Globals & globals, std::vector { DrvInfo::Outputs outputs = i.queryOutputs(state, printOutPath); - json &outputObj = pkgObj["outputs"]; - outputObj = json::object(); + JSON &outputObj = pkgObj["outputs"]; + outputObj = JSON::object(); for (auto & j : outputs) { if (j.second) outputObj[j.first] = globals.state->store->printStorePath(*j.second); @@ -996,8 +995,8 @@ static void queryJSON(EvalState & state, Globals & globals, std::vector } if (printMeta) { - json &metaObj = pkgObj["meta"]; - metaObj = json::object(); + JSON &metaObj = pkgObj["meta"]; + metaObj = JSON::object(); StringSet metaNames = i.queryMetaNames(state); for (auto & j : metaNames) { Value * v = i.queryMeta(state, j); diff --git a/lix/libcmd/built-path.cc b/lix/libcmd/built-path.cc index 939d1a333..ef2f8182c 100644 --- a/lix/libcmd/built-path.cc +++ b/lix/libcmd/built-path.cc @@ -83,9 +83,9 @@ SingleDerivedPath SingleBuiltPath::discardOutputPath() const ); } -kj::Promise> BuiltPath::Built::toJSON(const Store & store) const +kj::Promise> BuiltPath::Built::toJSON(const Store & store) const try { - nlohmann::json res; + JSON res; res["drvPath"] = TRY_AWAIT(drvPath->toJSON(store)); for (const auto & [outputName, outputPath] : outputs) { res["outputs"][outputName] = store.printStorePath(outputPath); @@ -95,9 +95,9 @@ try { co_return result::current_exception(); } -kj::Promise> SingleBuiltPath::Built::toJSON(const Store & store) const +kj::Promise> SingleBuiltPath::Built::toJSON(const Store & store) const try { - nlohmann::json res; + JSON res; res["drvPath"] = TRY_AWAIT(drvPath->toJSON(store)); auto & [outputName, outputPath] = output; res["output"] = outputName; @@ -107,7 +107,7 @@ try { co_return result::current_exception(); } -kj::Promise> SingleBuiltPath::toJSON(const Store & store) const +kj::Promise> SingleBuiltPath::toJSON(const Store & store) const try { co_return TRY_AWAIT(std::visit([&](const auto & buildable) { return buildable.toJSON(store); @@ -117,7 +117,7 @@ try { } -kj::Promise> BuiltPath::toJSON(const Store & store) const +kj::Promise> BuiltPath::toJSON(const Store & store) const try { co_return TRY_AWAIT(std::visit([&](const auto & buildable) { return buildable.toJSON(store); diff --git a/lix/libcmd/built-path.hh b/lix/libcmd/built-path.hh index 0ddf0f5e7..7652269dd 100644 --- a/lix/libcmd/built-path.hh +++ b/lix/libcmd/built-path.hh @@ -17,7 +17,7 @@ struct SingleBuiltPathBuilt { std::string to_string(const Store & store) const; static SingleBuiltPathBuilt parse(const Store & store, std::string_view, std::string_view); - kj::Promise> toJSON(const Store & store) const; + kj::Promise> toJSON(const Store & store) const; DECLARE_CMP(SingleBuiltPathBuilt); }; @@ -45,7 +45,7 @@ struct SingleBuiltPath : built_path::detail::SingleBuiltPathRaw { SingleDerivedPath discardOutputPath() const; static SingleBuiltPath parse(const Store & store, std::string_view); - kj::Promise> toJSON(const Store & store) const; + kj::Promise> toJSON(const Store & store) const; }; static inline ref staticDrv(StorePath drvPath) @@ -64,7 +64,7 @@ struct BuiltPathBuilt { std::string to_string(const Store & store) const; static BuiltPathBuilt parse(const Store & store, std::string_view, std::string_view); - kj::Promise> toJSON(const Store & store) const; + kj::Promise> toJSON(const Store & store) const; DECLARE_CMP(BuiltPathBuilt); }; @@ -94,7 +94,7 @@ struct BuiltPath : built_path::detail::BuiltPathRaw { StorePathSet outPaths() const; kj::Promise> toRealisedPaths(Store & store) const; - kj::Promise> toJSON(const Store & store) const; + kj::Promise> toJSON(const Store & store) const; }; typedef std::vector BuiltPaths; diff --git a/lix/libcmd/cmd-profiles.cc b/lix/libcmd/cmd-profiles.cc index f16d8de93..718f4d296 100644 --- a/lix/libcmd/cmd-profiles.cc +++ b/lix/libcmd/cmd-profiles.cc @@ -111,7 +111,7 @@ ProfileManifest::ProfileManifest(EvalState & state, const Path & profile) auto manifestPath = profile + "/manifest.json"; if (pathExists(manifestPath)) { - auto json = nlohmann::json::parse(readFile(manifestPath)); + auto json = JSON::parse(readFile(manifestPath)); auto version = json.value("version", 0); std::string sUrl; @@ -198,15 +198,15 @@ void ProfileManifest::addElement(ProfileElement element) addElement(finalName, std::move(element)); } -nlohmann::json ProfileManifest::toJSON(Store & store) const +JSON ProfileManifest::toJSON(Store & store) const { - auto es = nlohmann::json::object(); + auto es = JSON::object(); for (auto & [name, element] : elements) { - auto paths = nlohmann::json::array(); + auto paths = JSON::array(); for (auto & path : element.storePaths) { paths.push_back(store.printStorePath(path)); } - nlohmann::json obj; + JSON obj; obj["storePaths"] = paths; obj["active"] = element.active; obj["priority"] = element.priority; @@ -218,7 +218,7 @@ nlohmann::json ProfileManifest::toJSON(Store & store) const } es[name] = obj; } - nlohmann::json json; + JSON json; json["version"] = 3; json["elements"] = es; return json; diff --git a/lix/libcmd/cmd-profiles.hh b/lix/libcmd/cmd-profiles.hh index 265ecafe5..c08370a39 100644 --- a/lix/libcmd/cmd-profiles.hh +++ b/lix/libcmd/cmd-profiles.hh @@ -61,7 +61,7 @@ struct ProfileManifest ProfileManifest(EvalState & state, const Path & profile); - nlohmann::json toJSON(Store & store) const; + JSON toJSON(Store & store) const; kj::Promise> build(ref store); diff --git a/lix/libexpr/eval.cc b/lix/libexpr/eval.cc index 74ea9cc10..7a5b29558 100644 --- a/lix/libexpr/eval.cc +++ b/lix/libexpr/eval.cc @@ -54,8 +54,6 @@ #endif -using json = nlohmann::json; - namespace nix { RootValue allocRootValue(Value * v) @@ -2628,7 +2626,7 @@ void Evaluator::printStatistics() std::fstream fs; if (outPath != "-") fs.open(outPath, std::fstream::out); - json topObj = json::object(); + JSON topObj = JSON::object(); topObj["cpuTime"] = cpuTime; topObj["envs"] = { {"number", mem.nrEnvs}, @@ -2677,9 +2675,9 @@ void Evaluator::printStatistics() topObj["primops"] = stats.primOpCalls; { auto& list = topObj["functions"]; - list = json::array(); + list = JSON::array(); for (auto & [fun, count] : stats.functionCalls) { - json obj = json::object(); + JSON obj = JSON::object(); if (fun->name) obj["name"] = (std::string_view) symbols[fun->name]; else @@ -2696,9 +2694,9 @@ void Evaluator::printStatistics() } { auto list = topObj["attributes"]; - list = json::array(); + list = JSON::array(); for (auto & i : stats.attrSelects) { - json obj = json::object(); + JSON obj = JSON::object(); if (auto pos = positions[i.first]) { if (auto path = std::get_if(&pos.origin)) obj["file"] = path->to_string(); @@ -2713,7 +2711,7 @@ void Evaluator::printStatistics() if (getEnv("NIX_SHOW_SYMBOLS").value_or("0") != "0") { // XXX: overrides earlier assignment - topObj["symbols"] = json::array(); + topObj["symbols"] = JSON::array(); auto &list = topObj["symbols"]; symbols.dump([&](const std::string & s) { list.emplace_back(s); }); } diff --git a/lix/libexpr/flake/config.cc b/lix/libexpr/flake/config.cc index 409e1974c..56e5558e6 100644 --- a/lix/libexpr/flake/config.cc +++ b/lix/libexpr/flake/config.cc @@ -18,7 +18,7 @@ static TrustedList readTrustedList() { auto path = trustedListPath(); if (!pathExists(path)) return {}; - auto json = nlohmann::json::parse(readFile(path)); + auto json = JSON::parse(readFile(path)); return json; } @@ -26,7 +26,7 @@ static void writeTrustedList(const TrustedList & trustedList) { auto path = trustedListPath(); createDirs(dirOf(path)); - writeFile(path, nlohmann::json(trustedList).dump()); + writeFile(path, JSON(trustedList).dump()); } static bool askForSetting( diff --git a/lix/libexpr/flake/lockfile.cc b/lix/libexpr/flake/lockfile.cc index b710a9c90..0e7c45da8 100644 --- a/lix/libexpr/flake/lockfile.cc +++ b/lix/libexpr/flake/lockfile.cc @@ -10,7 +10,7 @@ namespace nix::flake { FlakeRef getFlakeRef( - const nlohmann::json & json, + const JSON & json, const char * attr, const char * info) { @@ -31,7 +31,7 @@ FlakeRef getFlakeRef( throw Error("attribute '%s' missing in lock file", attr); } -LockedNode::LockedNode(const nlohmann::json & json) +LockedNode::LockedNode(const JSON & json) : lockedRef(getFlakeRef(json, "locked", "info")) // FIXME: remove "info" , originalRef(getFlakeRef(json, "original", nullptr)) , isFlake(json.find("flake") != json.end() ? (bool) json["flake"] : true) @@ -67,7 +67,7 @@ std::shared_ptr LockFile::findInput(const InputPath & path) return pos; } -LockFile::LockFile(const nlohmann::json & json, const Path & path) +LockFile::LockFile(const JSON & json, const Path & path) { auto version = json.value("version", 0); if (version < 5 || version > 7) @@ -75,9 +75,9 @@ LockFile::LockFile(const nlohmann::json & json, const Path & path) std::map> nodeMap; - std::function getInputs; + std::function getInputs; - getInputs = [&](Node & node, const nlohmann::json & jsonNode) + getInputs = [&](Node & node, const JSON & jsonNode) { if (jsonNode.find("inputs") == jsonNode.end()) return; for (auto & i : jsonNode["inputs"].items()) { @@ -117,9 +117,9 @@ LockFile::LockFile(const nlohmann::json & json, const Path & path) // a bit since we don't need to worry about cycles. } -nlohmann::json LockFile::toJSON() const +JSON LockFile::toJSON() const { - nlohmann::json nodes; + JSON nodes; std::unordered_map, std::string> nodeKeys; std::unordered_set keys; @@ -143,15 +143,15 @@ nlohmann::json LockFile::toJSON() const nodeKeys.insert_or_assign(node, key); - auto n = nlohmann::json::object(); + auto n = JSON::object(); if (!node->inputs.empty()) { - auto inputs = nlohmann::json::object(); + auto inputs = JSON::object(); for (auto & i : node->inputs) { if (auto child = std::get_if<0>(&i.second)) { inputs[i.first] = dumpNode(i.first, *child); } else if (auto follows = std::get_if<1>(&i.second)) { - auto arr = nlohmann::json::array(); + auto arr = JSON::array(); for (auto & x : *follows) arr.push_back(x); inputs[i.first] = std::move(arr); @@ -172,7 +172,7 @@ nlohmann::json LockFile::toJSON() const return key; }; - nlohmann::json json; + JSON json; json["version"] = 7; json["root"] = dumpNode("root", root); json["nodes"] = std::move(nodes); @@ -191,8 +191,8 @@ LockFile LockFile::read(const Path & path) return LockFile(); } try { - return LockFile(nlohmann::json::parse(readFile(path)), path); - } catch (nlohmann::json::parse_error &nlohmann_json_parse_exc) { + return LockFile(JSON::parse(readFile(path)), path); + } catch (JSON::parse_error &nlohmann_json_parse_exc) { auto json_parse_error = JSONParseError(nlohmann_json_parse_exc.what()); json_parse_error.addTrace(nullptr, "while parsing the lock file at %s", path); throw json_parse_error; diff --git a/lix/libexpr/flake/lockfile.hh b/lix/libexpr/flake/lockfile.hh index cfc6d00dc..b67e68cd0 100644 --- a/lix/libexpr/flake/lockfile.hh +++ b/lix/libexpr/flake/lockfile.hh @@ -44,7 +44,7 @@ struct LockedNode : Node : lockedRef(lockedRef), originalRef(originalRef), isFlake(isFlake) { } - LockedNode(const nlohmann::json & json); + LockedNode(const JSON & json); StorePath computeStorePath(Store & store) const; }; @@ -54,11 +54,11 @@ struct LockFile ref root = make_ref(); LockFile() {}; - LockFile(const nlohmann::json & json, const Path & path); + LockFile(const JSON & json, const Path & path); typedef std::map, std::string> KeyMap; - nlohmann::json toJSON() const; + JSON toJSON() const; std::string to_string() const; diff --git a/lix/libexpr/json-to-value.cc b/lix/libexpr/json-to-value.cc index c8c9402aa..d6ea86ffa 100644 --- a/lix/libexpr/json-to-value.cc +++ b/lix/libexpr/json-to-value.cc @@ -6,13 +6,11 @@ #include #include -using json = nlohmann::json; - namespace nix { // for more information, refer to // https://github.com/nlohmann/json/blob/master/include/nlohmann/detail/input/json_sax.hpp -class JSONSax : nlohmann::json_sax { +class JSONSax : nlohmann::json_sax { class JSONState { protected: std::unique_ptr parent; @@ -175,7 +173,7 @@ public: void parseJSON(EvalState & state, const std::string_view & s_, Value & v) { JSONSax parser(state, v); - bool res = json::sax_parse(s_, &parser); + bool res = JSON::sax_parse(s_, &parser); if (!res) throw JSONParseError("Invalid JSON Value"); } diff --git a/lix/libexpr/nixexpr.cc b/lix/libexpr/nixexpr.cc index cc763e0c8..db1014050 100644 --- a/lix/libexpr/nixexpr.cc +++ b/lix/libexpr/nixexpr.cc @@ -8,8 +8,6 @@ #include #include -using json = nlohmann::json; - namespace nix { ExprBlackHole eBlackHole; @@ -31,15 +29,15 @@ AttrName::AttrName(PosIdx pos, std::unique_ptr e) : pos(pos), expr(std::mo { } -json Expr::toJSON(const SymbolTable & symbols) const +JSON Expr::toJSON(const SymbolTable & symbols) const { abort(); } -json ExprLiteral::toJSON(const SymbolTable & symbols) const +JSON ExprLiteral::toJSON(const SymbolTable & symbols) const { - json valueType; - json value; + JSON valueType; + JSON value; #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wswitch-enum" switch (v.type()) { @@ -71,7 +69,7 @@ json ExprLiteral::toJSON(const SymbolTable & symbols) const }; } -json ExprVar::toJSON(const SymbolTable & symbols) const +JSON ExprVar::toJSON(const SymbolTable & symbols) const { return { {"_type", "ExprVar"}, @@ -79,16 +77,16 @@ json ExprVar::toJSON(const SymbolTable & symbols) const }; } -json ExprInheritFrom::toJSON(SymbolTable const & symbols) const +JSON ExprInheritFrom::toJSON(SymbolTable const & symbols) const { return { {"_type", "ExprInheritFrom"} }; } -json ExprSelect::toJSON(const SymbolTable & symbols) const +JSON ExprSelect::toJSON(const SymbolTable & symbols) const { - json out = { + JSON out = { {"_type", "ExprSelect"}, {"e", e->toJSON(symbols)}, {"attrs", printAttrPathToJson(symbols, attrPath)} @@ -98,7 +96,7 @@ json ExprSelect::toJSON(const SymbolTable & symbols) const return out; } -json ExprOpHasAttr::toJSON(const SymbolTable & symbols) const +JSON ExprOpHasAttr::toJSON(const SymbolTable & symbols) const { return { {"_type", "ExprOpHasAttr"}, @@ -107,7 +105,7 @@ json ExprOpHasAttr::toJSON(const SymbolTable & symbols) const }; } -void ExprAttrs::addBindingsToJSON(json & out, const SymbolTable & symbols) const +void ExprAttrs::addBindingsToJSON(JSON & out, const SymbolTable & symbols) const { typedef const decltype(attrs)::value_type * Attr; std::vector sorted; @@ -135,7 +133,7 @@ void ExprAttrs::addBindingsToJSON(json & out, const SymbolTable & symbols) const } for (const auto & [from, syms] : inheritsFrom) { - json attrs = json::array(); + JSON attrs = JSON::array(); for (auto sym : syms) attrs.push_back(symbols[sym]); out["inheritFrom"].push_back({ @@ -152,9 +150,9 @@ void ExprAttrs::addBindingsToJSON(json & out, const SymbolTable & symbols) const } } -json ExprSet::toJSON(const SymbolTable & symbols) const +JSON ExprSet::toJSON(const SymbolTable & symbols) const { - json out = { + JSON out = { {"_type", "ExprSet"}, {"recursive", recursive}, }; @@ -162,9 +160,9 @@ json ExprSet::toJSON(const SymbolTable & symbols) const return out; } -json ExprList::toJSON(const SymbolTable & symbols) const +JSON ExprList::toJSON(const SymbolTable & symbols) const { - json list = json::array(); + JSON list = JSON::array(); for (auto & i : elems) list.push_back(i->toJSON(symbols)); return { @@ -173,12 +171,12 @@ json ExprList::toJSON(const SymbolTable & symbols) const }; } -void SimplePattern::addBindingsToJSON(nlohmann::json & out, const SymbolTable & symbols) const +void SimplePattern::addBindingsToJSON(JSON & out, const SymbolTable & symbols) const { out["arg"] = symbols[name]; } -void AttrsPattern::addBindingsToJSON(nlohmann::json & out, const SymbolTable & symbols) const +void AttrsPattern::addBindingsToJSON(JSON & out, const SymbolTable & symbols) const { if (name) out["arg"] = symbols[name]; @@ -195,9 +193,9 @@ void AttrsPattern::addBindingsToJSON(nlohmann::json & out, const SymbolTable & s out["formalsEllipsis"] = ellipsis; } -json ExprLambda::toJSON(const SymbolTable & symbols) const +JSON ExprLambda::toJSON(const SymbolTable & symbols) const { - json out = { + JSON out = { { "_type", "ExprLambda" }, { "body", body->toJSON(symbols) } }; @@ -205,9 +203,9 @@ json ExprLambda::toJSON(const SymbolTable & symbols) const return out; } -json ExprCall::toJSON(const SymbolTable & symbols) const +JSON ExprCall::toJSON(const SymbolTable & symbols) const { - json outArgs = json::array(); + JSON outArgs = JSON::array(); for (auto & e : args) outArgs.push_back(e->toJSON(symbols)); return { @@ -217,9 +215,9 @@ json ExprCall::toJSON(const SymbolTable & symbols) const }; } -json ExprLet::toJSON(const SymbolTable & symbols) const +JSON ExprLet::toJSON(const SymbolTable & symbols) const { - json out = { + JSON out = { { "_type", "ExprLet" }, { "body", body->toJSON(symbols) } }; @@ -227,7 +225,7 @@ json ExprLet::toJSON(const SymbolTable & symbols) const return out; } -json ExprWith::toJSON(const SymbolTable & symbols) const +JSON ExprWith::toJSON(const SymbolTable & symbols) const { return { {"_type", "ExprWith"}, @@ -236,7 +234,7 @@ json ExprWith::toJSON(const SymbolTable & symbols) const }; } -json ExprIf::toJSON(const SymbolTable & symbols) const +JSON ExprIf::toJSON(const SymbolTable & symbols) const { return { {"_type", "ExprIf"}, @@ -246,7 +244,7 @@ json ExprIf::toJSON(const SymbolTable & symbols) const }; } -json ExprAssert::toJSON(const SymbolTable & symbols) const +JSON ExprAssert::toJSON(const SymbolTable & symbols) const { return { {"_type", "ExprAssert"}, @@ -255,7 +253,7 @@ json ExprAssert::toJSON(const SymbolTable & symbols) const }; } -json ExprOpNot::toJSON(const SymbolTable & symbols) const +JSON ExprOpNot::toJSON(const SymbolTable & symbols) const { return { {"_type", "ExprOpNot"}, @@ -263,9 +261,9 @@ json ExprOpNot::toJSON(const SymbolTable & symbols) const }; } -json ExprConcatStrings::toJSON(const SymbolTable & symbols) const +JSON ExprConcatStrings::toJSON(const SymbolTable & symbols) const { - json parts = json::array(); + JSON parts = JSON::array(); for (auto & [_pos, part] : es) parts.push_back(part->toJSON(symbols)); return { @@ -275,7 +273,7 @@ json ExprConcatStrings::toJSON(const SymbolTable & symbols) const }; } -json ExprPos::toJSON(const SymbolTable & symbols) const +JSON ExprPos::toJSON(const SymbolTable & symbols) const { return {{ "_type", "ExprPos" }}; } @@ -295,9 +293,9 @@ std::string showAttrPath(const SymbolTable & symbols, const AttrPath & attrPath) return out.str(); } -json printAttrPathToJson(const SymbolTable & symbols, const AttrPath & attrPath) +JSON printAttrPathToJson(const SymbolTable & symbols, const AttrPath & attrPath) { - json out = json::array(); + JSON out = JSON::array(); for (auto & i : attrPath) { if (i.symbol) out.push_back(symbols[i.symbol]); diff --git a/lix/libexpr/nixexpr.hh b/lix/libexpr/nixexpr.hh index 3a6b05fd1..e4de3a731 100644 --- a/lix/libexpr/nixexpr.hh +++ b/lix/libexpr/nixexpr.hh @@ -38,7 +38,7 @@ struct AttrName typedef std::vector AttrPath; std::string showAttrPath(const SymbolTable & symbols, const AttrPath & attrPath); -nlohmann::json printAttrPathToJson(const SymbolTable & symbols, const AttrPath & attrPath); +JSON printAttrPathToJson(const SymbolTable & symbols, const AttrPath & attrPath); /* Abstract syntax of Nix expressions. */ @@ -62,7 +62,7 @@ public: Expr & operator=(const Expr &) = delete; virtual ~Expr() { }; - virtual nlohmann::json toJSON(const SymbolTable & symbols) const; + virtual JSON toJSON(const SymbolTable & symbols) const; virtual void bindVars(Evaluator & es, const std::shared_ptr & env); virtual void eval(EvalState & state, Env & env, Value & v); virtual Value * maybeThunk(EvalState & state, Env & env); @@ -71,7 +71,7 @@ public: }; #define COMMON_METHODS \ - nlohmann::json toJSON(const SymbolTable & symbols) const override; \ + JSON toJSON(const SymbolTable & symbols) const override; \ void eval(EvalState & state, Env & env, Value & v) override; \ void bindVars(Evaluator & es, const std::shared_ptr & env) override; @@ -153,7 +153,7 @@ struct ExprInheritFrom : ExprVar this->fromWith = nullptr; } - nlohmann::json toJSON(SymbolTable const & symbols) const override; + JSON toJSON(SymbolTable const & symbols) const override; void bindVars(Evaluator & es, const std::shared_ptr & env) override; }; @@ -240,7 +240,7 @@ struct ExprAttrs std::shared_ptr bindInheritSources( Evaluator & es, const std::shared_ptr & env); Env * buildInheritFromEnv(EvalState & state, Env & up); - void addBindingsToJSON(nlohmann::json & out, const SymbolTable & symbols) const; + void addBindingsToJSON(JSON & out, const SymbolTable & symbols) const; }; struct ExprSet : Expr, ExprAttrs { @@ -272,7 +272,7 @@ struct Pattern { virtual void bindVars(Evaluator & es, const std::shared_ptr & env) = 0; virtual Env & match(ExprLambda & lambda, EvalState & state, Env & up, Value * arg, const PosIdx pos) = 0; - virtual void addBindingsToJSON(nlohmann::json & out, const SymbolTable & symbols) const = 0; + virtual void addBindingsToJSON(JSON & out, const SymbolTable & symbols) const = 0; }; /** A plain old lambda */ @@ -287,7 +287,7 @@ struct SimplePattern : Pattern virtual void bindVars(Evaluator & es, const std::shared_ptr & env) override; virtual Env & match(ExprLambda & lambda, EvalState & state, Env & up, Value * arg, const PosIdx pos) override; - virtual void addBindingsToJSON(nlohmann::json & out, const SymbolTable & symbols) const override; + virtual void addBindingsToJSON(JSON & out, const SymbolTable & symbols) const override; }; /** Attribute set destructuring in arguments of a lambda, if present */ @@ -308,7 +308,7 @@ struct AttrsPattern : Pattern virtual void bindVars(Evaluator & es, const std::shared_ptr & env) override; virtual Env & match(ExprLambda & lambda, EvalState & state, Env & up, Value * arg, const PosIdx pos) override; - virtual void addBindingsToJSON(nlohmann::json & out, const SymbolTable & symbols) const override; + virtual void addBindingsToJSON(JSON & out, const SymbolTable & symbols) const override; bool has(Symbol arg) const { @@ -423,7 +423,7 @@ struct ExprOpNot : Expr std::unique_ptr e1, e2; \ name(std::unique_ptr e1, std::unique_ptr e2) : e1(std::move(e1)), e2(std::move(e2)) { }; \ name(const PosIdx & pos, std::unique_ptr e1, std::unique_ptr e2) : Expr(pos), e1(std::move(e1)), e2(std::move(e2)) { }; \ - nlohmann::json toJSON(const SymbolTable & symbols) const override \ + JSON toJSON(const SymbolTable & symbols) const override \ { \ return { \ {"_type", #name}, \ diff --git a/lix/libexpr/primops.cc b/lix/libexpr/primops.cc index 466ee2fcc..d33bd4d47 100644 --- a/lix/libexpr/primops.cc +++ b/lix/libexpr/primops.cc @@ -800,15 +800,14 @@ static void derivationStrictInternal(EvalState & state, const std::string & drvName, Bindings * attrs, Value & v) { /* Check whether attributes should be passed as a JSON file. */ - using nlohmann::json; - std::optional jsonObject; + std::optional jsonObject; auto pos = v.determinePos(noPos); auto attr = attrs->find(state.ctx.s.structuredAttrs); if (attr != attrs->end() && state.forceBool(*attr->value, pos, "while evaluating the `__structuredAttrs` " "attribute passed to builtins.derivationStrict")) - jsonObject = json::object(); + jsonObject = JSON::object(); /* Check whether null attributes should be ignored. */ bool ignoreNulls = false; diff --git a/lix/libexpr/value-to-json.cc b/lix/libexpr/value-to-json.cc index 96bec3e41..e996032a0 100644 --- a/lix/libexpr/value-to-json.cc +++ b/lix/libexpr/value-to-json.cc @@ -9,15 +9,14 @@ namespace nix { -using json = nlohmann::json; -json printValueAsJSON(EvalState & state, bool strict, +JSON printValueAsJSON(EvalState & state, bool strict, Value & v, const PosIdx pos, NixStringContext & context, bool copyToStore) { checkInterrupt(); if (strict) state.forceValue(v, pos); - json out; + JSON out; switch (v.type()) { @@ -56,7 +55,7 @@ json printValueAsJSON(EvalState & state, bool strict, } auto i = v.attrs->find(state.ctx.s.outPath); if (i == v.attrs->end()) { - out = json::object(); + out = JSON::object(); StringSet names; for (auto & j : *v.attrs) names.emplace(state.ctx.symbols[j.name]); @@ -76,7 +75,7 @@ json printValueAsJSON(EvalState & state, bool strict, } case nList: { - out = json::array(); + out = JSON::array(); int i = 0; for (auto elem : v.listItems()) { try { @@ -117,7 +116,7 @@ void printValueAsJSON(EvalState & state, bool strict, str << printValueAsJSON(state, strict, v, pos, context, copyToStore); } -json ExternalValueBase::printValueAsJSON(EvalState & state, bool strict, +JSON ExternalValueBase::printValueAsJSON(EvalState & state, bool strict, NixStringContext & context, bool copyToStore) const { state.ctx.errors.make("cannot convert %1% to JSON", showType()) diff --git a/lix/libexpr/value-to-json.hh b/lix/libexpr/value-to-json.hh index b1f914110..c08f268b5 100644 --- a/lix/libexpr/value-to-json.hh +++ b/lix/libexpr/value-to-json.hh @@ -10,7 +10,7 @@ namespace nix { -nlohmann::json printValueAsJSON(EvalState & state, bool strict, +JSON printValueAsJSON(EvalState & state, bool strict, Value & v, const PosIdx pos, NixStringContext & context, bool copyToStore = true); void printValueAsJSON(EvalState & state, bool strict, diff --git a/lix/libexpr/value.hh b/lix/libexpr/value.hh index 0b42c5768..03b6c67ad 100644 --- a/lix/libexpr/value.hh +++ b/lix/libexpr/value.hh @@ -118,7 +118,7 @@ class ExternalValueBase /** * Print the value as JSON. Defaults to unconvertable, i.e. throws an error */ - virtual nlohmann::json printValueAsJSON(EvalState & state, bool strict, + virtual JSON printValueAsJSON(EvalState & state, bool strict, NixStringContext & context, bool copyToStore = true) const; /** diff --git a/lix/libfetchers/attrs.cc b/lix/libfetchers/attrs.cc index 66f7af1ad..139919b71 100644 --- a/lix/libfetchers/attrs.cc +++ b/lix/libfetchers/attrs.cc @@ -4,7 +4,7 @@ namespace nix::fetchers { -Attrs jsonToAttrs(const nlohmann::json & json) +Attrs jsonToAttrs(const JSON & json) { Attrs attrs; @@ -22,9 +22,9 @@ Attrs jsonToAttrs(const nlohmann::json & json) return attrs; } -nlohmann::json attrsToJSON(const Attrs & attrs) +JSON attrsToJSON(const Attrs & attrs) { - nlohmann::json json; + JSON json; for (auto & attr : attrs) { if (auto v = std::get_if(&attr.second)) { json[attr.first] = *v; diff --git a/lix/libfetchers/attrs.hh b/lix/libfetchers/attrs.hh index cfa64b3e3..f987bedba 100644 --- a/lix/libfetchers/attrs.hh +++ b/lix/libfetchers/attrs.hh @@ -14,9 +14,9 @@ namespace nix::fetchers { typedef std::variant> Attr; typedef std::map Attrs; -Attrs jsonToAttrs(const nlohmann::json & json); +Attrs jsonToAttrs(const JSON & json); -nlohmann::json attrsToJSON(const Attrs & attrs); +JSON attrsToJSON(const Attrs & attrs); std::optional maybeGetStrAttr(const Attrs & attrs, const std::string & name); diff --git a/lix/libfetchers/cache.cc b/lix/libfetchers/cache.cc index c3cbff33c..b02607d3b 100644 --- a/lix/libfetchers/cache.cc +++ b/lix/libfetchers/cache.cc @@ -121,7 +121,7 @@ struct CacheImpl : Cache co_return LookupResult { .expired = !locked && (settings.tarballTtl.get() == 0 || timestamp + settings.tarballTtl < time(0)), - .infoAttrs = jsonToAttrs(nlohmann::json::parse(infoJSON)), + .infoAttrs = jsonToAttrs(JSON::parse(infoJSON)), .storePath = std::move(storePath) }; } catch (...) { diff --git a/lix/libfetchers/fetch-settings.cc b/lix/libfetchers/fetch-settings.cc index 5f4470ff1..b48236193 100644 --- a/lix/libfetchers/fetch-settings.cc +++ b/lix/libfetchers/fetch-settings.cc @@ -6,7 +6,7 @@ namespace nix { -void to_json(nlohmann::json & j, const AcceptFlakeConfig & e) +void to_json(JSON & j, const AcceptFlakeConfig & e) { if (e == AcceptFlakeConfig::False) { j = false; @@ -19,7 +19,7 @@ void to_json(nlohmann::json & j, const AcceptFlakeConfig & e) } } -void from_json(const nlohmann::json & j, AcceptFlakeConfig & e) +void from_json(const JSON & j, AcceptFlakeConfig & e) { if (j == false) { e = AcceptFlakeConfig::False; diff --git a/lix/libfetchers/fetch-settings.hh b/lix/libfetchers/fetch-settings.hh index c0ad3c09e..a69545020 100644 --- a/lix/libfetchers/fetch-settings.hh +++ b/lix/libfetchers/fetch-settings.hh @@ -13,8 +13,8 @@ namespace nix { enum class AcceptFlakeConfig { False, Ask, True }; -void to_json(nlohmann::json & j, const AcceptFlakeConfig & e); -void from_json(const nlohmann::json & j, AcceptFlakeConfig & e); +void to_json(JSON & j, const AcceptFlakeConfig & e); +void from_json(const JSON & j, AcceptFlakeConfig & e); struct FetchSettings : public Config { diff --git a/lix/libfetchers/github.cc b/lix/libfetchers/github.cc index 991811450..c52e78e2d 100644 --- a/lix/libfetchers/github.cc +++ b/lix/libfetchers/github.cc @@ -278,7 +278,7 @@ struct GitHubInputScheme : GitArchiveInputScheme Headers headers = makeHeadersWithAuthTokens(host); - auto json = nlohmann::json::parse(readFile(store->toRealPath( + auto json = JSON::parse(readFile(store->toRealPath( TRY_AWAIT(downloadFile(store, url, "source", false, headers)).storePath ))); auto rev = Hash::parseAny(std::string { json["sha"] }, HashType::SHA1); @@ -359,7 +359,7 @@ struct GitLabInputScheme : GitArchiveInputScheme Headers headers = makeHeadersWithAuthTokens(host); - auto json = nlohmann::json::parse(readFile(store->toRealPath( + auto json = JSON::parse(readFile(store->toRealPath( TRY_AWAIT(downloadFile(store, url, "source", false, headers)).storePath ))); if (json.is_array() && json.size() >= 1 && json[0]["id"] != nullptr) { diff --git a/lix/libfetchers/registry.cc b/lix/libfetchers/registry.cc index 1f7b93cfe..cb353028f 100644 --- a/lix/libfetchers/registry.cc +++ b/lix/libfetchers/registry.cc @@ -30,7 +30,7 @@ std::shared_ptr Registry::read( try { - auto json = nlohmann::json::parse(readFile(path)); + auto json = JSON::parse(readFile(path)); auto version = json.value("version", 0); @@ -57,7 +57,7 @@ std::shared_ptr Registry::read( else throw Error("flake registry '%s' has unsupported version %d", path, version); - } catch (nlohmann::json::exception & e) { + } catch (JSON::exception & e) { warn("cannot parse flake registry '%s': %s", path, e.what()); } catch (Error & e) { warn("cannot read flake registry '%s': %s", path, e.what()); @@ -68,9 +68,9 @@ std::shared_ptr Registry::read( void Registry::write(const Path & path) { - nlohmann::json arr; + JSON arr; for (auto & entry : entries) { - nlohmann::json obj; + JSON obj; obj["from"] = attrsToJSON(entry.from.toAttrs()); obj["to"] = attrsToJSON(entry.to.toAttrs()); if (!entry.extraAttrs.empty()) @@ -80,7 +80,7 @@ void Registry::write(const Path & path) arr.emplace_back(std::move(obj)); } - nlohmann::json json; + JSON json; json["version"] = 2; json["flakes"] = std::move(arr); diff --git a/lix/libstore/binary-cache-store.cc b/lix/libstore/binary-cache-store.cc index 0b3893935..f049e6ac2 100644 --- a/lix/libstore/binary-cache-store.cc +++ b/lix/libstore/binary-cache-store.cc @@ -172,7 +172,7 @@ try { /* Optionally write a JSON file containing a listing of the contents of the NAR. */ if (config().writeNARListing) { - nlohmann::json j = { + JSON j = { {"version", 1}, {"root", listNar(narIndex)}, }; @@ -200,7 +200,7 @@ try { auto doFile = [&](std::string member, std::string key, std::string target) { checkInterrupt(); - nlohmann::json json; + JSON json; json["archive"] = target; json["member"] = member; @@ -511,7 +511,7 @@ try { if (!data) co_return result::success(nullptr); auto realisation = Realisation::fromJSON( - nlohmann::json::parse(*data), outputInfoFilePath); + JSON::parse(*data), outputInfoFilePath); co_return std::make_shared(realisation); } catch (...) { co_return result::current_exception(); diff --git a/lix/libstore/build/derivation-goal.cc b/lix/libstore/build/derivation-goal.cc index 6773f8a10..6896b6ef7 100644 --- a/lix/libstore/build/derivation-goal.cc +++ b/lix/libstore/build/derivation-goal.cc @@ -1511,11 +1511,11 @@ try { // We want to get the same lines in case of remote builds. // The format is: // @nix { "action": "setPhase", "phase": "$curPhase" } - const auto logLine = nlohmann::json::object({ + const auto logLine = JSON::object({ {"action", "setPhase"}, {"phase", phase} }); - (*logSink)("@nix " + logLine.dump(-1, ' ', false, nlohmann::json::error_handler_t::replace) + "\n"); + (*logSink)("@nix " + logLine.dump(-1, ' ', false, JSON::error_handler_t::replace) + "\n"); } } } diff --git a/lix/libstore/build/local-derivation-goal.cc b/lix/libstore/build/local-derivation-goal.cc index 869cecec3..48868105e 100644 --- a/lix/libstore/build/local-derivation-goal.cc +++ b/lix/libstore/build/local-derivation-goal.cc @@ -953,8 +953,8 @@ try { TRY_AWAIT(parsedDrv->prepareStructuredAttrs(worker.store, inputPaths))) { auto json = structAttrsJson.value(); - nlohmann::json rewritten; - for (auto & [i, v] : json["outputs"].get()) { + JSON rewritten; + for (auto & [i, v] : json["outputs"].get()) { /* The placeholder must have a rewrite, so we use it to cover both the cases where we know or don't know the output path ahead of time. */ rewritten[i] = rewriteStrings((std::string) v, inputRewrites); diff --git a/lix/libstore/common-protocol.cc b/lix/libstore/common-protocol.cc index 55b8c8a2b..fa65d4376 100644 --- a/lix/libstore/common-protocol.cc +++ b/lix/libstore/common-protocol.cc @@ -47,7 +47,7 @@ Realisation CommonProto::Serialise::read(const Store & store, Commo { std::string rawInput = readString(conn.from); return Realisation::fromJSON( - nlohmann::json::parse(rawInput), + JSON::parse(rawInput), "remote-protocol" ); } diff --git a/lix/libstore/derivations.cc b/lix/libstore/derivations.cc index 280244ddb..8ab203519 100644 --- a/lix/libstore/derivations.cc +++ b/lix/libstore/derivations.cc @@ -1250,10 +1250,10 @@ try { const Hash impureOutputHash = hashString(HashType::SHA256, "impure"); -nlohmann::json DerivationOutput::toJSON( +JSON DerivationOutput::toJSON( const Store & store, std::string_view drvName, OutputNameView outputName) const { - nlohmann::json res = nlohmann::json::object(); + JSON res = JSON::object(); std::visit(overloaded { [&](const DerivationOutput::InputAddressed & doi) { res["path"] = store.printStorePath(doi.path); @@ -1279,12 +1279,12 @@ nlohmann::json DerivationOutput::toJSON( DerivationOutput DerivationOutput::fromJSON( const Store & store, std::string_view drvName, OutputNameView outputName, - const nlohmann::json & _json, + const JSON & _json, const ExperimentalFeatureSettings & xpSettings) { std::set keys; ensureType(_json, nlohmann::detail::value_t::object); - auto json = (std::map) _json; + auto json = (std::map) _json; for (const auto & [key, _] : json) keys.insert(key); @@ -1347,15 +1347,15 @@ DerivationOutput DerivationOutput::fromJSON( } -nlohmann::json Derivation::toJSON(const Store & store) const +JSON Derivation::toJSON(const Store & store) const { - nlohmann::json res = nlohmann::json::object(); + JSON res = JSON::object(); res["name"] = name; { - nlohmann::json & outputsObj = res["outputs"]; - outputsObj = nlohmann::json::object(); + JSON & outputsObj = res["outputs"]; + outputsObj = JSON::object(); for (auto & [outputName, output] : outputs) { outputsObj[outputName] = output.toJSON(store, name, outputName); } @@ -1363,18 +1363,18 @@ nlohmann::json Derivation::toJSON(const Store & store) const { auto& inputsList = res["inputSrcs"]; - inputsList = nlohmann::json ::array(); + inputsList = JSON ::array(); for (auto & input : inputSrcs) inputsList.emplace_back(store.printStorePath(input)); } { - std::function::ChildNode &)> doInput; + std::function::ChildNode &)> doInput; doInput = [&](const auto & inputNode) { - auto value = nlohmann::json::object(); + auto value = JSON::object(); value["outputs"] = inputNode.value; { - auto next = nlohmann::json::object(); + auto next = JSON::object(); for (auto & [outputId, childNode] : inputNode.childMap) next[outputId] = doInput(childNode); value["dynamicOutputs"] = std::move(next); @@ -1383,7 +1383,7 @@ nlohmann::json Derivation::toJSON(const Store & store) const }; { auto& inputDrvsObj = res["inputDrvs"]; - inputDrvsObj = nlohmann::json::object(); + inputDrvsObj = JSON::object(); for (auto & [inputDrv, inputNode] : inputDrvs.map) { inputDrvsObj[store.printStorePath(inputDrv)] = doInput(inputNode); } @@ -1401,7 +1401,7 @@ nlohmann::json Derivation::toJSON(const Store & store) const Derivation Derivation::fromJSON( const Store & store, - const nlohmann::json & json, + const JSON & json, const ExperimentalFeatureSettings & xpSettings) { using nlohmann::detail::value_t; @@ -1434,7 +1434,7 @@ Derivation Derivation::fromJSON( } try { - std::function::ChildNode(const nlohmann::json &)> doInput; + std::function::ChildNode(const JSON &)> doInput; doInput = [&](const auto & json) { DerivedPathMap::ChildNode node; node.value = static_cast( diff --git a/lix/libstore/derivations.hh b/lix/libstore/derivations.hh index c4b126267..6e2d4f341 100644 --- a/lix/libstore/derivations.hh +++ b/lix/libstore/derivations.hh @@ -136,7 +136,7 @@ struct DerivationOutput */ std::optional path(const Store & store, std::string_view drvName, OutputNameView outputName) const; - nlohmann::json toJSON( + JSON toJSON( const Store & store, std::string_view drvName, OutputNameView outputName) const; @@ -147,7 +147,7 @@ struct DerivationOutput const Store & store, std::string_view drvName, OutputNameView outputName, - const nlohmann::json & json, + const JSON & json, const ExperimentalFeatureSettings & xpSettings = experimentalFeatureSettings); }; @@ -368,10 +368,10 @@ struct Derivation : BasicDerivation Derivation(const BasicDerivation & bd) : BasicDerivation(bd) { } Derivation(BasicDerivation && bd) : BasicDerivation(std::move(bd)) { } - nlohmann::json toJSON(const Store & store) const; + JSON toJSON(const Store & store) const; static Derivation fromJSON( const Store & store, - const nlohmann::json & json, + const JSON & json, const ExperimentalFeatureSettings & xpSettings = experimentalFeatureSettings); GENERATE_CMP(Derivation, diff --git a/lix/libstore/derived-path.cc b/lix/libstore/derived-path.cc index 9ca5e1c0e..ff34d719f 100644 --- a/lix/libstore/derived-path.cc +++ b/lix/libstore/derived-path.cc @@ -27,16 +27,16 @@ CMP(SingleDerivedPath, DerivedPathBuilt, outputs) #undef CMP #undef CMP_ONE -kj::Promise> DerivedPath::Opaque::toJSON(const Store & store) const +kj::Promise> DerivedPath::Opaque::toJSON(const Store & store) const try { return {store.printStorePath(path)}; } catch (...) { return {result::current_exception()}; } -kj::Promise> SingleDerivedPath::Built::toJSON(Store & store) const +kj::Promise> SingleDerivedPath::Built::toJSON(Store & store) const try { - nlohmann::json res; + JSON res; res["drvPath"] = TRY_AWAIT(drvPath->toJSON(store)); // Fallback for the input-addressed derivation case: We expect to always be // able to print the output paths, so let’s do it @@ -57,9 +57,9 @@ try { co_return result::current_exception(); } -kj::Promise> DerivedPath::Built::toJSON(Store & store) const +kj::Promise> DerivedPath::Built::toJSON(Store & store) const try { - nlohmann::json res; + JSON res; res["drvPath"] = TRY_AWAIT(drvPath->toJSON(store)); // Fallback for the input-addressed derivation case: We expect to always be // able to print the output paths, so let’s do it @@ -79,7 +79,7 @@ try { co_return result::current_exception(); } -kj::Promise> SingleDerivedPath::toJSON(Store & store) const +kj::Promise> SingleDerivedPath::toJSON(Store & store) const try { co_return TRY_AWAIT(std::visit([&](const auto & buildable) { return buildable.toJSON(store); @@ -88,7 +88,7 @@ try { co_return result::current_exception(); } -kj::Promise> DerivedPath::toJSON(Store & store) const +kj::Promise> DerivedPath::toJSON(Store & store) const try { co_return TRY_AWAIT(std::visit([&](const auto & buildable) { return buildable.toJSON(store); diff --git a/lix/libstore/derived-path.hh b/lix/libstore/derived-path.hh index a1bcb1b0f..a4cf26f1a 100644 --- a/lix/libstore/derived-path.hh +++ b/lix/libstore/derived-path.hh @@ -28,7 +28,7 @@ struct DerivedPathOpaque { std::string to_string(const Store & store) const; static DerivedPathOpaque parse(const Store & store, std::string_view); - kj::Promise> toJSON(const Store & store) const; + kj::Promise> toJSON(const Store & store) const; GENERATE_CMP(DerivedPathOpaque, me->path); }; @@ -75,7 +75,7 @@ struct SingleDerivedPathBuilt { const Store & store, ref drvPath, OutputNameView outputs, const ExperimentalFeatureSettings & xpSettings = experimentalFeatureSettings); - kj::Promise> toJSON(Store & store) const; + kj::Promise> toJSON(Store & store) const; DECLARE_CMP(SingleDerivedPathBuilt); }; @@ -147,7 +147,7 @@ struct SingleDerivedPath : derived_path::detail::SingleDerivedPathRaw { const Store & store, std::string_view, const ExperimentalFeatureSettings & xpSettings = experimentalFeatureSettings); - kj::Promise> toJSON(Store & store) const; + kj::Promise> toJSON(Store & store) const; }; static inline ref makeConstantStorePathRef(StorePath drvPath) @@ -200,7 +200,7 @@ struct DerivedPathBuilt { const Store & store, ref, std::string_view, const ExperimentalFeatureSettings & xpSettings = experimentalFeatureSettings); - kj::Promise> toJSON(Store & store) const; + kj::Promise> toJSON(Store & store) const; DECLARE_CMP(DerivedPathBuilt); }; @@ -277,7 +277,7 @@ struct DerivedPath : derived_path::detail::DerivedPathRaw { */ static DerivedPath fromSingle(const SingleDerivedPath &); - kj::Promise> toJSON(Store & store) const; + kj::Promise> toJSON(Store & store) const; }; typedef std::vector DerivedPaths; diff --git a/lix/libstore/globals.cc b/lix/libstore/globals.cc index d0d9ef548..9221da32b 100644 --- a/lix/libstore/globals.cc +++ b/lix/libstore/globals.cc @@ -268,7 +268,7 @@ Path Settings::getDefaultSSLCertFile() const std::string nixVersion = PACKAGE_VERSION; -void to_json(nlohmann::json & j, const SandboxMode & e) +void to_json(JSON & j, const SandboxMode & e) { if (e == SandboxMode::smEnabled) { j = true; @@ -281,7 +281,7 @@ void to_json(nlohmann::json & j, const SandboxMode & e) } } -void from_json(const nlohmann::json & j, SandboxMode & e) +void from_json(const JSON & j, SandboxMode & e) { if (j == true) { e = SandboxMode::smEnabled; diff --git a/lix/libstore/globals.hh b/lix/libstore/globals.hh index c5e149233..5a7a24aca 100644 --- a/lix/libstore/globals.hh +++ b/lix/libstore/globals.hh @@ -14,8 +14,8 @@ namespace nix { typedef enum { smEnabled, smRelaxed, smDisabled } SandboxMode; -void to_json(nlohmann::json & j, const SandboxMode & e); -void from_json(const nlohmann::json & j, SandboxMode & e); +void to_json(JSON & j, const SandboxMode & e); +void from_json(const JSON & j, SandboxMode & e); struct MaxBuildJobsSetting : public BaseSetting { diff --git a/lix/libstore/nar-accessor.cc b/lix/libstore/nar-accessor.cc index 96203e320..097f00f60 100644 --- a/lix/libstore/nar-accessor.cc +++ b/lix/libstore/nar-accessor.cc @@ -30,11 +30,10 @@ struct NarAccessor : public FSAccessor : getNarBytes(getNarBytes) { using namespace nar_index; - using json = nlohmann::json; - std::function recurse; + std::function recurse; - recurse = [&](Entry & member, json & v) { + recurse = [&](Entry & member, JSON & v) { std::string type = v["type"]; if (type == "directory") { @@ -51,7 +50,7 @@ struct NarAccessor : public FSAccessor } else return; }; - json v = json::parse(listing); + JSON v = JSON::parse(listing); recurse(root, v); } @@ -166,12 +165,11 @@ ref makeLazyNarAccessor(const std::string & listing, return make_ref(listing, getNarBytes); } -using nlohmann::json; -kj::Promise> listNar(ref accessor, const Path & path, bool recurse) +kj::Promise> listNar(ref accessor, const Path & path, bool recurse) try { auto st = TRY_AWAIT(accessor->stat(path)); - json obj = json::object(); + JSON obj = JSON::object(); switch (st.type) { case FSAccessor::Type::tRegular: @@ -185,13 +183,13 @@ try { case FSAccessor::Type::tDirectory: obj["type"] = "directory"; { - obj["entries"] = json::object(); - json &res2 = obj["entries"]; + obj["entries"] = JSON::object(); + JSON &res2 = obj["entries"]; for (auto & name : TRY_AWAIT(accessor->readDirectory(path))) { if (recurse) { res2[name] = TRY_AWAIT(listNar(accessor, path + "/" + name, true)); } else - res2[name] = json::object(); + res2[name] = JSON::object(); } } break; @@ -208,9 +206,9 @@ try { co_return result::current_exception(); } -static nlohmann::json listNar(const nar_index::Entry & e, Path path) +static JSON listNar(const nar_index::Entry & e, Path path) { - json obj = json::object(); + JSON obj = JSON::object(); auto handlers = overloaded{ [&](const nar_index::File & f) { @@ -227,8 +225,8 @@ static nlohmann::json listNar(const nar_index::Entry & e, Path path) }, [&](const nar_index::Directory & d) { obj["type"] = "directory"; - obj["entries"] = json::object(); - json & res2 = obj["entries"]; + obj["entries"] = JSON::object(); + JSON & res2 = obj["entries"]; for (auto & [name, entry] : d.contents) { res2[name] = listNar(entry, path + "/" + name); } @@ -239,7 +237,7 @@ static nlohmann::json listNar(const nar_index::Entry & e, Path path) return obj; } -nlohmann::json listNar(const nar_index::Entry & nar) +JSON listNar(const nar_index::Entry & nar) { return listNar(nar, ""); } diff --git a/lix/libstore/nar-accessor.hh b/lix/libstore/nar-accessor.hh index f3e873af4..ce4023faa 100644 --- a/lix/libstore/nar-accessor.hh +++ b/lix/libstore/nar-accessor.hh @@ -36,8 +36,8 @@ ref makeLazyNarAccessor( * Write a JSON representation of the contents of a NAR (except file * contents). */ -kj::Promise> +kj::Promise> listNar(ref accessor, const Path & path, bool recurse); -nlohmann::json listNar(const nar_index::Entry & nar); +JSON listNar(const nar_index::Entry & nar); } diff --git a/lix/libstore/nar-info-disk-cache.cc b/lix/libstore/nar-info-disk-cache.cc index ebda95f6b..444dfa58c 100644 --- a/lix/libstore/nar-info-disk-cache.cc +++ b/lix/libstore/nar-info-disk-cache.cc @@ -306,7 +306,7 @@ public: auto realisation = std::make_shared(Realisation::fromJSON( - nlohmann::json::parse(queryRealisation.getStr(0)), + JSON::parse(queryRealisation.getStr(0)), "Local disk cache")); return {oValid, realisation}; diff --git a/lix/libstore/outputs-spec.cc b/lix/libstore/outputs-spec.cc index 2b0a7e758..da56851e5 100644 --- a/lix/libstore/outputs-spec.cc +++ b/lix/libstore/outputs-spec.cc @@ -153,7 +153,7 @@ namespace nlohmann { using namespace nix; -OutputsSpec adl_serializer::from_json(const json & json) { +OutputsSpec adl_serializer::from_json(const JSON & json) { auto names = json.get(); if (names == StringSet({"*"})) return OutputsSpec::All {}; @@ -161,7 +161,7 @@ OutputsSpec adl_serializer::from_json(const json & json) { return OutputsSpec::Names { std::move(names) }; } -void adl_serializer::to_json(json & json, OutputsSpec t) { +void adl_serializer::to_json(JSON & json, OutputsSpec t) { std::visit(overloaded { [&](const OutputsSpec::All &) { json = std::vector({"*"}); @@ -173,7 +173,7 @@ void adl_serializer::to_json(json & json, OutputsSpec t) { } -ExtendedOutputsSpec adl_serializer::from_json(const json & json) { +ExtendedOutputsSpec adl_serializer::from_json(const JSON & json) { if (json.is_null()) return ExtendedOutputsSpec::Default {}; else { @@ -181,7 +181,7 @@ ExtendedOutputsSpec adl_serializer::from_json(const json & } } -void adl_serializer::to_json(json & json, ExtendedOutputsSpec t) { +void adl_serializer::to_json(JSON & json, ExtendedOutputsSpec t) { std::visit(overloaded { [&](const ExtendedOutputsSpec::Default &) { json = nullptr; diff --git a/lix/libstore/parsed-derivations.cc b/lix/libstore/parsed-derivations.cc index e7a12d92e..319a70f0b 100644 --- a/lix/libstore/parsed-derivations.cc +++ b/lix/libstore/parsed-derivations.cc @@ -14,7 +14,7 @@ ParsedDerivation::ParsedDerivation(const StorePath & drvPath, BasicDerivation & auto jsonAttr = drv.env.find("__json"); if (jsonAttr != drv.env.end()) { try { - structuredAttrs = std::make_unique(nlohmann::json::parse(jsonAttr->second)); + structuredAttrs = std::make_unique(JSON::parse(jsonAttr->second)); } catch (std::exception & e) { throw Error("cannot process __json attribute of '%s': %s", drvPath.to_string(), e.what()); } @@ -134,7 +134,7 @@ bool ParsedDerivation::useUidRange() const static std::regex shVarName("[A-Za-z_][A-Za-z0-9_]*"); -kj::Promise>> +kj::Promise>> ParsedDerivation::prepareStructuredAttrs(Store & store, const StorePathSet & inputPaths) try { auto structuredAttrs = getStructuredAttrs(); @@ -143,7 +143,7 @@ try { auto json = *structuredAttrs; /* Add an "outputs" object containing the output paths. */ - nlohmann::json outputs; + JSON outputs; for (auto & i : drv.outputs) outputs[i.first] = hashPlaceholder(i.first); json["outputs"] = outputs; @@ -171,10 +171,10 @@ try { namely, strings, integers, nulls, Booleans, and arrays and objects consisting entirely of those values. (So nested arrays or objects are not supported.) */ -std::string writeStructuredAttrsShell(const nlohmann::json & json) +std::string writeStructuredAttrsShell(const JSON & json) { - auto handleSimpleType = [](const nlohmann::json & value) -> std::optional { + auto handleSimpleType = [](const JSON & value) -> std::optional { if (value.is_string()) return shellEscape(value.get()); diff --git a/lix/libstore/parsed-derivations.hh b/lix/libstore/parsed-derivations.hh index 2f51921ce..e91eddeef 100644 --- a/lix/libstore/parsed-derivations.hh +++ b/lix/libstore/parsed-derivations.hh @@ -11,7 +11,7 @@ class ParsedDerivation { StorePath drvPath; BasicDerivation & drv; - std::unique_ptr structuredAttrs; + std::unique_ptr structuredAttrs; public: @@ -19,7 +19,7 @@ public: ~ParsedDerivation(); - const nlohmann::json * getStructuredAttrs() const + const JSON * getStructuredAttrs() const { return structuredAttrs.get(); } @@ -40,10 +40,10 @@ public: bool useUidRange() const; - kj::Promise>> + kj::Promise>> prepareStructuredAttrs(Store & store, const StorePathSet & inputPaths); }; -std::string writeStructuredAttrsShell(const nlohmann::json & json); +std::string writeStructuredAttrsShell(const JSON & json); } diff --git a/lix/libstore/realisation.cc b/lix/libstore/realisation.cc index a6be5a722..82bb59454 100644 --- a/lix/libstore/realisation.cc +++ b/lix/libstore/realisation.cc @@ -61,11 +61,11 @@ try { co_return result::current_exception(); } -nlohmann::json Realisation::toJSON() const { - auto jsonDependentRealisations = nlohmann::json::object(); +JSON Realisation::toJSON() const { + auto jsonDependentRealisations = JSON::object(); for (auto & [depId, depOutPath] : dependentRealisations) jsonDependentRealisations.emplace(depId.to_string(), depOutPath.to_string()); - return nlohmann::json{ + return JSON{ {"id", id.to_string()}, {"outPath", outPath.to_string()}, {"signatures", signatures}, @@ -74,7 +74,7 @@ nlohmann::json Realisation::toJSON() const { } Realisation Realisation::fromJSON( - const nlohmann::json& json, + const JSON& json, const std::string& whence) { auto getOptionalField = [&](std::string fieldName) -> std::optional { auto fieldIterator = json.find(fieldName); diff --git a/lix/libstore/realisation.hh b/lix/libstore/realisation.hh index 9350f7f3c..42dd3a87a 100644 --- a/lix/libstore/realisation.hh +++ b/lix/libstore/realisation.hh @@ -60,8 +60,8 @@ struct Realisation { */ std::map dependentRealisations = {}; - nlohmann::json toJSON() const; - static Realisation fromJSON(const nlohmann::json& json, const std::string& whence); + JSON toJSON() const; + static Realisation fromJSON(const JSON& json, const std::string& whence); std::string fingerprint() const; void sign(const SecretKey &); diff --git a/lix/libstore/remote-fs-accessor.cc b/lix/libstore/remote-fs-accessor.cc index 653e98558..6f9a9a160 100644 --- a/lix/libstore/remote-fs-accessor.cc +++ b/lix/libstore/remote-fs-accessor.cc @@ -39,7 +39,7 @@ try { if (cacheDir != "") { try { - nlohmann::json j = TRY_AWAIT(listNar(narAccessor, "", true)); + JSON j = TRY_AWAIT(listNar(narAccessor, "", true)); writeFile(makeCacheFile(hashPart, "ls"), j.dump()); } catch (...) { ignoreExceptionExceptInterrupt(); diff --git a/lix/libstore/store-api.cc b/lix/libstore/store-api.cc index cf1d9a98a..04baef417 100644 --- a/lix/libstore/store-api.cc +++ b/lix/libstore/store-api.cc @@ -27,8 +27,6 @@ #include #include -using json = nlohmann::json; - namespace nix { BuildMode buildModeFromInteger(int raw) { @@ -954,15 +952,15 @@ try { co_return result::current_exception(); } -kj::Promise> Store::pathInfoToJSON(const StorePathSet & storePaths, +kj::Promise> Store::pathInfoToJSON(const StorePathSet & storePaths, bool includeImpureInfo, bool showClosureSize, Base hashBase, AllowInvalidFlag allowInvalid) try { - json::array_t jsonList = json::array(); + JSON::array_t jsonList = JSON::array(); for (auto & storePath : storePaths) { - auto& jsonPath = jsonList.emplace_back(json::object()); + auto& jsonPath = jsonList.emplace_back(JSON::object()); try { auto info = TRY_AWAIT(queryPathInfo(storePath)); @@ -973,7 +971,7 @@ try { jsonPath["narSize"] = info->narSize; { - auto& jsonRefs = (jsonPath["references"] = json::array()); + auto& jsonRefs = (jsonPath["references"] = JSON::array()); for (auto & ref : info->references) jsonRefs.emplace_back(printStorePath(ref)); } diff --git a/lix/libstore/store-api.hh b/lix/libstore/store-api.hh index ef897b0f7..36f8c2281 100644 --- a/lix/libstore/store-api.hh +++ b/lix/libstore/store-api.hh @@ -714,7 +714,7 @@ public: * @param showClosureSize If true, the closure size of each path is * included. */ - kj::Promise> pathInfoToJSON(const StorePathSet & storePaths, + kj::Promise> pathInfoToJSON(const StorePathSet & storePaths, bool includeImpureInfo, bool showClosureSize, Base hashBase = Base::Base32, AllowInvalidFlag allowInvalid = DisallowInvalid); diff --git a/lix/libutil/abstract-setting-to-json.hh b/lix/libutil/abstract-setting-to-json.hh index 4fd5a19f3..9a0ba0532 100644 --- a/lix/libutil/abstract-setting-to-json.hh +++ b/lix/libutil/abstract-setting-to-json.hh @@ -9,7 +9,7 @@ namespace nix { template -std::map BaseSetting::toJSONObject() const +std::map BaseSetting::toJSONObject() const { auto obj = AbstractSetting::toJSONObject(); obj.emplace("value", value); diff --git a/lix/libutil/args.cc b/lix/libutil/args.cc index de98c4fcc..573382a5f 100644 --- a/lix/libutil/args.cc +++ b/lix/libutil/args.cc @@ -275,12 +275,12 @@ bool Args::processArgs(const Strings & args, bool finish) return res; } -nlohmann::json Args::toJSON() +JSON Args::toJSON() { - auto flags = nlohmann::json::object(); + auto flags = JSON::object(); for (auto & [name, flag] : longFlags) { - auto j = nlohmann::json::object(); + auto j = JSON::object(); if (hiddenCategories.count(flag->category)) continue; if (flag->aliases.count(name)) continue; if (flag->shortName) @@ -296,10 +296,10 @@ nlohmann::json Args::toJSON() flags[name] = std::move(j); } - auto args = nlohmann::json::array(); + auto args = JSON::array(); for (auto & arg : expectedArgs) { - auto j = nlohmann::json::object(); + auto j = JSON::object(); j["label"] = arg.label; j["optional"] = arg.optional; if (arg.handler.arity != ArityAny) @@ -307,7 +307,7 @@ nlohmann::json Args::toJSON() args.push_back(std::move(j)); } - auto res = nlohmann::json::object(); + auto res = JSON::object(); res["description"] = trim(description()); res["flags"] = std::move(flags); res["args"] = std::move(args); @@ -544,16 +544,16 @@ bool MultiCommand::processArgs(const Strings & args, bool finish) return Args::processArgs(args, finish); } -nlohmann::json MultiCommand::toJSON() +JSON MultiCommand::toJSON() { // FIXME: use Command::toJSON() as well. - auto cmds = nlohmann::json::object(); + auto cmds = JSON::object(); for (auto & [name, commandFun] : commands) { auto command = commandFun(aio()); auto j = command->toJSON(); - auto cat = nlohmann::json::object(); + auto cat = JSON::object(); cat["id"] = command->category(); cat["description"] = trim(categories[command->category()]); cat["experimental-feature"] = command->experimentalFeature(); diff --git a/lix/libutil/args.hh b/lix/libutil/args.hh index edf58efa7..50db21749 100644 --- a/lix/libutil/args.hh +++ b/lix/libutil/args.hh @@ -303,7 +303,7 @@ public: static CompleterFun completeDir; - virtual nlohmann::json toJSON(); + virtual JSON toJSON(); friend class MultiCommand; @@ -376,7 +376,7 @@ public: bool processArgs(const Strings & args, bool finish) override; - nlohmann::json toJSON() override; + JSON toJSON() override; }; /** diff --git a/lix/libutil/config.cc b/lix/libutil/config.cc index 1bc9371a4..55ecdcaf7 100644 --- a/lix/libutil/config.cc +++ b/lix/libutil/config.cc @@ -177,9 +177,9 @@ void Config::resetOverridden() s.second.setting->overridden = false; } -nlohmann::json Config::toJSON() +JSON Config::toJSON() { - auto res = nlohmann::json::object(); + auto res = JSON::object(); for (const auto & s : _settings) if (!s.second.isAlias) res.emplace(s.first, s.second.setting->toJSON()); @@ -213,14 +213,14 @@ AbstractSetting::~AbstractSetting() assert(created == 123); } -nlohmann::json AbstractSetting::toJSON() +JSON AbstractSetting::toJSON() { - return nlohmann::json(toJSONObject()); + return JSON(toJSONObject()); } -std::map AbstractSetting::toJSONObject() const +std::map AbstractSetting::toJSONObject() const { - std::map obj; + std::map obj; obj.emplace("description", description); obj.emplace("aliases", aliases); if (experimentalFeature) @@ -516,9 +516,9 @@ void GlobalConfig::resetOverridden() config->resetOverridden(); } -nlohmann::json GlobalConfig::toJSON() +JSON GlobalConfig::toJSON() { - auto res = nlohmann::json::object(); + auto res = JSON::object(); for (const auto & config : *configRegistrations) res.update(config->toJSON()); return res; diff --git a/lix/libutil/config.hh b/lix/libutil/config.hh index 4b58f8f2b..cb5ddb11c 100644 --- a/lix/libutil/config.hh +++ b/lix/libutil/config.hh @@ -92,7 +92,7 @@ public: * Outputs all settings to JSON * - out: JSONObject to write the configuration to */ - virtual nlohmann::json toJSON() = 0; + virtual JSON toJSON() = 0; /** * Converts settings to `Args` to be used on the command line interface @@ -157,7 +157,7 @@ public: void resetOverridden() override; - nlohmann::json toJSON() override; + JSON toJSON() override; void convertToArgs(Args & args, const std::string & category) override; }; @@ -202,9 +202,9 @@ protected: virtual std::string to_string() const = 0; - nlohmann::json toJSON(); + JSON toJSON(); - virtual std::map toJSONObject() const; + virtual std::map toJSONObject() const; virtual void convertToArg(Args & args, const std::string & category); @@ -293,7 +293,7 @@ public: void convertToArg(Args & args, const std::string & category) override; - std::map toJSONObject() const override; + std::map toJSONObject() const override; }; template @@ -360,7 +360,7 @@ struct GlobalConfig : public AbstractConfig void resetOverridden() override; - nlohmann::json toJSON() override; + JSON toJSON() override; /** * Outputs all settings in a key-value pair format suitable to be used as diff --git a/lix/libutil/deprecated-features-json.hh b/lix/libutil/deprecated-features-json.hh index fef94f872..f3992e64b 100644 --- a/lix/libutil/deprecated-features-json.hh +++ b/lix/libutil/deprecated-features-json.hh @@ -11,14 +11,14 @@ namespace nix { * * See `doc/manual` for how this information is used. */ -nlohmann::json documentDeprecatedFeatures(); +JSON documentDeprecatedFeatures(); /** * Semi-magic conversion to and from json. * See the nlohmann/json readme for more details. */ -void to_json(nlohmann::json &, const DeprecatedFeature &); -void from_json(const nlohmann::json &, DeprecatedFeature &); +void to_json(JSON &, const DeprecatedFeature &); +void from_json(const JSON &, DeprecatedFeature &); /** * It is always rendered as a string diff --git a/lix/libutil/deprecated-features.cc b/lix/libutil/deprecated-features.cc index 2009d3040..ad2d1600b 100644 --- a/lix/libutil/deprecated-features.cc +++ b/lix/libutil/deprecated-features.cc @@ -60,13 +60,13 @@ std::string_view showDeprecatedFeature(const DeprecatedFeature tag) return depFeatureDetails[(size_t)tag].name; } -nlohmann::json documentDeprecatedFeatures() +JSON documentDeprecatedFeatures() { StringMap res; for (auto & depFeature : depFeatureDetails) res[std::string { depFeature.name }] = trim(stripIndentation(depFeature.description)); - return (nlohmann::json) res; + return (JSON) res; } DeprecatedFeatures parseDeprecatedFeatures(const std::set & rawFeatures) @@ -88,12 +88,12 @@ std::ostream & operator <<(std::ostream & str, const DeprecatedFeature & feature return str << showDeprecatedFeature(feature); } -void to_json(nlohmann::json & j, const DeprecatedFeature & feature) +void to_json(JSON & j, const DeprecatedFeature & feature) { j = showDeprecatedFeature(feature); } -void from_json(const nlohmann::json & j, DeprecatedFeature & feature) +void from_json(const JSON & j, DeprecatedFeature & feature) { const std::string input = j; const auto parsed = parseDeprecatedFeature(input); diff --git a/lix/libutil/experimental-features-json.hh b/lix/libutil/experimental-features-json.hh index d015193b7..8a31d4548 100644 --- a/lix/libutil/experimental-features-json.hh +++ b/lix/libutil/experimental-features-json.hh @@ -11,14 +11,14 @@ namespace nix { * * See `doc/manual` for how this information is used. */ -nlohmann::json documentExperimentalFeatures(); +JSON documentExperimentalFeatures(); /** * Semi-magic conversion to and from json. * See the nlohmann/json readme for more details. */ -void to_json(nlohmann::json &, const ExperimentalFeature &); -void from_json(const nlohmann::json &, ExperimentalFeature &); +void to_json(JSON &, const ExperimentalFeature &); +void from_json(const JSON &, ExperimentalFeature &); /** * It is always rendered as a string diff --git a/lix/libutil/experimental-features.cc b/lix/libutil/experimental-features.cc index fa43d9273..9982087f6 100644 --- a/lix/libutil/experimental-features.cc +++ b/lix/libutil/experimental-features.cc @@ -60,13 +60,13 @@ std::string_view showExperimentalFeature(const ExperimentalFeature tag) return xpFeatureDetails[(size_t)tag].name; } -nlohmann::json documentExperimentalFeatures() +JSON documentExperimentalFeatures() { StringMap res; for (auto & xpFeature : xpFeatureDetails) res[std::string { xpFeature.name }] = trim(stripIndentation(xpFeature.description)); - return (nlohmann::json) res; + return (JSON) res; } ExperimentalFeatures parseFeatures(const std::set & rawFeatures) @@ -88,12 +88,12 @@ std::ostream & operator <<(std::ostream & str, const ExperimentalFeature & featu return str << showExperimentalFeature(feature); } -void to_json(nlohmann::json & j, const ExperimentalFeature & feature) +void to_json(JSON & j, const ExperimentalFeature & feature) { j = showExperimentalFeature(feature); } -void from_json(const nlohmann::json & j, ExperimentalFeature & feature) +void from_json(const JSON & j, ExperimentalFeature & feature) { const std::string input = j; const auto parsed = parseExperimentalFeature(input); diff --git a/lix/libutil/json-fwd.hh b/lix/libutil/json-fwd.hh index 865fbabaf..487e2638e 100644 --- a/lix/libutil/json-fwd.hh +++ b/lix/libutil/json-fwd.hh @@ -2,3 +2,9 @@ ///@file Lix-specific JSON handling (forward declarations only). #include + +namespace nix { + +using JSON = nlohmann::json; + +} diff --git a/lix/libutil/json-impls.hh b/lix/libutil/json-impls.hh index 301e989d6..31dbd9eff 100644 --- a/lix/libutil/json-impls.hh +++ b/lix/libutil/json-impls.hh @@ -9,7 +9,7 @@ using namespace nix; \ template <> \ struct adl_serializer { \ - static TYPE from_json(const json & json); \ - static void to_json(json & json, TYPE t); \ + static TYPE from_json(const JSON & json); \ + static void to_json(JSON & json, TYPE t); \ }; \ } diff --git a/lix/libutil/json-utils.cc b/lix/libutil/json-utils.cc index 204f7b411..5f6d9c6c1 100644 --- a/lix/libutil/json-utils.cc +++ b/lix/libutil/json-utils.cc @@ -3,22 +3,22 @@ namespace nix { -const nlohmann::json * get(const nlohmann::json & map, const std::string & key) +const JSON * get(const JSON & map, const std::string & key) { auto i = map.find(key); if (i == map.end()) return nullptr; return &*i; } -nlohmann::json * get(nlohmann::json & map, const std::string & key) +JSON * get(JSON & map, const std::string & key) { auto i = map.find(key); if (i == map.end()) return nullptr; return &*i; } -const nlohmann::json & valueAt( - const nlohmann::json & map, +const JSON & valueAt( + const JSON & map, const std::string & key) { if (!map.contains(key)) @@ -27,15 +27,15 @@ const nlohmann::json & valueAt( return map[key]; } -const nlohmann::json & ensureType( - const nlohmann::json & value, - nlohmann::json::value_type expectedType +const JSON & ensureType( + const JSON & value, + JSON::value_type expectedType ) { if (value.type() != expectedType) throw Error( "Expected JSON value to be of type '%s' but it is of type '%s'", - nlohmann::json(expectedType).type_name(), + JSON(expectedType).type_name(), value.type_name()); return value; diff --git a/lix/libutil/json-utils.hh b/lix/libutil/json-utils.hh index 9cf26a08d..bae902892 100644 --- a/lix/libutil/json-utils.hh +++ b/lix/libutil/json-utils.hh @@ -6,20 +6,20 @@ namespace nix { -const nlohmann::json * get(const nlohmann::json & map, const std::string & key); +const JSON * get(const JSON & map, const std::string & key); -nlohmann::json * get(nlohmann::json & map, const std::string & key); +JSON * get(JSON & map, const std::string & key); /** * Get the value of a json object at a key safely, failing * with a Nix Error if the key does not exist. * - * Use instead of nlohmann::json::at() to avoid ugly exceptions. + * Use instead of JSON::at() to avoid ugly exceptions. * * _Does not check whether `map` is an object_, use `ensureType` for that. */ -const nlohmann::json & valueAt( - const nlohmann::json & map, +const JSON & valueAt( + const JSON & map, const std::string & key); /** @@ -28,9 +28,9 @@ const nlohmann::json & valueAt( * * Use before type conversions and element access to avoid ugly exceptions. */ -const nlohmann::json & ensureType( - const nlohmann::json & value, - nlohmann::json::value_type expectedType); +const JSON & ensureType( + const JSON & value, + JSON::value_type expectedType); /** * For `adl_serializer>` below, we need to track what diff --git a/lix/libutil/json.hh b/lix/libutil/json.hh index b07461170..040cf4e5c 100644 --- a/lix/libutil/json.hh +++ b/lix/libutil/json.hh @@ -1,4 +1,5 @@ #pragma once ///@file Lix-specific JSON handling. -#include +#include "lix/libutil/json-fwd.hh" // IWYU pragma: keep +#include // IWYU pragma: keep diff --git a/lix/libutil/logging-json.hh b/lix/libutil/logging-json.hh index 00f266ba7..d7404afdb 100644 --- a/lix/libutil/logging-json.hh +++ b/lix/libutil/logging-json.hh @@ -12,12 +12,12 @@ namespace nix { /** * @param source A noun phrase describing the source of the message, e.g. "the builder". */ -std::optional parseJSONMessage(const std::string & msg, std::string_view source); +std::optional parseJSONMessage(const std::string & msg, std::string_view source); /** * @param source A noun phrase describing the source of the message, e.g. "the builder". */ -bool handleJSONLogMessage(nlohmann::json & json, +bool handleJSONLogMessage(JSON & json, const Activity & act, std::map & activities, std::string_view source, bool trusted); diff --git a/lix/libutil/logging.cc b/lix/libutil/logging.cc index 2a4165a7c..b78ef17ed 100644 --- a/lix/libutil/logging.cc +++ b/lix/libutil/logging.cc @@ -142,7 +142,7 @@ Activity::Activity(Logger & logger, Verbosity lvl, ActivityType type, logger.startActivity(id, lvl, type, s, fields, parent); } -void to_json(nlohmann::json & json, std::shared_ptr pos) +void to_json(JSON & json, std::shared_ptr pos) { if (pos) { json["line"] = pos->line; @@ -166,10 +166,10 @@ struct JSONLogger : Logger { return true; } - void addFields(nlohmann::json & json, const Fields & fields) + void addFields(JSON & json, const Fields & fields) { if (fields.empty()) return; - auto & arr = json["fields"] = nlohmann::json::array(); + auto & arr = json["fields"] = JSON::array(); for (auto & f : fields) if (f.type == Logger::Field::tInt) arr.push_back(f.i); @@ -179,14 +179,14 @@ struct JSONLogger : Logger { abort(); } - void write(const nlohmann::json & json) + void write(const JSON & json) { - prevLogger.log(lvlError, "@nix " + json.dump(-1, ' ', false, nlohmann::json::error_handler_t::replace)); + prevLogger.log(lvlError, "@nix " + json.dump(-1, ' ', false, JSON::error_handler_t::replace)); } void log(Verbosity lvl, std::string_view s) override { - nlohmann::json json; + JSON json; json["action"] = "msg"; json["level"] = lvl; json["msg"] = s; @@ -198,7 +198,7 @@ struct JSONLogger : Logger { std::ostringstream oss; showErrorInfo(oss, ei, loggerSettings.showTrace.get()); - nlohmann::json json; + JSON json; json["action"] = "msg"; json["level"] = ei.level; json["msg"] = oss.str(); @@ -206,9 +206,9 @@ struct JSONLogger : Logger { to_json(json, ei.pos); if (loggerSettings.showTrace.get() && !ei.traces.empty()) { - nlohmann::json traces = nlohmann::json::array(); + JSON traces = JSON::array(); for (auto iter = ei.traces.rbegin(); iter != ei.traces.rend(); ++iter) { - nlohmann::json stackFrame; + JSON stackFrame; stackFrame["raw_msg"] = iter->hint.str(); to_json(stackFrame, iter->pos); traces.push_back(stackFrame); @@ -223,7 +223,7 @@ struct JSONLogger : Logger { void startActivity(ActivityId act, Verbosity lvl, ActivityType type, const std::string & s, const Fields & fields, ActivityId parent) override { - nlohmann::json json; + JSON json; json["action"] = "start"; json["id"] = act; json["level"] = lvl; @@ -236,7 +236,7 @@ struct JSONLogger : Logger { void stopActivity(ActivityId act) override { - nlohmann::json json; + JSON json; json["action"] = "stop"; json["id"] = act; write(json); @@ -244,7 +244,7 @@ struct JSONLogger : Logger { void result(ActivityId act, ResultType type, const Fields & fields) override { - nlohmann::json json; + JSON json; json["action"] = "result"; json["id"] = act; json["type"] = type; @@ -258,24 +258,24 @@ Logger * makeJSONLogger(Logger & prevLogger) return new JSONLogger(prevLogger); } -static Logger::Fields getFields(nlohmann::json & json) +static Logger::Fields getFields(JSON & json) { Logger::Fields fields; for (auto & f : json) { - if (f.type() == nlohmann::json::value_t::number_unsigned) + if (f.type() == JSON::value_t::number_unsigned) fields.emplace_back(Logger::Field(f.get())); - else if (f.type() == nlohmann::json::value_t::string) + else if (f.type() == JSON::value_t::string) fields.emplace_back(Logger::Field(f.get())); else throw Error("unsupported JSON type %d", (int) f.type()); } return fields; } -std::optional parseJSONMessage(const std::string & msg, std::string_view source) +std::optional parseJSONMessage(const std::string & msg, std::string_view source) { if (!msg.starts_with("@nix ")) return std::nullopt; try { - return nlohmann::json::parse(std::string(msg, 5)); + return JSON::parse(std::string(msg, 5)); } catch (std::exception & e) { printError("bad JSON log message from %s: %s", Uncolored(source), @@ -284,7 +284,7 @@ std::optional parseJSONMessage(const std::string & msg, std::str return std::nullopt; } -bool handleJSONLogMessage(nlohmann::json & json, +bool handleJSONLogMessage(JSON & json, const Activity & act, std::map & activities, std::string_view source, bool trusted) { @@ -320,7 +320,7 @@ bool handleJSONLogMessage(nlohmann::json & json, } return true; - } catch (nlohmann::json::exception &e) { + } catch (JSON::exception &e) { warn( "Unable to handle a JSON message from %s: %s", Uncolored(source), diff --git a/lix/nix/build.cc b/lix/nix/build.cc index 2066c7749..ad46971ed 100644 --- a/lix/nix/build.cc +++ b/lix/nix/build.cc @@ -9,9 +9,9 @@ namespace nix { -static nlohmann::json derivedPathsToJSON(AsyncIoRoot & aio, const DerivedPaths & paths, Store & store) +static JSON derivedPathsToJSON(AsyncIoRoot & aio, const DerivedPaths & paths, Store & store) { - auto res = nlohmann::json::array(); + auto res = JSON::array(); for (auto & t : paths) { std::visit([&](const auto & t) { res.push_back(aio.blockOn(t.toJSON(store))); @@ -20,11 +20,11 @@ static nlohmann::json derivedPathsToJSON(AsyncIoRoot & aio, const DerivedPaths & return res; } -static nlohmann::json builtPathsWithResultToJSON( +static JSON builtPathsWithResultToJSON( AsyncIoRoot & aio, const std::vector & buildables, const Store & store ) { - auto res = nlohmann::json::array(); + auto res = JSON::array(); for (auto & b : buildables) { std::visit([&](const auto & t) { auto j = aio.blockOn(t.toJSON(store)); diff --git a/lix/nix/derivation-add.cc b/lix/nix/derivation-add.cc index 5d8a857c6..93c8e5e94 100644 --- a/lix/nix/derivation-add.cc +++ b/lix/nix/derivation-add.cc @@ -8,7 +8,6 @@ #include "lix/libstore/derivations.hh" namespace nix { -using json = nlohmann::json; struct CmdAddDerivation : MixDryRun, StoreCommand { @@ -28,7 +27,7 @@ struct CmdAddDerivation : MixDryRun, StoreCommand void run(ref store) override { - auto json = nlohmann::json::parse(drainFD(STDIN_FILENO)); + auto json = JSON::parse(drainFD(STDIN_FILENO)); auto drv = Derivation::fromJSON(*store, json); diff --git a/lix/nix/derivation-show.cc b/lix/nix/derivation-show.cc index 2c313bc35..31e718b09 100644 --- a/lix/nix/derivation-show.cc +++ b/lix/nix/derivation-show.cc @@ -9,7 +9,6 @@ #include "lix/libstore/derivations.hh" namespace nix { -using json = nlohmann::json; struct CmdShowDerivation : InstallablesCommand { @@ -50,7 +49,7 @@ struct CmdShowDerivation : InstallablesCommand drvPaths = std::move(closure); } - json jsonRoot = json::object(); + JSON jsonRoot = JSON::object(); for (auto & drvPath : drvPaths) { if (!drvPath.isDerivation()) continue; diff --git a/lix/nix/develop.cc b/lix/nix/develop.cc index 18becfa35..07d1c5f2a 100644 --- a/lix/nix/develop.cc +++ b/lix/nix/develop.cc @@ -57,7 +57,7 @@ struct BuildEnvironment std::set exported; - auto json = nlohmann::json::parse(in); + auto json = JSON::parse(in); for (auto & [name, info] : json["variables"].items()) { std::string type = info["type"]; @@ -82,11 +82,11 @@ struct BuildEnvironment std::string toJSON() const { - auto res = nlohmann::json::object(); + auto res = JSON::object(); - auto vars2 = nlohmann::json::object(); + auto vars2 = JSON::object(); for (auto & [name, value] : vars) { - auto info = nlohmann::json::object(); + auto info = JSON::object(); if (auto str = std::get_if(&value)) { info["type"] = str->exported ? "exported" : "var"; info["value"] = str->value; @@ -106,7 +106,7 @@ struct BuildEnvironment res["bashFunctions"] = bashFunctions; if (providesStructuredAttrs()) { - auto contents = nlohmann::json::object(); + auto contents = JSON::object(); contents[".attrs.sh"] = getAttrsSH(); contents[".attrs.json"] = getAttrsJSON(); res["structuredAttrs"] = std::move(contents); diff --git a/lix/nix/diff-closures.cc b/lix/nix/diff-closures.cc index 1e03043b2..fae2742e1 100644 --- a/lix/nix/diff-closures.cc +++ b/lix/nix/diff-closures.cc @@ -31,13 +31,13 @@ typedef std::map>> typedef std::map DiffInfo; -nlohmann::json toJSON(const DiffInfo & diff) +JSON toJSON(const DiffInfo & diff) { - nlohmann::json res = nlohmann::json::object(); - nlohmann::json content = nlohmann::json::object(); + JSON res = JSON::object(); + JSON content = JSON::object(); for (auto & [name, item] : diff) { - auto packageContent = nlohmann::json::object(); + auto packageContent = JSON::object(); if (!item.removedVersions.empty() || !item.addedVersions.empty()) { packageContent["versionsBefore"] = item.removedVersions; diff --git a/lix/nix/flake.cc b/lix/nix/flake.cc index 306dcc6dd..7884bc8ad 100644 --- a/lix/nix/flake.cc +++ b/lix/nix/flake.cc @@ -25,7 +25,6 @@ namespace nix { using namespace nix::flake; -using json = nlohmann::json; struct CmdFlakeUpdate; class FlakeCommand : public virtual Args, public MixFlakeOptions @@ -220,7 +219,7 @@ struct CmdFlakeMetadata : FlakeCommand, MixJSON }; if (json) { - nlohmann::json j; + JSON j; if (flake.description) j["description"] = *flake.description; j["originalUrl"] = flake.originalRef.to_string(); @@ -1051,10 +1050,10 @@ struct CmdFlakeArchive : FlakeCommand, MixJSON, MixDryRun sources.insert(flake.flake.sourceInfo->storePath); // FIXME: use graph output, handle cycles. - std::function traverse; + std::function traverse; traverse = [&](const Node & node) { - nlohmann::json jsonObj2 = json ? json::object() : nlohmann::json(nullptr); + JSON jsonObj2 = json ? JSON::object() : JSON(nullptr); for (auto & [inputName, input] : node.inputs) { if (auto inputNode = std::get_if<0>(&input)) { auto storePath = @@ -1076,7 +1075,7 @@ struct CmdFlakeArchive : FlakeCommand, MixJSON, MixDryRun }; if (json) { - nlohmann::json jsonRoot = { + JSON jsonRoot = { {"path", store->printStorePath(flake.flake.sourceInfo->storePath)}, {"inputs", traverse(*flake.lockFile.root)}, }; @@ -1191,7 +1190,7 @@ struct CmdFlakeShow : FlakeCommand, MixJSON } }; - std::function & attrPath, const std::string & headerPrefix, @@ -1202,9 +1201,9 @@ struct CmdFlakeShow : FlakeCommand, MixJSON const std::vector & attrPath, const std::string & headerPrefix, const std::string & nextPrefix) - -> nlohmann::json + -> JSON { - auto j = nlohmann::json::object(); + auto j = JSON::object(); Activity act(*logger, lvlInfo, actUnknown, fmt("evaluating '%s'", concatStringsSep(".", attrPath))); @@ -1443,7 +1442,7 @@ struct CmdFlakePrefetch : FlakeCommand, MixJSON auto hash = aio().blockOn(store->queryPathInfo(tree.storePath))->narHash; if (json) { - auto res = nlohmann::json::object(); + auto res = JSON::object(); res["storePath"] = store->printStorePath(tree.storePath); res["hash"] = hash.to_string(Base::SRI, true); logger->cout(res.dump()); diff --git a/lix/nix/main.cc b/lix/nix/main.cc index fc45f1b63..ca5bcd43c 100644 --- a/lix/nix/main.cc +++ b/lix/nix/main.cc @@ -324,11 +324,11 @@ struct NixArgs : virtual MultiCommand, virtual MixCommonArgs, virtual RootArgs std::string dumpCli() { - auto res = nlohmann::json::object(); + auto res = JSON::object(); res["args"] = toJSON(); - auto stores = nlohmann::json::object(); + auto stores = JSON::object(); for (auto & implem : *StoreImplementations::registered) { auto storeConfig = implem.getConfig(); auto storeName = storeConfig->name(); @@ -518,12 +518,12 @@ void mainWrapped(AsyncIoRoot & aio, int argc, char * * argv) | Xp::DynamicDerivations); evalSettings.pureEval.override(false); Evaluator state(aio, {}, aio.blockOn(openStore("dummy://"))); - auto res = nlohmann::json::object(); + auto res = JSON::object(); res["builtins"] = ({ - auto builtinsJson = nlohmann::json::object(); + auto builtinsJson = JSON::object(); auto builtins = state.builtins.env.values[0]->attrs; for (auto & builtin : *builtins) { - auto b = nlohmann::json::object(); + auto b = JSON::object(); if (!builtin.value->isPrimOp()) continue; auto primOp = builtin.value->primOp; if (!primOp->doc) continue; @@ -536,9 +536,9 @@ void mainWrapped(AsyncIoRoot & aio, int argc, char * * argv) std::move(builtinsJson); }); res["constants"] = ({ - auto constantsJson = nlohmann::json::object(); + auto constantsJson = JSON::object(); for (auto & [name, info] : state.builtins.constantInfos) { - auto c = nlohmann::json::object(); + auto c = JSON::object(); if (!info.doc) continue; c["doc"] = trim(stripIndentation(info.doc)); c["type"] = showType(info.type, false); diff --git a/lix/nix/make-content-addressed.cc b/lix/nix/make-content-addressed.cc index 3ab3d376d..9074e6f3b 100644 --- a/lix/nix/make-content-addressed.cc +++ b/lix/nix/make-content-addressed.cc @@ -7,8 +7,6 @@ namespace nix { -using nlohmann::json; - struct CmdMakeContentAddressed : virtual CopyCommand, virtual StorePathsCommand, MixJSON { CmdMakeContentAddressed() @@ -36,13 +34,13 @@ struct CmdMakeContentAddressed : virtual CopyCommand, virtual StorePathsCommand, StorePathSet(storePaths.begin(), storePaths.end()))); if (json) { - auto jsonRewrites = json::object(); + auto jsonRewrites = JSON::object(); for (auto & path : storePaths) { auto i = remappings.find(path); assert(i != remappings.end()); jsonRewrites[srcStore->printStorePath(path)] = srcStore->printStorePath(i->second); } - auto json = json::object(); + auto json = JSON::object(); json["rewrites"] = jsonRewrites; logger->cout("%s", json); } else { diff --git a/lix/nix/ping-store.cc b/lix/nix/ping-store.cc index 67172cce8..1bc1899b6 100644 --- a/lix/nix/ping-store.cc +++ b/lix/nix/ping-store.cc @@ -31,7 +31,7 @@ struct CmdPingStore : StoreCommand, MixJSON if (auto trusted = aio().blockOn(store->isTrustedClient())) notice("Trusted: %s", *trusted); } else { - nlohmann::json res; + JSON res; Finally printRes([&]() { logger->cout("%s", res); }); diff --git a/lix/nix/prefetch.cc b/lix/nix/prefetch.cc index 606951b83..9a429122c 100644 --- a/lix/nix/prefetch.cc +++ b/lix/nix/prefetch.cc @@ -323,7 +323,7 @@ struct CmdStorePrefetchFile : StoreCommand, MixJSON prefetchFile(aio(), store, url, name, hashType, expectedHash, unpack, executable); if (json) { - auto res = nlohmann::json::object(); + auto res = JSON::object(); res["storePath"] = store->printStorePath(storePath); res["hash"] = hash.to_string(Base::SRI, true); logger->cout(res.dump()); diff --git a/lix/nix/realisation.cc b/lix/nix/realisation.cc index c98e07249..164b5e6c6 100644 --- a/lix/nix/realisation.cc +++ b/lix/nix/realisation.cc @@ -54,9 +54,9 @@ struct CmdRealisationInfo : BuiltPathsCommand, MixJSON } if (json) { - nlohmann::json res = nlohmann::json::array(); + JSON res = JSON::array(); for (auto & path : realisations) { - nlohmann::json currentPath; + JSON currentPath; if (auto realisation = std::get_if(&path.raw)) currentPath = realisation->toJSON(); else diff --git a/lix/nix/search.cc b/lix/nix/search.cc index 7f3a96e7c..62fa95d85 100644 --- a/lix/nix/search.cc +++ b/lix/nix/search.cc @@ -17,7 +17,6 @@ #include namespace nix { -using json = nlohmann::json; std::string wrap(std::string prefix, std::string s) { @@ -88,8 +87,8 @@ struct CmdSearch : InstallableCommand, MixJSON auto evaluator = getEvaluator(); auto state = evaluator->begin(aio()); - std::optional jsonOut; - if (json) jsonOut = json::object(); + std::optional jsonOut; + if (json) jsonOut = JSON::object(); uint64_t results = 0; diff --git a/subprojects/nix-eval-jobs/src/constituents.cc b/subprojects/nix-eval-jobs/src/constituents.cc index bb13756ef..cdd4e490b 100644 --- a/subprojects/nix-eval-jobs/src/constituents.cc +++ b/subprojects/nix-eval-jobs/src/constituents.cc @@ -69,7 +69,7 @@ auto topoSort(const std::set &items) } } // namespace -auto resolveNamedConstituents(const std::map &jobs) +auto resolveNamedConstituents(const std::map &jobs) -> std::variant, DependencyCycle> { std::set aggregateJobs; for (auto const &[jobName, job] : jobs) { @@ -80,7 +80,7 @@ auto resolveNamedConstituents(const std::map &jobs) auto isBroken = [&brokenJobs, &jobName](const std::string &childJobName, - const nlohmann::json &job) -> bool { + const nix::JSON &job) -> bool { if (job.find("error") != job.end()) { std::string error = job["error"]; nix::logger->log( @@ -118,7 +118,7 @@ auto resolveNamedConstituents(const std::map &jobs) } } -void rewriteAggregates(std::map &jobs, +void rewriteAggregates(std::map &jobs, const std::vector &aggregateJobs, nix::ref &store, nix::Path &gcRootsDir, nix::AsyncIoRoot &aio) { diff --git a/subprojects/nix-eval-jobs/src/constituents.hh b/subprojects/nix-eval-jobs/src/constituents.hh index 9518262da..d7ca77595 100644 --- a/subprojects/nix-eval-jobs/src/constituents.hh +++ b/subprojects/nix-eval-jobs/src/constituents.hh @@ -36,10 +36,10 @@ struct AggregateJob { } }; -auto resolveNamedConstituents(const std::map &jobs) +auto resolveNamedConstituents(const std::map &jobs) -> std::variant, DependencyCycle>; -void rewriteAggregates(std::map &jobs, +void rewriteAggregates(std::map &jobs, const std::vector &aggregateJobs, nix::ref &store, nix::Path &gcRootsDir, nix::AsyncIoRoot &aio); diff --git a/subprojects/nix-eval-jobs/src/drv.cc b/subprojects/nix-eval-jobs/src/drv.cc index 910d84a30..510c2db91 100644 --- a/subprojects/nix-eval-jobs/src/drv.cc +++ b/subprojects/nix-eval-jobs/src/drv.cc @@ -73,7 +73,7 @@ Drv::Drv(std::string &attrPath, nix::EvalState &state, nix::DrvInfo &drvInfo, } if (args.meta) { - nlohmann::json meta_; + nix::JSON meta_; for (auto &metaName : drvInfo.queryMetaNames(state)) { nix::NixStringContext context; std::stringstream ss; @@ -88,7 +88,7 @@ Drv::Drv(std::string &attrPath, nix::EvalState &state, nix::DrvInfo &drvInfo, nix::printValueAsJSON(state, true, *metaValue, nix::noPos, ss, context); - meta_[metaName] = nlohmann::json::parse(ss.str()); + meta_[metaName] = nix::JSON::parse(ss.str()); } meta = meta_; } @@ -114,14 +114,14 @@ Drv::Drv(std::string &attrPath, nix::EvalState &state, nix::DrvInfo &drvInfo, system = drv.platform; } -void to_json(nlohmann::json &json, const Drv &drv) { - std::map outputsJson; +void to_json(nix::JSON &json, const Drv &drv) { + std::map outputsJson; for (auto &[name, optPath] : drv.outputs) { outputsJson[name] = - optPath ? nlohmann::json(*optPath) : nlohmann::json(nullptr); + optPath ? nix::JSON(*optPath) : nix::JSON(nullptr); } - json = nlohmann::json{{"name", drv.name}, + json = nix::JSON{{"name", drv.name}, {"system", drv.system}, {"drvPath", drv.drvPath}, {"outputs", outputsJson}, diff --git a/subprojects/nix-eval-jobs/src/drv.hh b/subprojects/nix-eval-jobs/src/drv.hh index 5ef352543..bf2945cad 100644 --- a/subprojects/nix-eval-jobs/src/drv.hh +++ b/subprojects/nix-eval-jobs/src/drv.hh @@ -34,13 +34,13 @@ struct Drv { enum class CacheStatus { Cached, Uncached, Unknown } cacheStatus; std::map> outputs; std::map> inputDrvs; - std::optional meta; + std::optional meta; std::optional constituents; Drv(std::string &attrPath, nix::EvalState &state, nix::DrvInfo &drvInfo, MyArgs &args, std::optional constituents); }; -void to_json(nlohmann::json &json, const Drv &drv); +void to_json(nix::JSON &json, const Drv &drv); void register_gc_root(nix::Path &gcRootsDir, std::string &drvPath, const nix::ref &store, nix::AsyncIoRoot &aio); diff --git a/subprojects/nix-eval-jobs/src/nix-eval-jobs.cc b/subprojects/nix-eval-jobs/src/nix-eval-jobs.cc index 709e4124e..25da5e31a 100644 --- a/subprojects/nix-eval-jobs/src/nix-eval-jobs.cc +++ b/subprojects/nix-eval-jobs/src/nix-eval-jobs.cc @@ -43,7 +43,6 @@ #include "worker.hh" using namespace nix; -using namespace nlohmann; using Processor = std::function state, Bindings &autoArgs, @@ -75,7 +74,7 @@ struct Proc { Bindings &autoArgs = *myArgs.getAutoArgs(*evaluator); proc(evaluator, autoArgs, *to, *from, myArgs, aio); } catch (Error &e) { - nlohmann::json err; + JSON err; auto msg = e.msg(); err["error"] = nix::filterANSIEscapes(msg, true); printError(msg); @@ -150,10 +149,10 @@ struct Thread { }; struct State { - std::set todo = json::array({json::array()}); - std::set active; + std::set todo = JSON::array({JSON::array()}); + std::set active; std::exception_ptr exc; - std::map jobs; + std::map jobs; }; void handleBrokenWorkerPipe(Proc &proc, std::string_view msg, bool retry = true) { @@ -226,7 +225,7 @@ void handleBrokenWorkerPipe(Proc &proc, std::string_view msg, bool retry = true) } } -std::string joinAttrPath(json &attrPath) { +std::string joinAttrPath(JSON &attrPath) { std::string joined; for (auto &element : attrPath) { if (!joined.empty()) { @@ -262,9 +261,9 @@ void collector(MyArgs &myArgs, Sync &state_, continue; } else if (s != "next") { try { - auto json = json::parse(s); + auto json = JSON::parse(s); throw Error("worker error: %s", (std::string)json["error"]); - } catch (const json::exception &e) { + } catch (const JSON::exception &e) { throw Error( "Received invalid JSON from worker: %s\n json: '%s'", e.what(), s); @@ -272,7 +271,7 @@ void collector(MyArgs &myArgs, Sync &state_, } /* Wait for a job name to become available. */ - json attrPath; + JSON attrPath; while (true) { checkInterrupt(); @@ -306,20 +305,20 @@ void collector(MyArgs &myArgs, Sync &state_, joinAttrPath(attrPath) + "'"; handleBrokenWorkerPipe(*proc.get(), msg); } - json response; + JSON response; try { - response = json::parse(respString); - } catch (const json::exception &e) { + response = JSON::parse(respString); + } catch (const JSON::exception &e) { throw Error( "Received invalid JSON from worker: %s\n json: '%s'", e.what(), respString); } /* Handle the response. */ - std::vector newAttrs; + std::vector newAttrs; if (response.find("attrs") != response.end()) { for (auto &i : response["attrs"]) { - json newAttr = json(response["attrPath"]); + JSON newAttr = JSON(response["attrPath"]); newAttr.emplace_back(i); newAttrs.push_back(newAttr); } diff --git a/subprojects/nix-eval-jobs/src/worker.cc b/subprojects/nix-eval-jobs/src/worker.cc index 0e27d6af3..3ca2fb841 100644 --- a/subprojects/nix-eval-jobs/src/worker.cc +++ b/subprojects/nix-eval-jobs/src/worker.cc @@ -61,7 +61,7 @@ static nix::Value *releaseExprTopLevelValue(nix::EvalState &state, return vRoot; } -static std::string attrPathJoin(nlohmann::json input) { +static std::string attrPathJoin(nix::JSON input) { return std::accumulate(input.begin(), input.end(), std::string(), [](std::string ss, std::string s) { // Escape token if containing dots @@ -157,12 +157,12 @@ void worker(nix::ref evaluator, s.data()); abort(); } - auto path = nlohmann::json::parse(s.substr(3)); + auto path = nix::JSON::parse(s.substr(3)); auto attrPathS = attrPathJoin(path); /* Evaluate it and send info back to the collector. */ - nlohmann::json reply = - nlohmann::json{{"attr", attrPathS}, {"attrPath", path}}; + nix::JSON reply = + nix::JSON{{"attr", attrPathS}, {"attrPath", path}}; try { auto vTmp = nix::findAlongAttrPath(*state, attrPathS, autoArgs, *vRoot) @@ -187,7 +187,7 @@ void worker(nix::ref evaluator, done. */ register_gc_root(args.gcRootsDir, drv.drvPath, evaluator->store, aio); } else { - auto attrs = nlohmann::json::array(); + auto attrs = nix::JSON::array(); bool recurse = args.forceRecurse || path.size() == 0; // Dont require `recurseForDerivations @@ -210,11 +210,11 @@ void worker(nix::ref evaluator, if (recurse) reply["attrs"] = std::move(attrs); else - reply["attrs"] = nlohmann::json::array(); + reply["attrs"] = nix::JSON::array(); } } else { // We ignore everything that cannot be build - reply["attrs"] = nlohmann::json::array(); + reply["attrs"] = nix::JSON::array(); } } catch (nix::EvalError &e) { auto err = e.info(); diff --git a/tests/unit/libstore/derivation.cc b/tests/unit/libstore/derivation.cc index 0ef9e4a7c..205e2a9c3 100644 --- a/tests/unit/libstore/derivation.cc +++ b/tests/unit/libstore/derivation.cc @@ -9,8 +9,6 @@ namespace nix { -using nlohmann::json; - class DerivationTest : public LibStoreTest { public: @@ -79,7 +77,7 @@ TEST_F(DynDerivationTest, BadATerm_oldVersionDynDeps) { } \ else \ { \ - auto encoded = json::parse( \ + auto encoded = JSON::parse( \ readFile(goldenMaster("output-" #NAME ".json"))); \ DerivationOutput got = DerivationOutput::fromJSON( \ *store, \ @@ -95,7 +93,7 @@ TEST_F(DynDerivationTest, BadATerm_oldVersionDynDeps) { TEST_F(FIXTURE, DerivationOutput_ ## NAME ## _to_json) { \ auto file = goldenMaster("output-" #NAME ".json"); \ \ - json got = DerivationOutput { VAL }.toJSON( \ + JSON got = DerivationOutput { VAL }.toJSON( \ *store, \ DRV_NAME, \ OUTPUT_NAME); \ @@ -108,7 +106,7 @@ TEST_F(DynDerivationTest, BadATerm_oldVersionDynDeps) { } \ else \ { \ - auto expected = json::parse(readFile(file)); \ + auto expected = JSON::parse(readFile(file)); \ ASSERT_EQ(got, expected); \ } \ } @@ -173,7 +171,7 @@ TEST_JSON(ImpureDerivationTest, impure, } \ else \ { \ - auto encoded = json::parse( \ + auto encoded = JSON::parse( \ readFile(goldenMaster( #NAME ".json"))); \ Derivation expected { VAL }; \ Derivation got = Derivation::fromJSON( \ @@ -187,7 +185,7 @@ TEST_JSON(ImpureDerivationTest, impure, TEST_F(FIXTURE, Derivation_ ## NAME ## _to_json) { \ auto file = goldenMaster( #NAME ".json"); \ \ - json got = Derivation { VAL }.toJSON(*store); \ + JSON got = Derivation { VAL }.toJSON(*store); \ \ if (testAccept()) \ { \ @@ -197,7 +195,7 @@ TEST_JSON(ImpureDerivationTest, impure, } \ else \ { \ - auto expected = json::parse(readFile(file)); \ + auto expected = JSON::parse(readFile(file)); \ ASSERT_EQ(got, expected); \ } \ } diff --git a/tests/unit/libstore/outputs-spec.cc b/tests/unit/libstore/outputs-spec.cc index d1c999b98..6c8be230f 100644 --- a/tests/unit/libstore/outputs-spec.cc +++ b/tests/unit/libstore/outputs-spec.cc @@ -177,7 +177,7 @@ TEST(ExtendedOutputsSpec, many_carrot) { ASSERT_EQ( \ STR ## _json, \ /* NOLINTNEXTLINE(bugprone-macro-parentheses) */ \ - ((nlohmann::json) TYPE { VAL })); \ + ((JSON) TYPE { VAL })); \ } \ \ TEST(TYPE, NAME ## _from_json) { \ diff --git a/tests/unit/libutil/json-utils.cc b/tests/unit/libutil/json-utils.cc index e0b19d9d1..77cd56034 100644 --- a/tests/unit/libutil/json-utils.cc +++ b/tests/unit/libutil/json-utils.cc @@ -13,9 +13,9 @@ namespace nix { TEST(to_json, optionalInt) { std::optional val = std::make_optional(420); - ASSERT_EQ(nlohmann::json(val), nlohmann::json(420)); + ASSERT_EQ(JSON(val), JSON(420)); val = std::nullopt; - ASSERT_EQ(nlohmann::json(val), nlohmann::json(nullptr)); + ASSERT_EQ(JSON(val), JSON(nullptr)); } TEST(to_json, vectorOfOptionalInts) { @@ -23,7 +23,7 @@ TEST(to_json, vectorOfOptionalInts) { std::make_optional(420), std::nullopt, }; - ASSERT_EQ(nlohmann::json(vals), nlohmann::json::parse("[420,null]")); + ASSERT_EQ(JSON(vals), JSON::parse("[420,null]")); } TEST(to_json, optionalVectorOfInts) { @@ -31,13 +31,13 @@ TEST(to_json, optionalVectorOfInts) { -420, 420, }); - ASSERT_EQ(nlohmann::json(val), nlohmann::json::parse("[-420,420]")); + ASSERT_EQ(JSON(val), JSON::parse("[-420,420]")); val = std::nullopt; - ASSERT_EQ(nlohmann::json(val), nlohmann::json(nullptr)); + ASSERT_EQ(JSON(val), JSON(nullptr)); } TEST(from_json, optionalInt) { - nlohmann::json json = 420; + JSON json = 420; std::optional val = json; ASSERT_TRUE(val.has_value()); ASSERT_EQ(*val, 420); @@ -47,7 +47,7 @@ TEST(from_json, optionalInt) { } TEST(from_json, vectorOfOptionalInts) { - nlohmann::json json = { 420, nullptr }; + JSON json = { 420, nullptr }; std::vector> vals = json; ASSERT_EQ(vals.size(), 2); ASSERT_TRUE(vals.at(0).has_value());