Skip to content

Commit

Permalink
feat(config): Inheritance
Browse files Browse the repository at this point in the history
Add support for basic inheritance. The parser will
look for `inherit = base/section` and copy all undefined
values from the base section.

Ref #84
  • Loading branch information
jaagr committed Dec 1, 2016
1 parent 4f76d91 commit 0c6937e
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 0 deletions.
3 changes: 3 additions & 0 deletions include/components/config.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -24,9 +24,12 @@ DEFINE_ERROR(key_error);

class config {
public:
static constexpr const char* KEY_INHERIT{"inherit"};

explicit config(const logger& logger, const xresource_manager& xrm) : m_logger(logger), m_xrm(xrm) {}

void load(string file, string barname);
void copy_inherited();
string filepath() const;
string bar_section() const;
vector<string> defined_bars() const;
Expand Down
41 changes: 41 additions & 0 deletions src/components/config.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,47 @@ void config::load(string file, string barname) {

m_logger.trace("config: Loaded %s", file);
m_logger.trace("config: Current bar section: [%s]", bar_section());

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) {
// Find and validate parent section
auto inherit_section = param.second.get_value<string>();

// Dereference value
inherit_section = dereference<string>(section.first, param.first, inherit_section, inherit_section);

if (inherit_section.empty()) {
throw value_error("[" + section.first + ".inherit] requires a value");
}
auto base_section = m_ptree.get_child_optional(inherit_section);
if (!base_section || base_section.value().empty()) {
throw value_error("[" + section.first + ".inherit] points to an invalid section \"" + inherit_section + "\"");
}

m_logger.trace("config: Copying missing params (sub=\"%s\", base=\"%s\")", section.first, inherit_section);

// Iterate the 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);
}
}
}
}
}
}

/**
Expand Down

0 comments on commit 0c6937e

Please sign in to comment.