Add SetBlock() to Config for large-scale settings replacements. (#868)

Modify `Config::Save()` to apply assign unflattened `mFlattenedJson` to `mNestedJson` and dump that, to keep `mNestedJson` somewhat synchronized.
This commit is contained in:
Malkierian
2025-05-05 20:37:04 -04:00
committed by GitHub
parent 41ac34ae80
commit ce38cb6883
2 changed files with 34 additions and 1 deletions
+33 -1
View File
@@ -131,6 +131,37 @@ void Config::Erase(const std::string& key) {
mFlattenedJson.erase(FormatNestedKey(key));
}
void Config::SetBlock(const std::string& key, nlohmann::json block) {
nlohmann::json gjson = mFlattenedJson.unflatten();
if (key.find(".") != std::string::npos) {
nlohmann::json* gjson2 = &gjson;
std::vector<std::string> dots = StringHelper::Split(key, ".");
if (dots.size() > 1) {
size_t curDot = 0;
for (auto& dot : dots) {
if (curDot == dots.size() - 1) {
if (gjson2->contains(dot)) {
gjson2->at(dot) = block;
break;
} else {
gjson2->emplace(dot, block);
break;
}
} else if (gjson2->contains(dot)) {
gjson2 = &gjson2->at(dot);
curDot++;
}
}
}
} else {
if (gjson.contains(key)) {
gjson[key] = block;
}
}
mFlattenedJson = gjson.flatten();
Save();
}
void Config::EraseBlock(const std::string& key) {
nlohmann::json gjson = mFlattenedJson.unflatten();
if (key.find(".") != std::string::npos) {
@@ -183,7 +214,8 @@ void Config::Reload() {
void Config::Save() {
std::ofstream file(mPath);
file << mFlattenedJson.unflatten().dump(4);
mNestedJson = mFlattenedJson.unflatten();
file << mNestedJson.dump(4);
}
template <typename T> std::vector<T> Config::GetArray(const std::string& key) {
+1
View File
@@ -57,6 +57,7 @@ class Config {
void SetUInt(const std::string& key, uint32_t value);
void Erase(const std::string& key);
void EraseBlock(const std::string& key);
void SetBlock(const std::string& key, nlohmann::json block);
void Copy(const std::string& fromKey, const std::string& toKey);
bool Contains(const std::string& key);
void Reload();