aboutsummaryrefslogtreecommitdiff
path: root/src/settings.cc
blob: 1ae3f07e87a85f87906c94198054db2c355b0c15 (plain)
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
#include "settings.h"
#include <map>
#include <cstdlib>
#include <regex>
#include <stdexcept>

namespace settings {
    const std::map<std::string, std::string> dummySettings {
        {"weapons", "/usr/share/dmtool/weapons/"},
            {"armor", "/usr/share/dmtool/armor/"},
            {"spells", "/usr/share/dmtool/spells/"},
            {"creatures", "/usr/share/dmtool/creatures/"},
            {"savedir", "~/.dmtool/"}
    };


    // 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 + "\"");
        }
        std::string ret = dummySettings.at(key);
        autoExpandEnvironmentVariables(ret);
        return ret;
    }

    const std::vector<std::string> objectTypes {"weapons", "armor", "spells"};
}