Skip to content

Commit

Permalink
Implement getNullable
Browse files Browse the repository at this point in the history
  • Loading branch information
haenoe committed Mar 31, 2024
1 parent dff4a94 commit fbd750d
Show file tree
Hide file tree
Showing 4 changed files with 24 additions and 3 deletions.
10 changes: 8 additions & 2 deletions src/libfetchers/git.cc
Original file line number Diff line number Diff line change
Expand Up @@ -148,8 +148,14 @@ std::vector<PublicKey> getPublicKeys(const Attrs & attrs)
std::vector<PublicKey> publicKeys;
if (attrs.contains("publicKeys")) {
nlohmann::json publicKeysJson = nlohmann::json::parse(getStrAttr(attrs, "publicKeys"));
ensureType(publicKeysJson, nlohmann::json::value_t::array);
publicKeys = publicKeysJson.get<std::vector<PublicKey>>();
auto pubKeys = getArray(publicKeysJson);
publicKeys.clear();
for (auto jsonKey : pubKeys) {
auto keyObj = getObject(jsonKey);
auto type = getString(getNullable(keyObj, "type").value_or("ssh-ed25519"));
auto key = getString(valueAt(keyObj, "key"));
publicKeys.push_back({ type, key });
}
}
if (attrs.contains("publicKey"))
publicKeys.push_back(PublicKey{maybeGetStrAttr(attrs, "keytype").value_or("ssh-ed25519"),getStrAttr(attrs, "publicKey")});
Expand Down
2 changes: 1 addition & 1 deletion src/libstore/path-info.cc
Original file line number Diff line number Diff line change
Expand Up @@ -201,7 +201,7 @@ UnkeyedValidPathInfo UnkeyedValidPathInfo::fromJSON(
res.narSize = getInteger(valueAt(json, "narSize"));

try {
auto & references = getArray(valueAt(json, "references"));
auto references = getStringList(valueAt(json, "references"));
for (auto & input : references)
res.references.insert(store.parseStorePath(static_cast<const std::string &>
(input)));
Expand Down
12 changes: 12 additions & 0 deletions src/libutil/json-utils.cc
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
#include "error.hh"
#include "types.hh"
#include <nlohmann/json_fwd.hpp>
#include <iostream>

namespace nix {

Expand Down Expand Up @@ -38,6 +39,17 @@ const nlohmann::json & valueAt(

return map.at(key);
}

std::optional<nlohmann::json> getNullable(const nlohmann::json & value, const std::string & key)
{
try {
auto & v = valueAt(value, key);
return v.get<nlohmann::json>();
} catch (...) {
return std::nullopt;
}
}

const nlohmann::json & ensureType(
const nlohmann::json & value,
nlohmann::json::value_type expectedType
Expand Down
3 changes: 3 additions & 0 deletions src/libutil/json-utils.hh
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,9 @@ const nlohmann::json & valueAt(
const nlohmann::json & valueAt(
const nlohmann::json::object_t & map,
const std::string & key);

std::optional<nlohmann::json> getNullable(const nlohmann::json & value, const std::string & key);

/**
* Ensure the type of a json object is what you expect, failing
* with a Nix Error if it isn't.
Expand Down

0 comments on commit fbd750d

Please sign in to comment.