Configuration.cpp 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. #include "Configuration.hpp"
  2. #include <boost/property_tree/ptree.hpp>
  3. #include <boost/property_tree/ini_parser.hpp>
  4. #include <boost/format.hpp>
  5. #include <boost/foreach.hpp>
  6. using namespace config;
  7. namespace config {
  8. struct ConfigurationImpl {
  9. boost::property_tree::ptree ptree;
  10. };
  11. template<typename TYPE>
  12. TYPE get(boost::property_tree::ptree tree, const std::string &property) {
  13. try {
  14. return tree.get<TYPE>(property);
  15. } catch (boost::property_tree::ptree_bad_path) {
  16. throw ConfigException((boost::format("Configuration option '%s' (type: %s) not found.")
  17. % property % typeid(TYPE).name()).str());
  18. }
  19. }
  20. }
  21. config::Configuration::Configuration(const std::string fileName)
  22. : impl(new ConfigurationImpl()) {
  23. boost::property_tree::read_ini(fileName, impl->ptree);
  24. }
  25. config::Configuration::Configuration(std::vector<std::string> const fileNames)
  26. : impl(new ConfigurationImpl()) {
  27. for (auto &name : fileNames) {
  28. boost::property_tree::read_ini(name, impl->ptree);
  29. }
  30. }
  31. config::Configuration::~Configuration() {
  32. delete impl;
  33. }
  34. int config::Configuration::getInt(const std::string &property) {
  35. return get<int>(impl->ptree, property);
  36. }
  37. bool config::Configuration::getBool(const std::string &property) {
  38. return get<bool>(impl->ptree, property);
  39. }
  40. std::string config::Configuration::getString(const std::string &property) {
  41. return get<std::string>(impl->ptree, property);
  42. }
  43. // TODO: return set
  44. std::unordered_map<std::string, std::string> config::Configuration::getChildren(const std::string &property) {
  45. std::unordered_map<std::string, std::string> pins;
  46. BOOST_FOREACH(boost::property_tree::ptree::value_type &v,
  47. impl->ptree.get_child(property)) {
  48. //pins[v.first.data()] = get<std::string>(impl->ptree, property + "." + v.second.data());
  49. pins[v.first.data()] = v.second.data();
  50. }
  51. return pins;
  52. }