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