refactor(config): Drop boost::property_tree

This commit is contained in:
Michael Carlberg 2016-12-13 18:24:01 +01:00
parent 8da52af6a2
commit d45fd76dcd
8 changed files with 277 additions and 117 deletions

View File

@ -1,9 +1,7 @@
#pragma once #pragma once
#include <boost/lexical_cast.hpp>
#include <boost/optional.hpp> #include <boost/optional.hpp>
#include <boost/property_tree/ini_parser.hpp> #include <unordered_map>
#include <boost/property_tree/ptree.hpp>
#include "common.hpp" #include "common.hpp"
#include "components/logger.hpp" #include "components/logger.hpp"
@ -14,42 +12,44 @@
POLYBAR_NS POLYBAR_NS
using boost::optional;
using boost::none;
#define GET_CONFIG_VALUE(section, var, name) var = m_conf.get<decltype(var)>(section, name, var) #define GET_CONFIG_VALUE(section, var, name) var = m_conf.get<decltype(var)>(section, name, var)
#define REQ_CONFIG_VALUE(section, var, name) var = m_conf.get<decltype(var)>(section, name) #define REQ_CONFIG_VALUE(section, var, name) var = m_conf.get<decltype(var)>(section, name)
using ptree = boost::property_tree::ptree;
DEFINE_ERROR(value_error); DEFINE_ERROR(value_error);
DEFINE_ERROR(key_error); DEFINE_ERROR(key_error);
class config { class config {
public: public:
using valuemap_t = std::unordered_map<string, string>;
using sectionmap_t = std::unordered_map<string, valuemap_t>;
static constexpr const char* KEY_INHERIT{"inherit"}; static constexpr const char* KEY_INHERIT{"inherit"};
explicit config(const logger& logger, const xresource_manager& xrm) : m_logger(logger), m_xrm(xrm) {} explicit config(const logger& logger, const xresource_manager& xrm) : m_logger(logger), m_xrm(xrm) {}
void load(string file, string barname); void load(string file, string barname);
void copy_inherited();
string filepath() const; string filepath() const;
string bar_section() const; string bar_section() const;
vector<string> defined_bars() const; vector<string> defined_bars() const;
string build_path(const string& section, const string& key) const;
void warn_deprecated(const string& section, const string& key, string replacement) const; void warn_deprecated(const string& section, const string& key, string replacement) const;
/** /**
* Returns true if a given parameter exists * Returns true if a given parameter exists
*/ */
template <typename T> template <typename T>
bool has(string section, string key) const { bool has(const string& section, const string& key) const {
auto val = m_ptree.get_optional<T>(build_path(section, key)); auto it = m_sections.find(section);
return (val != boost::none); return it != m_sections.end() && it->second.find(key) != it->second.end();
} }
/** /**
* Get parameter for the current bar by name * Get parameter for the current bar by name
*/ */
template <typename T> template <typename T>
T get(string key) const { T get(const string& key) const {
return get<T>(bar_section(), key); return get<T>(bar_section(), key);
} }
@ -57,15 +57,20 @@ class config {
* Get value of a variable by section and parameter name * Get value of a variable by section and parameter name
*/ */
template <typename T> template <typename T>
T get(string section, string key) const { T get(const string& section, const string& key) const {
auto val = m_ptree.get_optional<T>(build_path(section, key)); optional<T> value{opt<T>(section, key)};
if (val == boost::none) if (value == none) {
throw key_error("Missing parameter [" + section + "." + key + "]"); throw key_error("Missing parameter [" + section + "." + key + "]");
}
auto str_val = m_ptree.get<string>(build_path(section, key)); string string_value{opt<string>(section, key).get()};
return dereference<T>(section, key, str_val, val.get()); if (!string_value.empty()) {
return dereference<T>(section, key, opt<string>(section, key).get(), value.get());
}
return move(value.get());
} }
/** /**
@ -73,18 +78,27 @@ class config {
* with a default value in case the parameter isn't defined * with a default value in case the parameter isn't defined
*/ */
template <typename T> template <typename T>
T get(string section, string key, T default_value) const { T get(const string& section, const string& key, const T& default_value) const {
auto val = m_ptree.get_optional<T>(build_path(section, key)); optional<T> value{opt<T>(section, key)};
auto str_val = m_ptree.get_optional<string>(build_path(section, key));
return dereference<T>(section, key, str_val.get_value_or(""), val.get_value_or(default_value)); if (value == none) {
return default_value;
}
string string_value{opt<string>(section, key).get()};
if (!string_value.empty()) {
return dereference<T>(section, key, opt<string>(section, key).get(), value.get());
}
return move(value.get());
} }
/** /**
* Get list of values for the current bar by name * Get list of values for the current bar by name
*/ */
template <typename T> template <typename T>
vector<T> get_list(string key) const { vector<T> get_list(const string& key) const {
return get_list<T>(bar_section(), key); return get_list<T>(bar_section(), key);
} }
@ -92,13 +106,18 @@ class config {
* Get list of values by section and parameter name * Get list of values by section and parameter name
*/ */
template <typename T> template <typename T>
vector<T> get_list(string section, string key) const { vector<T> get_list(const string& section, const string& key) const {
vector<T> vec; vector<T> vec;
boost::optional<T> value; optional<T> value;
while ((value = m_ptree.get_optional<T>(build_path(section, key) + "-" + to_string(vec.size()))) != boost::none) { while ((value = opt<T>(section, key + "-" + to_string(vec.size()))) != none) {
auto str_val = m_ptree.get<string>(build_path(section, key) + "-" + to_string(vec.size())); string string_value{get<string>(section, key + "-" + to_string(vec.size()))};
vec.emplace_back(dereference<T>(section, key, str_val, value.get()));
if (!string_value.empty()) {
vec.emplace_back(dereference<T>(section, key, move(string_value), move(value.get())));
} else {
vec.emplace_back(move(value.get()));
}
} }
if (vec.empty()) if (vec.empty())
@ -112,13 +131,18 @@ class config {
* with a default list in case the list isn't defined * with a default list in case the list isn't defined
*/ */
template <typename T> template <typename T>
vector<T> get_list(string section, string key, vector<T> default_value) const { vector<T> get_list(const string& section, const string& key, const vector<T>& default_value) const {
vector<T> vec; vector<T> vec;
boost::optional<T> value; optional<T> value;
while ((value = m_ptree.get_optional<T>(build_path(section, key) + "-" + to_string(vec.size()))) != boost::none) { while ((value = opt<T>(section, key + "-" + to_string(vec.size()))) != none) {
auto str_val = m_ptree.get<string>(build_path(section, key) + "-" + to_string(vec.size())); string string_value{get<string>(section, key + "-" + to_string(vec.size()))};
vec.emplace_back(dereference<T>(section, key, str_val, value.get()));
if (!string_value.empty()) {
vec.emplace_back(dereference<T>(section, key, move(string_value), move(value.get())));
} else {
vec.emplace_back(move(value.get()));
}
} }
if (vec.empty()) if (vec.empty())
@ -128,26 +152,44 @@ class config {
} }
protected: protected:
void read();
void copy_inherited();
template <typename T>
T convert(string&& value) const;
template <typename T>
const optional<T> opt(const string& section, const string& key) const {
sectionmap_t::const_iterator s;
valuemap_t::const_iterator v;
if ((s = m_sections.find(section)) != m_sections.end() && (v = s->second.find(key)) != s->second.end()) {
return {convert<T>(string{v->second})};
}
return none;
}
/** /**
* Dereference value reference * Dereference value reference
*/ */
template <typename T> template <typename T>
T dereference(string section, string key, string var, const T value) const { T dereference(const string& section, const string& key, const string& var, T fallback) const {
if (var.substr(0, 2) != "${" || var.substr(var.length() - 1) != "}") { if (var.substr(0, 2) != "${" || var.substr(var.length() - 1) != "}") {
return value; return fallback;
} }
auto path = var.substr(2, var.length() - 3); auto path = var.substr(2, var.length() - 3);
size_t pos; size_t pos;
if (path.find("env:") == 0) { if (path.compare(0, 4, "env:") == 0) {
return dereference_env<T>(path.substr(4), value); return dereference_env<T>(path.substr(4), fallback);
} else if (path.find("xrdb:") == 0) { } else if (path.compare(0, 5, "xrdb:") == 0) {
return dereference_xrdb<T>(path.substr(5), value); return dereference_xrdb<T>(path.substr(5), fallback);
} else if ((pos = path.find(".")) != string::npos) { } else if ((pos = path.find(".")) != string::npos) {
return dereference_local<T>(path.substr(0, pos), path.substr(pos + 1), section); return dereference_local<T>(path.substr(0, pos), path.substr(pos + 1), section);
} else { } else {
throw value_error("Invalid reference defined at [" + build_path(section, key) + "]"); throw value_error("Invalid reference defined at [" + section + "." + key + "]");
} }
} }
@ -158,21 +200,22 @@ class config {
* ${section.key} * ${section.key}
*/ */
template <typename T> template <typename T>
T dereference_local(string section, string key, string current_section) const { T dereference_local(string section, const string& key, const string& current_section) const {
if (section == "BAR") if (section == "BAR") {
m_logger.warn("${BAR.key} is deprecated. Use ${root.key} instead"); m_logger.warn("${BAR.key} is deprecated. Use ${root.key} instead");
}
section = string_util::replace(section, "BAR", bar_section(), 0, 3); section = string_util::replace(section, "BAR", bar_section(), 0, 3);
section = string_util::replace(section, "root", bar_section(), 0, 4); section = string_util::replace(section, "root", bar_section(), 0, 4);
section = string_util::replace(section, "self", current_section, 0, 4); section = string_util::replace(section, "self", current_section, 0, 4);
auto path = build_path(section, key); optional<T> result{opt<T>(section, key)};
auto result = m_ptree.get_optional<T>(path);
if (result == boost::none) if (result == none) {
throw value_error("Unexisting reference defined [" + path + "]"); throw value_error("Unexisting reference defined [" + section + "." + key + "]");
}
return dereference<T>(section, key, m_ptree.get<string>(path), result.get()); return dereference<T>(section, key, opt<string>(section, key).get(), result.get());
} }
/** /**
@ -185,14 +228,15 @@ class config {
size_t pos; size_t pos;
if ((pos = var.find(":")) != string::npos) { if ((pos = var.find(":")) != string::npos) {
fallback = boost::lexical_cast<T>(var.substr(pos + 1)); fallback = convert<T>(var.substr(pos + 1));
var.erase(pos); var.erase(pos);
} }
if (env_util::has(var.c_str())) if (env_util::has(var.c_str())) {
return boost::lexical_cast<T>(env_util::get(var.c_str())); return convert<T>(env_util::get(var.c_str()));
} else {
return fallback; return fallback;
}
} }
/** /**
@ -205,25 +249,19 @@ class config {
size_t pos; size_t pos;
if ((pos = var.find(":")) != string::npos) { if ((pos = var.find(":")) != string::npos) {
fallback = boost::lexical_cast<T>(var.substr(pos + 1)); return convert<T>(m_xrm.get_string(var.substr(0, pos), var.substr(pos + 1)));
var.erase(pos);
} }
if (std::is_same<string, T>::value) string str{m_xrm.get_string(var, "")};
return boost::lexical_cast<T>(m_xrm.get_string(var, boost::lexical_cast<string>(fallback))); return str.empty() ? fallback : convert<T>(move(str));
else if (std::is_same<float, T>::value)
return boost::lexical_cast<T>(m_xrm.get_float(var, boost::lexical_cast<float>(fallback)));
else if (std::is_same<int, T>::value)
return boost::lexical_cast<T>(m_xrm.get_int(var, boost::lexical_cast<int>(fallback)));
return fallback;
} }
private: private:
const logger& m_logger; const logger& m_logger;
const xresource_manager& m_xrm; const xresource_manager& m_xrm;
ptree m_ptree;
string m_file; string m_file;
string m_current_bar; string m_current_bar;
sectionmap_t m_sections;
}; };
namespace { namespace {

View File

@ -1,7 +1,5 @@
#pragma once #pragma once
#include <istream>
#include "config.hpp" #include "config.hpp"
#include "modules/meta/timer_module.hpp" #include "modules/meta/timer_module.hpp"

View File

@ -1,7 +1,5 @@
#pragma once #pragma once
#include <istream>
#include "config.hpp" #include "config.hpp"
#include "modules/meta/timer_module.hpp" #include "modules/meta/timer_module.hpp"

View File

@ -276,7 +276,7 @@ void bar::bootstrap_tray() {
settings.orig_y = m_opts.pos.y + m_opts.borders.at(edge::TOP).size; settings.orig_y = m_opts.pos.y + m_opts.borders.at(edge::TOP).size;
// Apply user-defined scaling // Apply user-defined scaling
auto scale = m_conf.get<float>(bs, "tray-scale", 1.0); auto scale = m_conf.get<float>(bs, "tray-scale", 1.0f);
settings.width *= scale; settings.width *= scale;
settings.height_fill *= scale; settings.height_fill *= scale;

View File

@ -1,4 +1,6 @@
#include <algorithm> #include <algorithm>
#include <fstream>
#include <istream>
#include <utility> #include <utility>
#include "components/config.hpp" #include "components/config.hpp"
@ -20,11 +22,8 @@ void config::load(string file, string barname) {
throw application_error("Could not find config file: " + file); throw application_error("Could not find config file: " + file);
} }
try { // Read values
boost::property_tree::read_ini(file, m_ptree); read();
} catch (const std::exception& e) {
throw application_error(e.what());
}
auto bars = defined_bars(); auto bars = defined_bars();
if (std::find(bars.begin(), bars.end(), m_current_bar) == bars.end()) { if (std::find(bars.begin(), bars.end(), m_current_bar) == bars.end()) {
@ -44,43 +43,6 @@ void config::load(string file, string barname) {
copy_inherited(); copy_inherited();
} }
/**
* Look for sections set up to inherit from a base section
* and copy the missing parameters
*
* [sub/seciton]
* inherit = base/section
*/
void config::copy_inherited() {
for (auto&& section : m_ptree) {
for (auto&& param : section.second) {
if (param.first.compare(KEY_INHERIT) == 0) {
// Get name of base section
auto inherit = param.second.get_value<string>();
if ((inherit = dereference<string>(section.first, param.first, inherit, inherit)).empty()) {
throw value_error("[" + section.first + "." + KEY_INHERIT + "] requires a value");
}
// Find and validate base section
auto base_section = m_ptree.get_child_optional(inherit);
if (base_section == boost::none) {
throw value_error("[" + section.first + "." + KEY_INHERIT + "] invalid reference \"" + inherit + "\"");
}
m_logger.trace("config: Copying missing params (sub=\"%s\", base=\"%s\")", section.first, inherit);
// Iterate the base and copy the parameters
// that hasn't been defined for the sub-section
for (auto&& base_param : *base_section) {
if (!section.second.get_child_optional(base_param.first)) {
section.second.put_child(base_param.first, base_param.second);
}
}
}
}
}
}
/** /**
* Get path of loaded file * Get path of loaded file
*/ */
@ -101,7 +63,7 @@ string config::bar_section() const {
vector<string> config::defined_bars() const { vector<string> config::defined_bars() const {
vector<string> bars; vector<string> bars;
for (auto&& p : m_ptree) { for (auto&& p : m_sections) {
if (p.first.compare(0, 4, "bar/") == 0) { if (p.first.compare(0, 4, "bar/") == 0) {
bars.emplace_back(p.first.substr(4)); bars.emplace_back(p.first.substr(4));
} }
@ -110,13 +72,6 @@ vector<string> config::defined_bars() const {
return bars; return bars;
} }
/**
* Build path used to find a parameter in the given section
*/
string config::build_path(const string& section, const string& key) const {
return section + "." + key;
}
/** /**
* Print a deprecation warning if the given parameter is set * Print a deprecation warning if the given parameter is set
*/ */
@ -128,4 +83,169 @@ void config::warn_deprecated(const string& section, const string& key, string re
} }
} }
void config::read() {
std::ifstream in(m_file.c_str());
string line;
string section;
while (std::getline(in, line)) {
if (line.empty()) {
continue;
}
// New section
if (line[0] == '[' && line[line.length() - 1] == ']') {
section = line.substr(1, line.length() - 2);
continue;
}
size_t equal_pos;
// Check for key-value pair equal sign
if ((equal_pos = line.find('=')) == string::npos) {
continue;
}
string key{string_util::trim(line.substr(0, equal_pos), ' ')};
string value{string_util::trim(string_util::trim(line.substr(equal_pos + 1), ' '), '"')};
m_sections[section][key] = move(value);
}
}
/**
* Look for sections set up to inherit from a base section
* and copy the missing parameters
*
* [sub/seciton]
* inherit = base/section
*/
void config::copy_inherited() {
for (auto&& section : m_sections) {
for (auto&& param : section.second) {
if (param.first.compare(KEY_INHERIT) == 0) {
// Get name of base section
auto inherit = param.second;
if ((inherit = dereference<string>(section.first, param.first, inherit, inherit)).empty()) {
throw value_error("[" + section.first + "." + KEY_INHERIT + "] requires a value");
}
// Find and validate base section
auto base_section = m_sections.find(inherit);
if (base_section == m_sections.end()) {
throw value_error("[" + section.first + "." + KEY_INHERIT + "] invalid reference \"" + inherit + "\"");
}
m_logger.trace("config: Copying missing params (sub=\"%s\", base=\"%s\")", section.first, inherit);
// Iterate the base and copy the parameters
// that hasn't been defined for the sub-section
for (auto&& base_param : base_section->second) {
valuemap_t::const_iterator iter;
if ((iter = section.second.find(base_param.first)) == section.second.end()) {
section.second.emplace_hint(iter, base_param.first, base_param.second);
}
}
}
}
}
}
template <>
string config::convert(string&& value) const {
return forward<string>(value);
}
template <>
const char* config::convert(string&& value) const {
return value.c_str();
}
template <>
char config::convert(string&& value) const {
return value.c_str()[0];
}
template <>
int config::convert(string&& value) const {
return std::atoi(value.c_str());
}
template <>
short config::convert(string&& value) const {
return static_cast<short>(std::atoi(value.c_str()));
}
template <>
bool config::convert(string&& value) const {
return std::atoi(value.c_str()) != 0;
}
template <>
float config::convert(string&& value) const {
return std::atof(value.c_str());
}
template <>
double config::convert(string&& value) const {
return std::atof(value.c_str());
}
template <>
long config::convert(string&& value) const {
return std::atol(value.c_str());
}
template <>
long long config::convert(string&& value) const {
return std::atoll(value.c_str());
}
template <>
unsigned char config::convert(string&& value) const {
int conv{convert<int>(forward<string>(value))};
if (conv < std::numeric_limits<unsigned char>::min()) {
return std::numeric_limits<unsigned char>::min();
} else if (conv > std::numeric_limits<unsigned char>::max()) {
return std::numeric_limits<unsigned char>::max();
} else {
return static_cast<unsigned char>(conv);
}
}
template <>
unsigned short config::convert(string&& value) const {
int conv{convert<int>(forward<string>(value))};
if (conv < std::numeric_limits<unsigned short>::min()) {
return std::numeric_limits<unsigned short>::min();
} else if (conv > std::numeric_limits<unsigned short>::max()) {
return std::numeric_limits<unsigned short>::max();
} else {
return static_cast<unsigned short>(conv);
}
}
template <>
unsigned int config::convert(string&& value) const {
long conv{convert<int>(forward<string>(value))};
if (conv < std::numeric_limits<unsigned int>::min()) {
return std::numeric_limits<unsigned int>::min();
} else if (conv > std::numeric_limits<unsigned int>::max()) {
return std::numeric_limits<unsigned int>::max();
} else {
return static_cast<unsigned int>(conv);
}
}
template <>
unsigned long config::convert(string&& value) const {
return std::strtoul(value.c_str(), nullptr, 10);
}
template <>
unsigned long long config::convert(string&& value) const {
return std::strtoull(value.c_str(), nullptr, 10);
}
POLYBAR_NS_END POLYBAR_NS_END

View File

@ -94,10 +94,10 @@ namespace drawtypes {
unsigned int width; unsigned int width;
if ((format = conf.get<decltype(format)>(section, name + "-format", format)).empty()) { if ((format = conf.get<decltype(format)>(section, name + "-format", format)).empty()) {
throw application_error("Invalid format defined at [" + conf.build_path(section, name) + "]"); throw application_error("Invalid format defined at [" + section + "." + name + "]");
} }
if ((width = conf.get<decltype(width)>(section, name + "-width")) < 1) { if ((width = conf.get<decltype(width)>(section, name + "-width")) < 1) {
throw application_error("Invalid width defined at [" + conf.build_path(section, name) + "]"); throw application_error("Invalid width defined at [" + section + "." + name + "]");
} }
progressbar_t progressbar{new progressbar_t::element_type(bar, width, format)}; progressbar_t progressbar{new progressbar_t::element_type(bar, width, format)};

View File

@ -1,3 +1,6 @@
#include <istream>
#include <fstream>
#include "modules/cpu.hpp" #include "modules/cpu.hpp"
#include "drawtypes/label.hpp" #include "drawtypes/label.hpp"

View File

@ -1,3 +1,6 @@
#include <istream>
#include <fstream>
#include "modules/memory.hpp" #include "modules/memory.hpp"
#include "drawtypes/label.hpp" #include "drawtypes/label.hpp"