libmrbesen/src/config.cpp

88 lines
1.9 KiB
C++

#include "config.h"
#include "files.h"
#include "util.h"
namespace mrbesen {
const std::string Config::SPLIT = ".";
template<>
const std::string* Config::Section::get(const std::string& valueName) const {
auto it = values.find(valueName);
if(it == values.end()) return nullptr;
return &it->second;
}
template<typename T>
T Config::Section::get(const std::string& valueName) const {
return (T) get<const std::string*>(valueName);
}
Config::Config(const std::string& filename) : filename(filename) {}
Config::~Config() {}
bool Config::loadConfig() {
main.values.clear();
sections.clear();
Config::Section* currentSection = &main;
files::iterateFile(filename, [this](const std::string& line){
if(line[0] == '#' || line[0] == ';') return;
if(line[0] == '[' && util::endsWith(line, "]")) {
std::string sectionName = line.substr(1, line.length()-2);
util::trim(sectionName);
if(sectionName.empty()) {
//currentSection = &main;
return;
}
//check for existing section
auto it = sections.find(sectionName);
if(it == sections.end()) {
//create new section
//TODO
sections.insert({sectionName, {}});
}
}
std::string split[2];
unsigned int spl = util::split(line, "=", split, 2);
}, true);
return false;
}
const Config::Section* Config::getSection(std::string sectionName) const {
util::removeEnd(sectionName, SPLIT);
if(sectionName.empty())
return &main;
auto it = sections.find(sectionName);
if(it == sections.end()) {
return nullptr;
}
return &it->second;
}
template<typename T>
T Config::get(const std::string& valueName) const {
if(valueName.empty()) return nullptr;
std::string out[2];
unsigned int i = util::split(valueName, ".", out, 2);
if(i == 1) {
//main section
return main.get<T>(out[0]);
}
const Config::Section* sect = getSection(out[0]);
if(sect) return sect->get(out[1]);
return nullptr;
}
}