Match rewrite rules iteratively, using array structure

This guarantees rule order, and allows successive rules to match against
and replace the results of previous rules.
pull/2439/head
Kelsey Judson 2023-08-30 00:14:43 +12:00
parent e30fba0b8f
commit 674b12ae61
1 changed files with 12 additions and 8 deletions

View File

@ -6,23 +6,27 @@
namespace waybar::util { namespace waybar::util {
std::string rewriteString(const std::string& value, const Json::Value& rules) { std::string rewriteString(const std::string& value, const Json::Value& rules) {
if (!rules.isObject()) { if (rules.isObject()) {
// TODO: convert objects to the array structure to accept existing configs.
}
if (!rules.isArray()) {
return value; return value;
} }
std::string res = value; std::string res = value;
for (auto it = rules.begin(); it != rules.end(); ++it) { for (Json::Value::ArrayIndex i = 0; i != rules.size(); i++) {
if (it.key().isString() && it->isString()) { if (rules[i].isArray() && rules[i][0].isString() && rules[i][1].isString()) {
try { try {
// malformated regexes will cause an exception. // malformed regexes will cause an exception.
// in this case, log error and try the next rule. // in this case, log error and try the next rule.
const std::regex rule{it.key().asString()}; const std::regex rule{rules[i][0].asString()};
if (std::regex_match(value, rule)) { if (std::regex_match(res, rule)) {
res = std::regex_replace(res, rule, it->asString()); res = std::regex_replace(res, rule, rules[i][1].asString());
} }
} catch (const std::regex_error& e) { } catch (const std::regex_error& e) {
spdlog::error("Invalid rule {}: {}", it.key().asString(), e.what()); spdlog::error("Invalid rule {}: {}", rules[i][0].asString(), e.what());
} }
} }
} }