Merge branch 'master' of ssh://repo.or.cz/srv/git/ail
[ail.git] / source / configuration.cpp
blobdc3acdbd5ea810448eb84251812b247d025498ab
1 #include <ail/configuration.hpp>
3 namespace ail
5 configuration::configuration()
9 configuration::configuration(std::string const & file_name)
11 load(file_name);
14 bool configuration::load(std::string const & new_file_name)
16 file_name = new_file_name;
18 values.clear();
20 std::string input;
21 bool success = read_file(file_name, input);
22 if(success == false)
24 return false;
27 std::vector<std::string> lines = tokenise(input, "\n");
28 for(std::vector<std::string>::iterator i = lines.begin(), end = lines.end(); i != end; ++i)
30 std::string line = trim(*i);
32 bool is_empty = line.empty();
34 if(
35 (is_empty == true)
38 (is_empty == false)
40 (line[0] == '#')
44 continue;
47 std::size_t offset = line.find('=');
48 if(offset == std::string::npos)
50 continue;
53 std::string
54 variable = right_trim(line.substr(0, offset)),
55 value = left_trim(line.substr(offset + 1));
57 if(
58 (value.length() >= 2)
60 (value[0] == '"')
62 (*(value.end() - 1) == '"')
65 value.erase(value.begin());
66 value.erase(value.end() - 1);
69 values[variable] = value;
72 return true;
75 bool configuration::read_string(std::string const & variable_name, std::string & output)
77 std::map<std::string, std::string>::iterator search = values.find(variable_name);
78 if(search == values.end())
79 return false;
81 output = search->second;
82 return true;
85 std::string configuration::string(std::string const & variable_name)
87 std::string output;
88 bool success = read_string(variable_name, output);
89 if(success == false)
90 throw exception("Unable to find string value \"" + variable_name + "\" in \"" + file_name + "\"");
91 return output;
94 std::string configuration::string(std::string const & variable_name, std::string const & default_value)
96 std::string output;
97 bool success = read_string(variable_name, output);
98 if(success == false)
99 return default_value;
101 return output;