Waybar/src/util/rewrite_string.cpp

33 lines
883 B
C++
Raw Permalink Normal View History

2023-03-25 16:33:01 +00:00
#include "util/rewrite_string.hpp"
2022-10-19 11:25:08 +00:00
#include <spdlog/spdlog.h>
#include <regex>
namespace waybar::util {
2023-03-25 16:33:01 +00:00
std::string rewriteString(const std::string& value, const Json::Value& rules) {
2022-10-19 11:25:08 +00:00
if (!rules.isObject()) {
2023-03-25 16:33:01 +00:00
return value;
2022-10-19 11:25:08 +00:00
}
2023-03-25 16:33:01 +00:00
std::string res = value;
2022-10-19 11:25:08 +00:00
for (auto it = rules.begin(); it != rules.end(); ++it) {
if (it.key().isString() && it->isString()) {
try {
// malformated regexes will cause an exception.
// in this case, log error and try the next rule.
const std::regex rule{it.key().asString(), std::regex_constants::icase};
2023-03-25 16:33:01 +00:00
if (std::regex_match(value, rule)) {
2022-10-19 11:25:08 +00:00
res = std::regex_replace(res, rule, it->asString());
}
} catch (const std::regex_error& e) {
spdlog::error("Invalid rule {}: {}", it.key().asString(), e.what());
}
}
}
return res;
}
} // namespace waybar::util