The-NodeBox-Generator/src/Configuration.cpp

89 lines
1.7 KiB
C++
Raw Permalink Normal View History

2013-12-15 09:40:57 -08:00
#include <fstream>
#include <string>
#include <stdlib.h>
2014-04-25 11:46:35 -07:00
#include "Configuration.hpp"
#include "util/string.hpp"
2013-12-15 09:40:57 -08:00
2014-04-25 11:46:35 -07:00
bool Configuration::load(const std::string & filename){
2013-12-15 09:40:57 -08:00
std::string line;
2014-04-25 11:46:35 -07:00
std::ifstream file(filename.c_str());
if (!file) {
return false;
}
while (std::getline(file, line)) {
readLine(line);
}
file.close();
return true;
2013-12-15 09:40:57 -08:00
}
2014-04-25 11:46:35 -07:00
void Configuration::readLine(std::string & line){
// Skip comments
if (line[0] == '#')
return;
line = trim(line);
2013-12-15 09:40:57 -08:00
2014-04-25 11:46:35 -07:00
if (line.empty()) {
2013-12-15 09:40:57 -08:00
return;
}
// Split string into hash and value per
2014-04-25 11:46:35 -07:00
size_t eqPos = line.find('=');
if (eqPos == std::string::npos) {
return;
2013-12-15 09:40:57 -08:00
}
2014-04-25 11:46:35 -07:00
const std::string key = trim(line.substr(0, eqPos));
const std::string value = trim(line.substr(eqPos + 1));
2013-12-15 09:40:57 -08:00
// Create setting
2014-04-25 11:46:35 -07:00
settings[key] = value;
2013-12-15 09:40:57 -08:00
}
2014-04-25 11:46:35 -07:00
bool Configuration::save(const std::string & filename){
std::ofstream file(filename.c_str());
if (!file) {
return false;
2013-12-15 09:40:57 -08:00
}
2014-04-25 11:46:35 -07:00
for (std::map<std::string, std::string>::const_iterator it = settings.begin();
it != settings.end();
++it) {
file << it->first << " = " << it->second << "\n";
}
file.close();
return true;
2013-12-15 09:40:57 -08:00
}
2014-04-25 11:46:35 -07:00
const std::string & Configuration::get(const std::string & key) const
{
return settings.find(key)->second;
2013-12-15 09:40:57 -08:00
}
2014-04-25 11:46:35 -07:00
void Configuration::set(const std::string & key, const std::string & value)
{
settings[key] = value;
2013-12-15 09:40:57 -08:00
}
2014-04-25 11:46:35 -07:00
static inline bool to_bool(const std::string & str)
{
std::string s = str_to_lower(str);
return s == "true" || s == "yes" || s == "1" || s == "on";
2013-12-15 09:40:57 -08:00
}
2014-04-25 11:46:35 -07:00
bool Configuration::getBool(const std::string & key) const
{
return to_bool(settings.find(key)->second);
}
2013-12-15 09:40:57 -08:00
2014-04-25 11:46:35 -07:00
int Configuration::getInt(const std::string & key) const
{
return atoi(settings.find(key)->second.c_str());
2013-12-15 09:40:57 -08:00
}