Arkanjo 0.2
A tool for find code duplicated functions in codebases
Loading...
Searching...
No Matches
template_renderer.hpp
Go to the documentation of this file.
1#pragma once
2
5
10
12private:
13 static Utils::COLOR resolve_style(const std::string& name, const StyleMap& theme) {
14 auto it = theme.find(name);
15 return (it != theme.end()) ? it->second : Utils::COLOR::NONE;
16 }
17
18 static Placeholder parse_placeholder(const std::string& raw, const StyleMap& theme) {
20
21 auto pos = raw.find(':');
22
23 if (pos == std::string::npos) {
24 p.key = raw;
25 } else {
26 p.key = raw.substr(0, pos);
27 std::string style_name = raw.substr(pos + 1);
28
29 p.style = resolve_style(style_name, theme);
30 }
31
32 return p;
33 }
34
35public:
36 static std::string render(const std::string& tpl, const json& ctx, std::shared_ptr<IFormatter> formatter) {
37 std::string result;
38 result.reserve(tpl.size());
39
40 size_t pos = 0;
41 while (pos < tpl.size()) {
42 size_t start = tpl.find('{', pos);
43
44 if (start == std::string::npos) {
45 result.append(tpl, pos, tpl.size() - pos);
46 break;
47 }
48
49 result.append(tpl, pos, start - pos);
50
51 size_t end = tpl.find('}', start);
52 if (end == std::string::npos) {
53 result.append(tpl, start, tpl.size() - start);
54 break;
55 }
56
57 std::string raw = tpl.substr(start + 1, end - start - 1);
58 auto ph = parse_placeholder(raw, formatter->style());
59
60 std::string value;
61
62 if (ctx.contains(ph.key)) {
63 const auto& v = ctx[ph.key];
64 value = v.is_string() ? v.get<std::string>() : v.dump();
65 } else {
66 value = "{" + ph.key + "}";
67 }
68
69 result.append(formatter->colorize(value, ph.style));
70
71 pos = end + 1;
72 }
73
74 return result;
75 }
76};
std::unordered_map< std::string, Utils::COLOR > StyleMap
Definition base.hpp:15
static std::string render(const std::string &tpl, const json &ctx, std::shared_ptr< IFormatter > formatter)
nlohmann::json json
Definition function.hpp:22
COLOR
Enumeration of available colors for formatted messages.
Definition utils.hpp:111
@ NONE
Definition utils.hpp:125
std::string key
Utils::COLOR style
Defines utility functions used across all files.