]> git.proxmox.com Git - pve-client.git/blob - PVE/APIClient/CLIFormatter.pm
add7a3a615292d1c12cccd48108a30e43d4a24db
[pve-client.git] / PVE / APIClient / CLIFormatter.pm
1 package PVE::APIClient::CLIFormatter;
2
3 use strict;
4 use warnings;
5 use I18N::Langinfo;
6
7 use PVE::APIClient::JSONSchema;
8 use PVE::APIClient::PTY;
9 use JSON;
10 use utf8;
11 use Encode;
12
13 sub query_terminal_options {
14 my ($options) = @_;
15
16 $options //= {};
17
18 if (-t STDOUT) {
19 ($options->{columns}) = PVE::APIClient::PTY::tcgetsize(*STDOUT);
20 }
21
22 $options->{encoding} = I18N::Langinfo::langinfo(I18N::Langinfo::CODESET());
23
24 $options->{utf8} = 1 if $options->{encoding} eq 'UTF-8';
25
26 return $options;
27 }
28
29 sub data_to_text {
30 my ($data, $propdef) = @_;
31
32 return '' if !defined($data);
33
34 if (defined($propdef)) {
35 if (my $type = $propdef->{type}) {
36 if ($type eq 'boolean') {
37 return $data ? 1 : 0;
38 }
39 }
40 if (!defined($data) && defined($propdef->{default})) {
41 return "($propdef->{default})";
42 }
43 if (defined(my $renderer = $propdef->{renderer})) {
44 my $code = PVE::APIClient::JSONSchema::get_renderer($renderer);
45 die "internal error: unknown renderer '$renderer'" if !$code;
46 return $code->($data);
47 }
48 }
49
50 if (my $class = ref($data)) {
51 return to_json($data, { canonical => 1 });
52 } else {
53 return "$data";
54 }
55 }
56
57 # prints a formatted table with a title row.
58 # $data - the data to print (array of objects)
59 # $returnprops -json schema property description
60 # $props_to_print - ordered list of properties to print
61 # $options
62 # - sort_key: can be used to sort after a column, if it isn't set we sort
63 # after the leftmost column (with no undef value in $data) this can be
64 # turned off by passing 0 as sort_key
65 # - border: print with/without table header and asciiart border
66 # - columns: limit output width (if > 0)
67 # - utf8: use utf8 characters for table delimiters
68
69 sub print_text_table {
70 my ($data, $returnprops, $props_to_print, $options) = @_;
71
72 my $sort_key = $options->{sort_key};
73 my $border = $options->{border};
74 my $columns = $options->{columns};
75 my $utf8 = $options->{utf8};
76 my $encoding = $options->{encoding} // 'UTF-8';
77
78 if (!defined($sort_key) || $sort_key eq 0) {
79 $sort_key = $props_to_print->[0];
80 }
81
82 if (defined($sort_key)) {
83 my $type = $returnprops->{$sort_key}->{type} // 'string';
84 if ($type eq 'integer' || $type eq 'number') {
85 @$data = sort { $a->{$sort_key} <=> $b->{$sort_key} } @$data;
86 } else {
87 @$data = sort { $a->{$sort_key} cmp $b->{$sort_key} } @$data;
88 }
89 }
90
91 my $colopts = {};
92
93 my $borderstring_m = '';
94 my $borderstring_b = '';
95 my $borderstring_t = '';
96 my $formatstring = '';
97
98 my $column_count = scalar(@$props_to_print);
99
100 my $tabledata = [];
101
102 foreach my $entry (@$data) {
103
104 my $height = 1;
105 my $rowdata = {};
106
107 for (my $i = 0; $i < $column_count; $i++) {
108 my $prop = $props_to_print->[$i];
109 my $propinfo = $returnprops->{$prop} // {};
110
111 my $text = data_to_text($entry->{$prop}, $propinfo);
112 my $lines = [ split(/\n/, $text) ];
113 my $linecount = scalar(@$lines);
114 $height = $linecount if $linecount > $height;
115
116 my $width = 0;
117 foreach my $line (@$lines) {
118 my $len = length($line);
119 $width = $len if $len > $width;
120 }
121
122 $rowdata->{$prop} = {
123 lines => $lines,
124 width => $width,
125 };
126 }
127
128 push @$tabledata, {
129 height => $height,
130 rowdata => $rowdata,
131 };
132 }
133
134 for (my $i = 0; $i < $column_count; $i++) {
135 my $prop = $props_to_print->[$i];
136 my $propinfo = $returnprops->{$prop} // {};
137
138 my $title = $propinfo->{title} // $prop;
139 my $cutoff = $propinfo->{print_width} // $propinfo->{maxLength};
140
141 # calculate maximal print width and cutoff
142 my $titlelen = length($title);
143
144 my $longest = $titlelen;
145 foreach my $coldata (@$tabledata) {
146 my $rowdata = $coldata->{rowdata}->{$prop};
147 $longest = $rowdata->{width} if $rowdata->{width} > $longest;
148 }
149 $cutoff = $longest if !defined($cutoff) || $cutoff > $longest;
150
151 $colopts->{$prop} = {
152 title => $title,
153 cutoff => $cutoff,
154 };
155
156 if ($border) {
157 if ($i == 0 && ($column_count == 1)) {
158 if ($utf8) {
159 $formatstring .= "│ %-${cutoff}s │";
160 $borderstring_t .= "┌─" . ('─' x $cutoff) . "─┐";
161 $borderstring_m .= "├─" . ('─' x $cutoff) . "─┤";
162 $borderstring_b .= "└─" . ('─' x $cutoff) . "─┘";
163 } else {
164 $formatstring .= "| %-${cutoff}s |";
165 $borderstring_m .= "+-" . ('-' x $cutoff) . "-+";
166 }
167 } elsif ($i == 0) {
168 if ($utf8) {
169 $formatstring .= "│ %-${cutoff}s ";
170 $borderstring_t .= "┌─" . ('─' x $cutoff) . '─';
171 $borderstring_m .= "├─" . ('─' x $cutoff) . '─';
172 $borderstring_b .= "└─" . ('─' x $cutoff) . '─';
173 } else {
174 $formatstring .= "| %-${cutoff}s ";
175 $borderstring_m .= "+-" . ('-' x $cutoff) . '-';
176 }
177 } elsif ($i == ($column_count - 1)) {
178 if ($utf8) {
179 $formatstring .= "│ %-${cutoff}s │";
180 $borderstring_t .= "┬─" . ('─' x $cutoff) . "─┐";
181 $borderstring_m .= "┼─" . ('─' x $cutoff) . "─┤";
182 $borderstring_b .= "┴─" . ('─' x $cutoff) . "─┘";
183 } else {
184 $formatstring .= "| %-${cutoff}s |";
185 $borderstring_m .= "+-" . ('-' x $cutoff) . "-+";
186 }
187 } else {
188 if ($utf8) {
189 $formatstring .= "│ %-${cutoff}s ";
190 $borderstring_t .= "┬─" . ('─' x $cutoff) . '─';
191 $borderstring_m .= "┼─" . ('─' x $cutoff) . '─';
192 $borderstring_b .= "┴─" . ('─' x $cutoff) . '─';
193 } else {
194 $formatstring .= "| %-${cutoff}s ";
195 $borderstring_m .= "+-" . ('-' x $cutoff) . '-';
196 }
197 }
198 } else {
199 # skip alignment and cutoff on last column
200 $formatstring .= ($i == ($column_count - 1)) ? "%s" : "%-${cutoff}s ";
201 }
202 }
203
204 $borderstring_t = $borderstring_m if !length($borderstring_t);
205 $borderstring_b = $borderstring_m if !length($borderstring_b);
206
207 my $writeln = sub {
208 my ($text) = @_;
209
210 if ($columns) {
211 print encode($encoding, substr($text, 0, $columns) . "\n");
212 } else {
213 print encode($encoding, $text) . "\n";
214 }
215 };
216
217 $writeln->($borderstring_t) if $border;
218 my $text = sprintf $formatstring, map { $colopts->{$_}->{title} } @$props_to_print;
219 $writeln->($text);
220
221 foreach my $coldata (@$tabledata) {
222 $writeln->($borderstring_m) if $border;
223
224 for (my $i = 0; $i < $coldata->{height}; $i++) {
225
226 $text = sprintf $formatstring, map {
227 substr($coldata->{rowdata}->{$_}->{lines}->[$i] // '', 0, $colopts->{$_}->{cutoff});
228 } @$props_to_print;
229
230 $writeln->($text);
231 }
232 }
233
234 $writeln->($borderstring_b) if $border;
235 }
236
237 # prints the result of an API GET call returning an array as a table.
238 # takes formatting information from the results property of the call
239 # if $props_to_print is provided, prints only those columns. otherwise
240 # takes all fields of the results property, with a fallback
241 # to all fields occuring in items of $data.
242 sub print_api_list {
243 my ($data, $result_schema, $props_to_print, $options) = @_;
244
245 die "can only print object lists\n"
246 if !($result_schema->{type} eq 'array' && $result_schema->{items}->{type} eq 'object');
247
248 my $returnprops = $result_schema->{items}->{properties};
249
250 if (!defined($props_to_print)) {
251 $props_to_print = [ sort keys %$returnprops ];
252 if (!scalar(@$props_to_print)) {
253 my $all_props = {};
254 foreach my $obj (@{$data}) {
255 foreach my $key (keys %{$obj}) {
256 $all_props->{ $key } = 1;
257 }
258 }
259 $props_to_print = [ sort keys %{$all_props} ];
260 }
261 die "unable to detect list properties\n" if !scalar(@$props_to_print);
262 }
263
264 print_text_table($data, $returnprops, $props_to_print, $options);
265 }
266
267 sub print_api_result {
268 my ($format, $data, $result_schema, $props_to_print, $options) = @_;
269
270 if (!defined($options)) {
271 $options = query_terminal_options({});
272 } else {
273 $options = { %$options }; # copy
274 }
275
276 return if $result_schema->{type} eq 'null';
277
278 if ($format eq 'json') {
279 # Note: we always use utf8 encoding for json format
280 print to_json($data, {utf8 => 1, allow_nonref => 1, canonical => 1, pretty => 1 });
281 } elsif ($format eq 'text' || $format eq 'plain') {
282 my $encoding = $options->{encoding} // 'UTF-8';
283 my $type = $result_schema->{type};
284 if ($type eq 'object') {
285 $props_to_print = [ sort keys %$data ] if !defined($props_to_print);
286 my $kvstore = [];
287 foreach my $key (@$props_to_print) {
288 push @$kvstore, { key => $key, value => data_to_text($data->{$key}, $result_schema->{properties}->{$key}) };
289 }
290 my $schema = { type => 'array', items => { type => 'object' }};
291 $options->{border} = $format eq 'text';
292 print_api_list($kvstore, $schema, ['key', 'value'], $options);
293 } elsif ($type eq 'array') {
294 return if !scalar(@$data);
295 my $item_type = $result_schema->{items}->{type};
296 if ($item_type eq 'object') {
297 $options->{border} = $format eq 'text';
298 print_api_list($data, $result_schema, $props_to_print, $options);
299 } else {
300 foreach my $entry (@$data) {
301 print encode($encoding, data_to_text($entry) . "\n");
302 }
303 }
304 } else {
305 print encode($encoding, "$data\n");
306 }
307 } else {
308 die "internal error: unknown output format"; # should not happen
309 }
310 }
311
312 1;