2 * Copyright (C) 2015, 2016 ,2017 "IoT.bzh"
3 * Author "Loïc Collignon" <loic.collignon@iot.bzh>
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
9 * http://www.apache.org/licenses/LICENSE-2.0
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
18 #include "ini-config.hpp"
20 bool starts_with(const std::string& text, const std::string& token)
22 if(text.length() < token.length()) return false;
23 return (text.compare(0, token.length(), token) == 0);
26 void ini_config::read_file(const std::string& filename)
28 std::ifstream f(filename);
31 std::regex r_section("^\\s*\\[([^\\]]+)\\]\\s*(#.*)?$");
32 std::regex r_key("^\\s*([^\\s]+)\\s*=\\s*\"([^\"]+)\"\\s*(#.*)?$");
33 std::string current_section;
35 while (std::getline(f, line))
39 switch (qualify(line))
41 case line_type::section:
42 if (std::regex_match(line, mr, r_section) && mr.size() >= 2 && mr[1].matched)
44 current_section = mr[1].str();
48 if(std::regex_match(line, mr, r_key) && mr.size() >= 2 && mr[1].matched)
50 std::string key = current_section + '/' + mr[1].str();
51 config_[key] = (mr.size() >= 3 && mr[2].matched) ? mr[2].str() : "";
54 case line_type::ignore:
61 ini_config::map ini_config::get_keys(const std::string& section, bool wo_prefix)
66 std::string prefix = section + '/';
67 for(auto i = config_.begin();
71 if (starts_with(i->first, prefix))
74 key = i->first.substr(section.size()+1);
83 std::string ini_config::get_value(const std::string& section, const std::string& key)
85 return config_[section + '/' + key];
88 ini_config::line_type ini_config::qualify(std::string& line)
92 for (std::string::value_type c : line)
94 if (c == '#') return line_type::ignore;
95 if (c == '[') return line_type::section;
96 if (!std::isspace(c, std::locale("C"))) return line_type::key;
99 return line_type::ignore;