]>
Commit | Line | Data |
---|---|---|
c2bcfdb2 DM |
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 | ||
d012b98c DM |
13 | sub render_duration { |
14 | my ($duration_in_seconds) = @_; | |
15 | ||
16 | my $text = ''; | |
17 | my $rest = $duration_in_seconds; | |
18 | ||
19 | my $step = sub { | |
20 | my ($unit, $unitlength) = @_; | |
21 | ||
22 | if ((my $v = int($rest/$unitlength)) > 0) { | |
23 | $text .= " " if length($text); | |
24 | $text .= "${v}${unit}"; | |
25 | $rest -= $v * $unitlength; | |
26 | } | |
27 | }; | |
28 | ||
29 | $step->('w', 7*24*3600); | |
30 | $step->('d', 24*3600); | |
31 | $step->('h', 3600); | |
32 | $step->('m', 60); | |
33 | $step->('s', 1); | |
34 | ||
35 | return $text; | |
36 | } | |
37 | ||
38 | PVE::APIClient::JSONSchema::register_renderer('duration', \&render_duration); | |
39 | ||
40 | sub render_fraction_as_percentage { | |
41 | my ($fraction) = @_; | |
42 | ||
43 | return sprintf("%.2f%%", $fraction*100); | |
44 | } | |
45 | ||
46 | PVE::APIClient::JSONSchema::register_renderer( | |
47 | 'fraction_as_percentage', \&render_fraction_as_percentage); | |
48 | ||
49 | sub render_bytes { | |
50 | my ($value) = @_; | |
51 | ||
52 | my @units = qw(B KiB MiB GiB TiB PiB); | |
53 | ||
54 | my $max_unit = 0; | |
55 | if ($value > 1023) { | |
56 | $max_unit = int(log($value)/log(1024)); | |
57 | $value /= 1024**($max_unit); | |
58 | } | |
59 | ||
60 | return sprintf "%.2f $units[$max_unit]", $value; | |
61 | } | |
62 | ||
63 | PVE::APIClient::JSONSchema::register_renderer('bytes', \&render_bytes); | |
64 | ||
c2bcfdb2 DM |
65 | sub query_terminal_options { |
66 | my ($options) = @_; | |
67 | ||
68 | $options //= {}; | |
69 | ||
70 | if (-t STDOUT) { | |
71 | ($options->{columns}) = PVE::APIClient::PTY::tcgetsize(*STDOUT); | |
72 | } | |
73 | ||
74 | $options->{encoding} = I18N::Langinfo::langinfo(I18N::Langinfo::CODESET()); | |
75 | ||
76 | $options->{utf8} = 1 if $options->{encoding} eq 'UTF-8'; | |
77 | ||
78 | return $options; | |
79 | } | |
80 | ||
81 | sub data_to_text { | |
82 | my ($data, $propdef) = @_; | |
83 | ||
84 | return '' if !defined($data); | |
85 | ||
86 | if (defined($propdef)) { | |
87 | if (my $type = $propdef->{type}) { | |
88 | if ($type eq 'boolean') { | |
89 | return $data ? 1 : 0; | |
90 | } | |
91 | } | |
92 | if (!defined($data) && defined($propdef->{default})) { | |
93 | return "($propdef->{default})"; | |
94 | } | |
95 | if (defined(my $renderer = $propdef->{renderer})) { | |
96 | my $code = PVE::APIClient::JSONSchema::get_renderer($renderer); | |
97 | die "internal error: unknown renderer '$renderer'" if !$code; | |
98 | return $code->($data); | |
99 | } | |
100 | } | |
101 | ||
102 | if (my $class = ref($data)) { | |
103 | return to_json($data, { canonical => 1 }); | |
104 | } else { | |
105 | return "$data"; | |
106 | } | |
107 | } | |
108 | ||
109 | # prints a formatted table with a title row. | |
110 | # $data - the data to print (array of objects) | |
111 | # $returnprops -json schema property description | |
112 | # $props_to_print - ordered list of properties to print | |
113 | # $options | |
114 | # - sort_key: can be used to sort after a column, if it isn't set we sort | |
115 | # after the leftmost column (with no undef value in $data) this can be | |
116 | # turned off by passing 0 as sort_key | |
117 | # - border: print with/without table header and asciiart border | |
118 | # - columns: limit output width (if > 0) | |
119 | # - utf8: use utf8 characters for table delimiters | |
120 | ||
121 | sub print_text_table { | |
122 | my ($data, $returnprops, $props_to_print, $options) = @_; | |
123 | ||
124 | my $sort_key = $options->{sort_key}; | |
125 | my $border = $options->{border}; | |
126 | my $columns = $options->{columns}; | |
127 | my $utf8 = $options->{utf8}; | |
128 | my $encoding = $options->{encoding} // 'UTF-8'; | |
129 | ||
130 | if (!defined($sort_key) || $sort_key eq 0) { | |
131 | $sort_key = $props_to_print->[0]; | |
132 | } | |
133 | ||
134 | if (defined($sort_key)) { | |
135 | my $type = $returnprops->{$sort_key}->{type} // 'string'; | |
136 | if ($type eq 'integer' || $type eq 'number') { | |
137 | @$data = sort { $a->{$sort_key} <=> $b->{$sort_key} } @$data; | |
138 | } else { | |
139 | @$data = sort { $a->{$sort_key} cmp $b->{$sort_key} } @$data; | |
140 | } | |
141 | } | |
142 | ||
143 | my $colopts = {}; | |
144 | ||
145 | my $borderstring_m = ''; | |
146 | my $borderstring_b = ''; | |
147 | my $borderstring_t = ''; | |
148 | my $formatstring = ''; | |
149 | ||
150 | my $column_count = scalar(@$props_to_print); | |
151 | ||
152 | my $tabledata = []; | |
153 | ||
154 | foreach my $entry (@$data) { | |
155 | ||
156 | my $height = 1; | |
157 | my $rowdata = {}; | |
158 | ||
159 | for (my $i = 0; $i < $column_count; $i++) { | |
160 | my $prop = $props_to_print->[$i]; | |
161 | my $propinfo = $returnprops->{$prop} // {}; | |
162 | ||
163 | my $text = data_to_text($entry->{$prop}, $propinfo); | |
164 | my $lines = [ split(/\n/, $text) ]; | |
165 | my $linecount = scalar(@$lines); | |
166 | $height = $linecount if $linecount > $height; | |
167 | ||
168 | my $width = 0; | |
169 | foreach my $line (@$lines) { | |
170 | my $len = length($line); | |
171 | $width = $len if $len > $width; | |
172 | } | |
173 | ||
174 | $rowdata->{$prop} = { | |
175 | lines => $lines, | |
176 | width => $width, | |
177 | }; | |
178 | } | |
179 | ||
180 | push @$tabledata, { | |
181 | height => $height, | |
182 | rowdata => $rowdata, | |
183 | }; | |
184 | } | |
185 | ||
186 | for (my $i = 0; $i < $column_count; $i++) { | |
187 | my $prop = $props_to_print->[$i]; | |
188 | my $propinfo = $returnprops->{$prop} // {}; | |
189 | ||
190 | my $title = $propinfo->{title} // $prop; | |
191 | my $cutoff = $propinfo->{print_width} // $propinfo->{maxLength}; | |
192 | ||
193 | # calculate maximal print width and cutoff | |
194 | my $titlelen = length($title); | |
195 | ||
196 | my $longest = $titlelen; | |
197 | foreach my $coldata (@$tabledata) { | |
198 | my $rowdata = $coldata->{rowdata}->{$prop}; | |
199 | $longest = $rowdata->{width} if $rowdata->{width} > $longest; | |
200 | } | |
201 | $cutoff = $longest if !defined($cutoff) || $cutoff > $longest; | |
202 | ||
203 | $colopts->{$prop} = { | |
204 | title => $title, | |
205 | cutoff => $cutoff, | |
206 | }; | |
207 | ||
208 | if ($border) { | |
209 | if ($i == 0 && ($column_count == 1)) { | |
210 | if ($utf8) { | |
211 | $formatstring .= "│ %-${cutoff}s │"; | |
212 | $borderstring_t .= "┌─" . ('─' x $cutoff) . "─┐"; | |
213 | $borderstring_m .= "├─" . ('─' x $cutoff) . "─┤"; | |
214 | $borderstring_b .= "└─" . ('─' x $cutoff) . "─┘"; | |
215 | } else { | |
216 | $formatstring .= "| %-${cutoff}s |"; | |
217 | $borderstring_m .= "+-" . ('-' x $cutoff) . "-+"; | |
218 | } | |
219 | } elsif ($i == 0) { | |
220 | if ($utf8) { | |
221 | $formatstring .= "│ %-${cutoff}s "; | |
222 | $borderstring_t .= "┌─" . ('─' x $cutoff) . '─'; | |
223 | $borderstring_m .= "├─" . ('─' x $cutoff) . '─'; | |
224 | $borderstring_b .= "└─" . ('─' x $cutoff) . '─'; | |
225 | } else { | |
226 | $formatstring .= "| %-${cutoff}s "; | |
227 | $borderstring_m .= "+-" . ('-' x $cutoff) . '-'; | |
228 | } | |
229 | } elsif ($i == ($column_count - 1)) { | |
230 | if ($utf8) { | |
231 | $formatstring .= "│ %-${cutoff}s │"; | |
232 | $borderstring_t .= "┬─" . ('─' x $cutoff) . "─┐"; | |
233 | $borderstring_m .= "┼─" . ('─' x $cutoff) . "─┤"; | |
234 | $borderstring_b .= "┴─" . ('─' x $cutoff) . "─┘"; | |
235 | } else { | |
236 | $formatstring .= "| %-${cutoff}s |"; | |
237 | $borderstring_m .= "+-" . ('-' x $cutoff) . "-+"; | |
238 | } | |
239 | } else { | |
240 | if ($utf8) { | |
241 | $formatstring .= "│ %-${cutoff}s "; | |
242 | $borderstring_t .= "┬─" . ('─' x $cutoff) . '─'; | |
243 | $borderstring_m .= "┼─" . ('─' x $cutoff) . '─'; | |
244 | $borderstring_b .= "┴─" . ('─' x $cutoff) . '─'; | |
245 | } else { | |
246 | $formatstring .= "| %-${cutoff}s "; | |
247 | $borderstring_m .= "+-" . ('-' x $cutoff) . '-'; | |
248 | } | |
249 | } | |
250 | } else { | |
251 | # skip alignment and cutoff on last column | |
252 | $formatstring .= ($i == ($column_count - 1)) ? "%s" : "%-${cutoff}s "; | |
253 | } | |
254 | } | |
255 | ||
256 | $borderstring_t = $borderstring_m if !length($borderstring_t); | |
257 | $borderstring_b = $borderstring_m if !length($borderstring_b); | |
258 | ||
259 | my $writeln = sub { | |
260 | my ($text) = @_; | |
261 | ||
262 | if ($columns) { | |
263 | print encode($encoding, substr($text, 0, $columns) . "\n"); | |
264 | } else { | |
265 | print encode($encoding, $text) . "\n"; | |
266 | } | |
267 | }; | |
268 | ||
269 | $writeln->($borderstring_t) if $border; | |
270 | my $text = sprintf $formatstring, map { $colopts->{$_}->{title} } @$props_to_print; | |
271 | $writeln->($text); | |
272 | ||
273 | foreach my $coldata (@$tabledata) { | |
274 | $writeln->($borderstring_m) if $border; | |
275 | ||
276 | for (my $i = 0; $i < $coldata->{height}; $i++) { | |
277 | ||
278 | $text = sprintf $formatstring, map { | |
279 | substr($coldata->{rowdata}->{$_}->{lines}->[$i] // '', 0, $colopts->{$_}->{cutoff}); | |
280 | } @$props_to_print; | |
281 | ||
282 | $writeln->($text); | |
283 | } | |
284 | } | |
285 | ||
286 | $writeln->($borderstring_b) if $border; | |
287 | } | |
288 | ||
d012b98c DM |
289 | sub extract_properties_to_print { |
290 | my ($propdef) = @_; | |
291 | ||
292 | my $required = []; | |
293 | my $optional = []; | |
294 | ||
295 | foreach my $key (keys %$propdef) { | |
296 | my $prop = $propdef->{$key}; | |
297 | if ($prop->{optional}) { | |
298 | push @$optional, $key; | |
299 | } else { | |
300 | push @$required, $key; | |
301 | } | |
302 | } | |
303 | ||
304 | return [ sort(@$required), sort(@$optional) ]; | |
305 | } | |
306 | ||
c2bcfdb2 DM |
307 | # prints the result of an API GET call returning an array as a table. |
308 | # takes formatting information from the results property of the call | |
309 | # if $props_to_print is provided, prints only those columns. otherwise | |
310 | # takes all fields of the results property, with a fallback | |
311 | # to all fields occuring in items of $data. | |
312 | sub print_api_list { | |
313 | my ($data, $result_schema, $props_to_print, $options) = @_; | |
314 | ||
315 | die "can only print object lists\n" | |
316 | if !($result_schema->{type} eq 'array' && $result_schema->{items}->{type} eq 'object'); | |
317 | ||
318 | my $returnprops = $result_schema->{items}->{properties}; | |
319 | ||
d012b98c DM |
320 | $props_to_print = extract_properties_to_print($returnprops) |
321 | if !defined($props_to_print); | |
322 | ||
323 | if (!scalar(@$props_to_print)) { | |
324 | my $all_props = {}; | |
325 | foreach my $obj (@$data) { | |
326 | foreach my $key (keys %$obj) { | |
327 | $all_props->{$key} = 1; | |
c2bcfdb2 | 328 | } |
c2bcfdb2 | 329 | } |
d012b98c | 330 | $props_to_print = [ sort keys %{$all_props} ]; |
c2bcfdb2 DM |
331 | } |
332 | ||
d012b98c DM |
333 | die "unable to detect list properties\n" if !scalar(@$props_to_print); |
334 | ||
c2bcfdb2 DM |
335 | print_text_table($data, $returnprops, $props_to_print, $options); |
336 | } | |
337 | ||
338 | sub print_api_result { | |
339 | my ($format, $data, $result_schema, $props_to_print, $options) = @_; | |
340 | ||
341 | if (!defined($options)) { | |
342 | $options = query_terminal_options({}); | |
343 | } else { | |
344 | $options = { %$options }; # copy | |
345 | } | |
346 | ||
347 | return if $result_schema->{type} eq 'null'; | |
348 | ||
349 | if ($format eq 'json') { | |
350 | # Note: we always use utf8 encoding for json format | |
351 | print to_json($data, {utf8 => 1, allow_nonref => 1, canonical => 1, pretty => 1 }); | |
352 | } elsif ($format eq 'text' || $format eq 'plain') { | |
353 | my $encoding = $options->{encoding} // 'UTF-8'; | |
354 | my $type = $result_schema->{type}; | |
355 | if ($type eq 'object') { | |
d012b98c DM |
356 | $props_to_print = extract_properties_to_print($result_schema->{properties}) |
357 | if !defined($props_to_print); | |
358 | $props_to_print = [ sort keys %$data ] if !scalar(@$props_to_print); | |
c2bcfdb2 DM |
359 | my $kvstore = []; |
360 | foreach my $key (@$props_to_print) { | |
361 | push @$kvstore, { key => $key, value => data_to_text($data->{$key}, $result_schema->{properties}->{$key}) }; | |
362 | } | |
363 | my $schema = { type => 'array', items => { type => 'object' }}; | |
364 | $options->{border} = $format eq 'text'; | |
365 | print_api_list($kvstore, $schema, ['key', 'value'], $options); | |
366 | } elsif ($type eq 'array') { | |
367 | return if !scalar(@$data); | |
368 | my $item_type = $result_schema->{items}->{type}; | |
369 | if ($item_type eq 'object') { | |
370 | $options->{border} = $format eq 'text'; | |
371 | print_api_list($data, $result_schema, $props_to_print, $options); | |
372 | } else { | |
373 | foreach my $entry (@$data) { | |
374 | print encode($encoding, data_to_text($entry) . "\n"); | |
375 | } | |
376 | } | |
377 | } else { | |
378 | print encode($encoding, "$data\n"); | |
379 | } | |
380 | } else { | |
381 | die "internal error: unknown output format"; # should not happen | |
382 | } | |
383 | } | |
384 | ||
385 | 1; |