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 <fstream>
9
10namespace
11{
12 template <typename T> std::string stringifyRapidjson(const T &obj)
13 {
14 rapidjson::StringBuffer sbuffer;
15 rapidjson::Writer<rapidjson::StringBuffer> writer(sbuffer);
16 obj.Accept(writer);
17 return sbuffer.GetString();
18 }
19} // namespace
20
22{
23 std::ifstream inFile(_configPath);
24 if (!inFile.is_open())
25 {
26 throw std::invalid_argument("Can't open config file");
27 }
28
29 rapidjson::IStreamWrapper fStreamWrapper(inFile);
30
31 rapidjson::Document doc;
32 doc.ParseStream(fStreamWrapper);
33
34 // Check is there any data
35 if (doc.IsNull())
36 {
37 throw std::invalid_argument("Read config is empty or invalid JSON format");
38 }
39
40 // Parse the configuration file
41 for (const auto &entry : doc.GetObject())
42 {
43 _configMap[entry.name.GetString()] =
44 entry.value.IsString() ? entry.value.GetString() : stringifyRapidjson(entry.value);
45 }
46}
47
49{
50 std::ofstream outFile(_configPath);
51 rapidjson::OStreamWrapper fStreamWrapper(outFile);
52
53 rapidjson::Document doc;
54 doc.SetObject();
55
56 for (const auto &[keyVal, valueVal] : _configMap)
57 {
58 rapidjson::Value key(keyVal.c_str(), doc.GetAllocator());
59 rapidjson::Value value(valueVal.c_str(), doc.GetAllocator());
60 doc.AddMember(key, value, doc.GetAllocator());
61 }
62
63 rapidjson::Writer<rapidjson::OStreamWrapper> writer(fStreamWrapper);
64 doc.Accept(writer);
65}
66
67ConfigParser::ConfigParser(std::string configPath) : _configPath(std::move(configPath)) { load(); }
68
69std::string ConfigParser::get(const std::string &key) const
70{
71 auto itr = _configMap.find(key);
72 return itr == _configMap.end() ? "" : itr->second;
73}
74
75void ConfigParser::set(const std::string &key, const std::string_view &value) { _configMap[key] = value; }
76
77void ConfigParser::remove(const std::string &key) { _configMap.erase(key); }
78
79void ConfigParser::save() const { writeJson(); }
80
82{
83 _configMap.clear();
84 readJson();
85}
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
std::string _configPath
ConfigParser(std::string configPath)