Repo-Init
 
Loading...
Searching...
No Matches
ConfigParser.cpp
Go to the documentation of this file.
2
3#include <rapidjson/document.h>
4#include <rapidjson/istreamwrapper.h>
5#include <rapidjson/ostreamwrapper.h>
6#include <rapidjson/writer.h>
7
8#include <format>
9#include <fstream>
10
11namespace
12{
13 template <typename T> std::string stringifyRapidjson(const T &obj)
14 {
15 rapidjson::StringBuffer sbuffer;
16 rapidjson::Writer<rapidjson::StringBuffer> writer(sbuffer);
17 obj.Accept(writer);
18 return sbuffer.GetString();
19 }
20} // namespace
21
23{
24 std::ifstream inFile(_configPath);
25 if (!inFile.is_open())
26 {
27 _lastError = std::format("{} {}", "Can't open config file:", _configPath.string());
28 return false;
29 }
30
31 // Scope the wrapper to ensure proper destruction order
32 rapidjson::Document doc;
33 {
34 rapidjson::IStreamWrapper fStreamWrapper(inFile);
35 doc.ParseStream(fStreamWrapper);
36 }
37
38 // Check for parse errors
39 if (doc.HasParseError())
40 {
41 _lastError = std::format("{} {}", "JSON parse error at offset", std::to_string(doc.GetErrorOffset()));
42 return false;
43 }
44
45 // Check is there any data
46 if (doc.IsNull() || !doc.IsObject())
47 {
48 _lastError = "Config is empty or not a JSON object";
49 return false;
50 }
51
52 // Parse the configuration file
53 for (const auto &entry : doc.GetObject())
54 {
55 _configMap[entry.name.GetString()] =
56 entry.value.IsString() ? entry.value.GetString() : stringifyRapidjson(entry.value);
57 }
58
59 return true;
60}
61
63{
64 std::ofstream outFile(_configPath);
65 rapidjson::OStreamWrapper fStreamWrapper(outFile);
66
67 rapidjson::Document doc;
68 doc.SetObject();
69
70 for (const auto &[keyVal, valueVal] : _configMap)
71 {
72 rapidjson::Value key(keyVal.c_str(), doc.GetAllocator());
73 rapidjson::Value value(valueVal.c_str(), doc.GetAllocator());
74 doc.AddMember(key, value, doc.GetAllocator());
75 }
76
77 rapidjson::Writer<rapidjson::OStreamWrapper> writer(fStreamWrapper);
78 doc.Accept(writer);
79}
80
81ConfigParser::ConfigParser(std::filesystem::path configPath) : _configPath(std::move(configPath)) { load(); }
82
83std::string ConfigParser::get(const std::string &key) const
84{
85 auto itr = _configMap.find(key);
86 return itr == _configMap.end() ? "" : itr->second;
87}
88
89void ConfigParser::set(const std::string &key, const std::string_view &value) { _configMap[key] = value; }
90
91void ConfigParser::remove(const std::string &key) { _configMap.erase(key); }
92
93void ConfigParser::save() const { writeJson(); }
94
96{
97 _configMap.clear();
99 return _isValid;
100}
std::unordered_map< std::string, std::string > _configMap
void set(const std::string &key, const std::string_view &value)
std::string get(const std::string &key) const
void writeJson() const
void remove(const std::string &key)
void save() const
ConfigParser(std::filesystem::path configPath)
std::filesystem::path _configPath
std::string _lastError