Branch data Line data Source code
1 : : #include <hpactor/cli/tabular_formatter.hpp>
2 : :
3 : : #include <algorithm>
4 : :
5 : : namespace hpactor {
6 : : namespace cli {
7 : :
8 : 0 : void TabularFormatter::header(const std::string& title) {
9 : 0 : buffer_ += "# " + title + "\n";
10 : 0 : }
11 : :
12 : 1 : void TabularFormatter::table(const std::vector<std::string>& cols,
13 : : const std::vector<std::vector<std::string>>& rows) {
14 : 1 : if (cols.empty()) return;
15 : 1 : std::vector<size_t> widths(cols.size());
16 : 3 : for (size_t i = 0; i < cols.size(); ++i) widths[i] = cols[i].size();
17 : 3 : for (const auto& row : rows)
18 : 6 : for (size_t i = 0; i < row.size() && i < widths.size(); ++i)
19 : 4 : widths[i] = std::max(widths[i], row[i].size());
20 : :
21 : 3 : for (size_t i = 0; i < cols.size(); ++i)
22 : 4 : buffer_ += cols[i] + std::string(widths[i] - cols[i].size(), ' ') + " ";
23 : 1 : buffer_ += "\n";
24 : :
25 : 3 : for (const auto& row : rows) {
26 : 6 : for (size_t i = 0; i < cols.size(); ++i) {
27 : 4 : std::string val = i < row.size() ? row[i] : "-";
28 : 4 : buffer_ += val + std::string(widths[i] > val.size() ? widths[i] - val.size() : 0, ' ') + " ";
29 : 4 : }
30 : 2 : buffer_ += "\n";
31 : : }
32 : 1 : }
33 : :
34 : 1 : void TabularFormatter::key_value(const std::map<std::string, std::string>& pairs) {
35 : 2 : for (const auto& kv : pairs)
36 : 1 : buffer_ += kv.first + ": " + kv.second + "\n";
37 : 1 : }
38 : :
39 : 0 : void TabularFormatter::tree(const TreeNode& root) {
40 : 0 : auto print = [this](auto& self, const TreeNode& node, int depth) -> void {
41 : 0 : std::string indent(static_cast<size_t>(depth) * 2, ' ');
42 : 0 : buffer_ += indent + node.name;
43 : 0 : if (!node.description.empty()) buffer_ += " # " + node.description;
44 : 0 : buffer_ += "\n";
45 : 0 : for (const auto& child : node.children)
46 : 0 : self(self, child, depth + 1);
47 : 0 : };
48 : 0 : print(print, root, 0);
49 : 0 : }
50 : :
51 : 0 : void TabularFormatter::raw(const std::string& text) {
52 : 0 : buffer_ += text;
53 : 0 : if (!text.empty() && text.back() != '\n') buffer_ += '\n';
54 : 0 : }
55 : :
56 : 0 : void TabularFormatter::error(const std::string& message) {
57 : 0 : buffer_ += "ERROR: " + message + "\n";
58 : 0 : }
59 : :
60 : 2 : std::string TabularFormatter::finalize() { return std::move(buffer_); }
61 : :
62 : : } // namespace cli
63 : : } // namespace hpactor
|