From bf6db4e57895430d84503e800cec9e8b407212a8 Mon Sep 17 00:00:00 2001 From: Your Name Date: Thu, 6 May 2021 17:00:00 -0400 Subject: Added a real configuration file (plus a dependency on libconfuse) --- src/settings.cc | 56 ++++++++++++++++++++++---------------------------------- 1 file changed, 22 insertions(+), 34 deletions(-) (limited to 'src/settings.cc') diff --git a/src/settings.cc b/src/settings.cc index 380ae62..ba15945 100644 --- a/src/settings.cc +++ b/src/settings.cc @@ -3,44 +3,32 @@ #include #include #include +#include +#include namespace settings { - const std::map dummySettings { - {"weapons", "/usr/share/dmtool/weapons/"}, - {"armor", "/usr/share/dmtool/armor/"}, - {"spells", "/usr/share/dmtool/spells/"}, - {"creatures", "/usr/share/dmtool/creatures/"}, - {"savedir", "~/.dmtool/"}, - {"editor", "vi"} - }; - - - // Update the input string. - // Obtained from https://stackoverflow.com/a/23442780 - void autoExpandEnvironmentVariables(std::string& text) { - std::size_t tilde; - while((tilde = text.find("~")) != std::string::npos) { - text.replace(tilde, tilde+1, "${HOME}"); - } - static std::regex env("\\$(?:\\{([^}]+)\\}|([^/]+))"); - std::smatch match; - while(std::regex_search(text, match, env)) { - std::string matchStr = match[1].str().empty()? match[2].str() : match[1].str(); - auto s = getenv(matchStr.c_str()); - const std::string var(s == NULL? "" : s); - text.replace(match[0].first, match[0].second, var); - } - } - - // Returns the setting, or an exception in the case of an error std::string getString(const std::string& key) { - if(! dummySettings.contains(key)) { - throw std::invalid_argument("Cannot find key: \"" + key + "\""); + cfg_opt_t opts[] = { + CFG_STR("weapons", "/usr/share/dmtool/weapons/", CFGF_NONE), + CFG_STR("armor", "/usr/share/dmtool/armor/", CFGF_NONE), + CFG_STR("spells", "/usr/share/dmtool/spells/", CFGF_NONE), + CFG_STR("creatures", "/usr/share/dmtool/creatures/", CFGF_NONE), + CFG_STR("savedir", NULL, CFGF_NONE), + CFG_STR("editor", "vi", CFGF_NONE), + CFG_END() + }; + cfg_t *cfg = cfg_init(opts, CFGF_IGNORE_UNKNOWN); + if(cfg_parse(cfg, "/etc/dmtool.conf") == CFG_PARSE_ERROR) { + throw std::runtime_error("Configuration file /etc/dmtool.conf could not be read: " + std::string(strerror(errno))); + } + try { + std::string result(cfg_getstr(cfg, key.c_str())); + cfg_free(cfg); + return result; + } catch(std::exception& e) { + throw std::runtime_error("Cannot find key in configuration file: \"" + key + "\""); } - std::string ret = dummySettings.at(key); - autoExpandEnvironmentVariables(ret); - return ret; } - + const std::vector objectTypes {"weapons", "armor", "spells"}; } -- cgit v1.2.3