Merge pull request #10503 from haenoe/public-key-json-impl

`fetchers::PublicKey` json impl
This commit is contained in:
John Ericson 2024-04-14 18:02:27 -04:00 committed by GitHub
commit 03eb4f7baa
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
5 changed files with 38 additions and 8 deletions

View file

@ -3,6 +3,7 @@
#include "input-accessor.hh"
#include "source-path.hh"
#include "fetch-to-store.hh"
#include "json-utils.hh"
#include <nlohmann/json.hpp>
@ -412,3 +413,20 @@ std::string publicKeys_to_string(const std::vector<PublicKey>& publicKeys)
}
}
namespace nlohmann {
using namespace nix;
fetchers::PublicKey adl_serializer<fetchers::PublicKey>::from_json(const json & json) {
auto type = optionalValueAt(json, "type").value_or("ssh-ed25519");
auto key = valueAt(json, "key");
return fetchers::PublicKey { getString(type), getString(key) };
}
void adl_serializer<fetchers::PublicKey>::to_json(json & json, fetchers::PublicKey p) {
json["type"] = p.type;
json["key"] = p.key;
}
}

View file

@ -4,6 +4,7 @@
#include "types.hh"
#include "hash.hh"
#include "canon-path.hh"
#include "json-impls.hh"
#include "attrs.hh"
#include "url.hh"
@ -230,8 +231,9 @@ struct PublicKey
std::string type = "ssh-ed25519";
std::string key;
};
NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE_WITH_DEFAULT(PublicKey, type, key)
std::string publicKeys_to_string(const std::vector<PublicKey>&);
}
JSON_IMPL(fetchers::PublicKey)

View file

@ -30,14 +30,12 @@ const nlohmann::json & valueAt(
return map.at(key);
}
std::optional<nlohmann::json> optionalValueAt(const nlohmann::json & value, const std::string & key)
std::optional<nlohmann::json> optionalValueAt(const nlohmann::json::object_t & map, const std::string & key)
{
try {
auto & v = valueAt(value, key);
return v.get<nlohmann::json>();
} catch (...) {
if (!map.contains(key))
return std::nullopt;
}
return std::optional { map.at(key) };
}

View file

@ -23,7 +23,7 @@ const nlohmann::json & valueAt(
const nlohmann::json::object_t & map,
const std::string & key);
std::optional<nlohmann::json> optionalValueAt(const nlohmann::json & value, const std::string & key);
std::optional<nlohmann::json> optionalValueAt(const nlohmann::json::object_t & value, const std::string & key);
/**
* Downcast the json object, failing with a nice error if the conversion fails.

View file

@ -160,4 +160,16 @@ TEST(getBoolean, wrongAssertions) {
ASSERT_THROW(getBoolean(valueAt(json, "int")), Error);
}
TEST(optionalValueAt, existing) {
auto json = R"({ "string": "ssh-rsa" })"_json;
ASSERT_EQ(optionalValueAt(json, "string"), std::optional { "ssh-rsa" });
}
TEST(optionalValueAt, empty) {
auto json = R"({})"_json;
ASSERT_EQ(optionalValueAt(json, "string2"), std::nullopt);
}
} /* namespace nix */