Skip to content

Commit f2f0be1

Browse files
committed
SimpCfg:Parse config file and load string key-value fields
1 parent 0316c8f commit f2f0be1

File tree

1 file changed

+53
-9
lines changed

1 file changed

+53
-9
lines changed

common/simpcfg.hpp

Lines changed: 53 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -14,8 +14,12 @@
1414
#include <vector>
1515
#include <fstream>
1616

17+
#define TEST_LOGIC
18+
#ifdef TEST_LOGIC
19+
#define LOG_TEELN(FMT, ...) printf(FMT, __VA_ARGS__)
20+
#else
1721
#include "log.h"
18-
22+
#endif
1923

2024
std::map<std::string, std::map<std::string, std::string>> mapStrings = {};
2125
std::map<std::string, std::map<std::string, bool>> mapBools = {};
@@ -40,23 +44,63 @@ bool sc_get_bool(std::string &group, std::string &key) {
4044
return gm[key];
4145
}
4246

43-
std::string str_trim(std::string &sin) {
44-
std::string sout = sin;
45-
sout.erase(sout.find_last);
47+
std::string str_trim(std::string sin) {
48+
sin.erase(sin.find_last_not_of(" \t\n")+1);
49+
sin.erase(0, sin.find_first_not_of(" \t\n"));
50+
return sin;
4651
}
4752

4853
bool sc_load(std::string &fname) {
4954
std::ifstream f {fname};
5055
if (!f) {
5156
LOG_TEELN("ERRR:%s:%s:failed to load...", __func__, fname);
52-
exit(2);
57+
throw std::runtime_error { "ERRR:SimpCfg:File not found" };
58+
} else {
59+
LOG_TEELN("DBUG:%s:%s", __func__, fname);
5360
}
61+
std::string group;
62+
int iLine = 0;
5463
while(!f.eof()) {
55-
std::string curl;
56-
getline(f, curl);
57-
if (curl.empty()) {
64+
iLine += 1;
65+
std::string curL;
66+
getline(f, curL);
67+
if (curL.empty()) {
5868
continue;
5969
}
60-
70+
if (curL[0] == '#') {
71+
continue;
72+
}
73+
bool bGroup = !isspace(curL[0]);
74+
curL = str_trim(curL);
75+
if (bGroup) {
76+
group = curL;
77+
LOG_TEELN("DBUG:%s:%s:%s:%s", __func__, group);
78+
continue;
79+
}
80+
auto dPos = curL.find(':');
81+
if (dPos == std::string::npos) {
82+
LOG_TEELN("ERRR:%s:%d:invalid key value line:%s", __func__, iLine, curL);
83+
throw std::runtime_error { "ERRR:SimpCfg:Invalid key value line" };
84+
}
85+
auto dEnd = curL.length() - dPos;
86+
if ((dPos == 0) || (dEnd < 2)) {
87+
LOG_TEELN("ERRR:%s:%d:invalid key value line:%s", __func__, iLine, curL);
88+
throw std::runtime_error { "ERRR:SimpCfg:Invalid key value line" };
89+
}
90+
std::string key = curL.substr(0, dPos);
91+
key = str_trim(key);
92+
std::string value = curL.substr(dPos+1);
93+
value = str_trim(value);
94+
LOG_TEELN("DBUG:%s:%s:%s:%s", __func__, group, key, value);
95+
sc_set_string(group, key, value);
6196
}
6297
}
98+
99+
100+
#ifdef TEST_LOGIC
101+
int main(int argc, char **argv) {
102+
std::string fname {argv[1]};
103+
sc_load(fname);
104+
return 0;
105+
}
106+
#endif

0 commit comments

Comments
 (0)