This repository has been archived by the owner on Sep 11, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 25
/
Config.cpp
92 lines (70 loc) · 2.24 KB
/
Config.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
/*
This file is part of duckOS.
duckOS is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
duckOS is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with duckOS. If not, see <https://www.gnu.org/licenses/>.
Copyright (c) Byteduck 2016-2021. All rights reserved.
*/
#include "Config.h"
#include "StringUtils.h"
#include "FileStream.h"
using namespace Duck;
std::map<std::string, std::string>& Config::operator[](const std::string& name) {
return _values[name];
}
std::map<std::string, std::string>& Config::section(const std::string& name) {
return _values[name];
}
bool Config::has_section(const std::string& name) {
return _values.find(name) != _values.end();
}
std::map<std::string, std::string>& Config::defaults() {
return _values[""];
}
ResultRet<Config> Config::read_from(const Path& filename) {
auto file_res = File::open(filename, "r");
if(file_res.is_error())
return file_res.result();
FileInputStream stream(file_res.value());
return read_from(stream);
}
ResultRet<Config> Config::read_from(InputStream& stream) {
Config ret;
auto res = read_from(stream, ret);
if(res.is_error())
return res;
return ret;
}
Result Config::read_from(InputStream& stream, Config& config) {
stream.set_delimeter('\n');
std::string curr_header = "";
std::string line;
while(true) {
if(stream.eof())
break;
stream >> line;
trim(line);
if(line[0] == '[' && line[line.length() - 1] == ']') {
curr_header = line.substr(1, line.length() - 2);
continue;
}
auto eq_index = line.find_first_of('=');
if(eq_index != std::string::npos) {
auto key = line.substr(0, eq_index);
rtrim(key);
auto val = line.substr(eq_index + 1);
ltrim(val);
if(val[0] == '"' && val[val.length() - 1] == '"')
val = val.substr(1, val.length() - 2);
config._values[curr_header][key] = val;
}
}
return Result::SUCCESS;
}