]>
Commit | Line | Data |
---|---|---|
c2bcfdb2 DM |
1 | package PVE::APIClient::CLIFormatter; |
2 | ||
3 | use strict; | |
4 | use warnings; | |
5 | use I18N::Langinfo; | |
bb27fea1 | 6 | use POSIX qw(strftime); |
74ad9c37 | 7 | use CPAN::Meta::YAML; # comes with perl-modules |
c2bcfdb2 DM |
8 | |
9 | use PVE::APIClient::JSONSchema; | |
10 | use PVE::APIClient::PTY; | |
11 | use JSON; | |
12 | use utf8; | |
13 | use Encode; | |
14 | ||
bb27fea1 DM |
15 | sub render_timestamp { |
16 | my ($epoch) = @_; | |
17 | ||
18 | # ISO 8601 date format | |
19 | return strftime("%F %H:%M:%S", localtime($epoch)); | |
20 | } | |
21 | ||
22 | PVE::APIClient::JSONSchema::register_renderer('timestamp', \&render_timestamp); | |
23 | ||
24 | sub render_timestamp_gmt { | |
25 | my ($epoch) = @_; | |
26 | ||
27 | # ISO 8601 date format, standard Greenwich time zone | |
28 | return strftime("%F %H:%M:%S", gmtime($epoch)); | |
29 | } | |
30 | ||
31 | PVE::APIClient::JSONSchema::register_renderer('timestamp_gmt', \&render_timestamp_gmt); | |
32 | ||
d012b98c DM |
33 | sub render_duration { |
34 | my ($duration_in_seconds) = @_; | |
35 | ||
36 | my $text = ''; | |
37 | my $rest = $duration_in_seconds; | |
38 | ||
39 | my $step = sub { | |
40 | my ($unit, $unitlength) = @_; | |
41 | ||
42 | if ((my $v = int($rest/$unitlength)) > 0) { | |
43 | $text .= " " if length($text); | |
44 | $text .= "${v}${unit}"; | |
45 | $rest -= $v * $unitlength; | |
46 | } | |
47 | }; | |
48 | ||
49 | $step->('w', 7*24*3600); | |
50 | $step->('d', 24*3600); | |
51 | $step->('h', 3600); | |
52 | $step->('m', 60); | |
53 | $step->('s', 1); | |
54 | ||
55 | return $text; | |
56 | } | |
57 | ||
58 | PVE::APIClient::JSONSchema::register_renderer('duration', \&render_duration); | |
59 | ||
60 | sub render_fraction_as_percentage { | |
61 | my ($fraction) = @_; | |
62 | ||
63 | return sprintf("%.2f%%", $fraction*100); | |
64 | } | |
65 | ||
66 | PVE::APIClient::JSONSchema::register_renderer( | |
67 | 'fraction_as_percentage', \&render_fraction_as_percentage); | |
68 | ||
69 | sub render_bytes { | |
70 | my ($value) = @_; | |
71 | ||
72 | my @units = qw(B KiB MiB GiB TiB PiB); | |
73 | ||
74 | my $max_unit = 0; | |
75 | if ($value > 1023) { | |
76 | $max_unit = int(log($value)/log(1024)); | |
77 | $value /= 1024**($max_unit); | |
78 | } | |
74ad9c37 DM |
79 | my $unit = $units[$max_unit]; |
80 | return sprintf "%.2f $unit", $value; | |
d012b98c DM |
81 | } |
82 | ||
83 | PVE::APIClient::JSONSchema::register_renderer('bytes', \&render_bytes); | |
84 | ||
74ad9c37 DM |
85 | sub render_yaml { |
86 | my ($value) = @_; | |
87 | ||
88 | my $data = CPAN::Meta::YAML::Dump($value); | |
89 | $data =~ s/^---[\n\s]//; # remove yaml marker | |
90 | ||
91 | return $data; | |
92 | } | |
93 | ||
94 | PVE::APIClient::JSONSchema::register_renderer('yaml', \&render_yaml); | |
95 | ||
c2bcfdb2 DM |
96 | sub query_terminal_options { |
97 | my ($options) = @_; | |
98 | ||
99 | $options //= {}; | |
100 | ||
101 | if (-t STDOUT) { | |
102 | ($options->{columns}) = PVE::APIClient::PTY::tcgetsize(*STDOUT); | |
103 | } | |
104 | ||
105 | $options->{encoding} = I18N::Langinfo::langinfo(I18N::Langinfo::CODESET()); | |
106 | ||
107 | $options->{utf8} = 1 if $options->{encoding} eq 'UTF-8'; | |
108 | ||
109 | return $options; | |
110 | } | |
111 | ||
112 | sub data_to_text { | |
74ad9c37 | 113 | my ($data, $propdef, $options, $terminal_opts) = @_; |
c2bcfdb2 DM |
114 | |
115 | return '' if !defined($data); | |
116 | ||
74ad9c37 DM |
117 | $terminal_opts //= {}; |
118 | ||
874acd77 DM |
119 | my $human_readable = $options->{'human-readable'} // 1; |
120 | ||
121 | if ($human_readable && defined($propdef)) { | |
c2bcfdb2 DM |
122 | if (my $type = $propdef->{type}) { |
123 | if ($type eq 'boolean') { | |
124 | return $data ? 1 : 0; | |
125 | } | |
126 | } | |
127 | if (!defined($data) && defined($propdef->{default})) { | |
128 | return "($propdef->{default})"; | |
129 | } | |
130 | if (defined(my $renderer = $propdef->{renderer})) { | |
131 | my $code = PVE::APIClient::JSONSchema::get_renderer($renderer); | |
132 | die "internal error: unknown renderer '$renderer'" if !$code; | |
74ad9c37 | 133 | return $code->($data, $options, $terminal_opts); |
c2bcfdb2 DM |
134 | } |
135 | } | |
136 | ||
137 | if (my $class = ref($data)) { | |
74ad9c37 DM |
138 | # JSON::PP::Boolean requires allow_nonref |
139 | return to_json($data, { allow_nonref => 1, canonical => 1 }); | |
c2bcfdb2 DM |
140 | } else { |
141 | return "$data"; | |
142 | } | |
143 | } | |
144 | ||
145 | # prints a formatted table with a title row. | |
146 | # $data - the data to print (array of objects) | |
147 | # $returnprops -json schema property description | |
148 | # $props_to_print - ordered list of properties to print | |
149 | # $options | |
74ad9c37 | 150 | # - sort_key: can be used to sort after a specific column, if it isn't set we sort |
c2bcfdb2 DM |
151 | # after the leftmost column (with no undef value in $data) this can be |
152 | # turned off by passing 0 as sort_key | |
874acd77 DM |
153 | # - noborder: print without asciiart border |
154 | # - noheader: print without table header | |
c2bcfdb2 DM |
155 | # - columns: limit output width (if > 0) |
156 | # - utf8: use utf8 characters for table delimiters | |
157 | ||
158 | sub print_text_table { | |
74ad9c37 DM |
159 | my ($data, $returnprops, $props_to_print, $options, $terminal_opts) = @_; |
160 | ||
161 | $terminal_opts //= query_terminal_options({}); | |
c2bcfdb2 DM |
162 | |
163 | my $sort_key = $options->{sort_key}; | |
874acd77 DM |
164 | my $border = !$options->{noborder}; |
165 | my $header = !$options->{noheader}; | |
c2bcfdb2 | 166 | |
74ad9c37 DM |
167 | my $columns = $terminal_opts->{columns}; |
168 | my $utf8 = $terminal_opts->{utf8}; | |
169 | my $encoding = $terminal_opts->{encoding} // 'UTF-8'; | |
c2bcfdb2 | 170 | |
74ad9c37 DM |
171 | $sort_key //= $props_to_print->[0]; |
172 | ||
173 | if (defined($sort_key) && $sort_key ne 0) { | |
c2bcfdb2 DM |
174 | my $type = $returnprops->{$sort_key}->{type} // 'string'; |
175 | if ($type eq 'integer' || $type eq 'number') { | |
176 | @$data = sort { $a->{$sort_key} <=> $b->{$sort_key} } @$data; | |
177 | } else { | |
178 | @$data = sort { $a->{$sort_key} cmp $b->{$sort_key} } @$data; | |
179 | } | |
180 | } | |
181 | ||
182 | my $colopts = {}; | |
183 | ||
184 | my $borderstring_m = ''; | |
185 | my $borderstring_b = ''; | |
186 | my $borderstring_t = ''; | |
187 | my $formatstring = ''; | |
188 | ||
189 | my $column_count = scalar(@$props_to_print); | |
190 | ||
191 | my $tabledata = []; | |
192 | ||
193 | foreach my $entry (@$data) { | |
194 | ||
195 | my $height = 1; | |
196 | my $rowdata = {}; | |
197 | ||
198 | for (my $i = 0; $i < $column_count; $i++) { | |
199 | my $prop = $props_to_print->[$i]; | |
200 | my $propinfo = $returnprops->{$prop} // {}; | |
201 | ||
74ad9c37 | 202 | my $text = data_to_text($entry->{$prop}, $propinfo, $options, $terminal_opts); |
c2bcfdb2 DM |
203 | my $lines = [ split(/\n/, $text) ]; |
204 | my $linecount = scalar(@$lines); | |
205 | $height = $linecount if $linecount > $height; | |
206 | ||
207 | my $width = 0; | |
208 | foreach my $line (@$lines) { | |
209 | my $len = length($line); | |
210 | $width = $len if $len > $width; | |
211 | } | |
212 | ||
74ad9c37 DM |
213 | $width = ($width =~ m/^(\d+)$/) ? int($1) : 0; # untaint int |
214 | ||
c2bcfdb2 DM |
215 | $rowdata->{$prop} = { |
216 | lines => $lines, | |
217 | width => $width, | |
218 | }; | |
219 | } | |
220 | ||
221 | push @$tabledata, { | |
222 | height => $height, | |
223 | rowdata => $rowdata, | |
224 | }; | |
225 | } | |
226 | ||
227 | for (my $i = 0; $i < $column_count; $i++) { | |
228 | my $prop = $props_to_print->[$i]; | |
229 | my $propinfo = $returnprops->{$prop} // {}; | |
74ad9c37 DM |
230 | my $type = $propinfo->{type} // 'string'; |
231 | my $alignstr = ($type eq 'integer' || $type eq 'number') ? '' : '-'; | |
c2bcfdb2 DM |
232 | |
233 | my $title = $propinfo->{title} // $prop; | |
234 | my $cutoff = $propinfo->{print_width} // $propinfo->{maxLength}; | |
235 | ||
236 | # calculate maximal print width and cutoff | |
237 | my $titlelen = length($title); | |
238 | ||
239 | my $longest = $titlelen; | |
240 | foreach my $coldata (@$tabledata) { | |
241 | my $rowdata = $coldata->{rowdata}->{$prop}; | |
242 | $longest = $rowdata->{width} if $rowdata->{width} > $longest; | |
243 | } | |
244 | $cutoff = $longest if !defined($cutoff) || $cutoff > $longest; | |
245 | ||
246 | $colopts->{$prop} = { | |
247 | title => $title, | |
248 | cutoff => $cutoff, | |
249 | }; | |
250 | ||
251 | if ($border) { | |
252 | if ($i == 0 && ($column_count == 1)) { | |
253 | if ($utf8) { | |
74ad9c37 | 254 | $formatstring .= "│ %$alignstr${cutoff}s │"; |
c2bcfdb2 DM |
255 | $borderstring_t .= "┌─" . ('─' x $cutoff) . "─┐"; |
256 | $borderstring_m .= "├─" . ('─' x $cutoff) . "─┤"; | |
257 | $borderstring_b .= "└─" . ('─' x $cutoff) . "─┘"; | |
258 | } else { | |
74ad9c37 | 259 | $formatstring .= "| %$alignstr${cutoff}s |"; |
c2bcfdb2 DM |
260 | $borderstring_m .= "+-" . ('-' x $cutoff) . "-+"; |
261 | } | |
262 | } elsif ($i == 0) { | |
263 | if ($utf8) { | |
74ad9c37 | 264 | $formatstring .= "│ %$alignstr${cutoff}s "; |
c2bcfdb2 DM |
265 | $borderstring_t .= "┌─" . ('─' x $cutoff) . '─'; |
266 | $borderstring_m .= "├─" . ('─' x $cutoff) . '─'; | |
267 | $borderstring_b .= "└─" . ('─' x $cutoff) . '─'; | |
268 | } else { | |
74ad9c37 | 269 | $formatstring .= "| %$alignstr${cutoff}s "; |
c2bcfdb2 DM |
270 | $borderstring_m .= "+-" . ('-' x $cutoff) . '-'; |
271 | } | |
272 | } elsif ($i == ($column_count - 1)) { | |
273 | if ($utf8) { | |
74ad9c37 | 274 | $formatstring .= "│ %$alignstr${cutoff}s │"; |
c2bcfdb2 DM |
275 | $borderstring_t .= "┬─" . ('─' x $cutoff) . "─┐"; |
276 | $borderstring_m .= "┼─" . ('─' x $cutoff) . "─┤"; | |
277 | $borderstring_b .= "┴─" . ('─' x $cutoff) . "─┘"; | |
278 | } else { | |
74ad9c37 | 279 | $formatstring .= "| %$alignstr${cutoff}s |"; |
c2bcfdb2 DM |
280 | $borderstring_m .= "+-" . ('-' x $cutoff) . "-+"; |
281 | } | |
282 | } else { | |
283 | if ($utf8) { | |
74ad9c37 | 284 | $formatstring .= "│ %$alignstr${cutoff}s "; |
c2bcfdb2 DM |
285 | $borderstring_t .= "┬─" . ('─' x $cutoff) . '─'; |
286 | $borderstring_m .= "┼─" . ('─' x $cutoff) . '─'; | |
287 | $borderstring_b .= "┴─" . ('─' x $cutoff) . '─'; | |
288 | } else { | |
74ad9c37 | 289 | $formatstring .= "| %$alignstr${cutoff}s "; |
c2bcfdb2 DM |
290 | $borderstring_m .= "+-" . ('-' x $cutoff) . '-'; |
291 | } | |
292 | } | |
293 | } else { | |
294 | # skip alignment and cutoff on last column | |
74ad9c37 | 295 | $formatstring .= ($i == ($column_count - 1)) ? "%s" : "%$alignstr${cutoff}s "; |
c2bcfdb2 DM |
296 | } |
297 | } | |
298 | ||
299 | $borderstring_t = $borderstring_m if !length($borderstring_t); | |
300 | $borderstring_b = $borderstring_m if !length($borderstring_b); | |
301 | ||
302 | my $writeln = sub { | |
303 | my ($text) = @_; | |
304 | ||
305 | if ($columns) { | |
306 | print encode($encoding, substr($text, 0, $columns) . "\n"); | |
307 | } else { | |
308 | print encode($encoding, $text) . "\n"; | |
309 | } | |
310 | }; | |
311 | ||
312 | $writeln->($borderstring_t) if $border; | |
c2bcfdb2 | 313 | |
874acd77 DM |
314 | if ($header) { |
315 | my $text = sprintf $formatstring, map { $colopts->{$_}->{title} } @$props_to_print; | |
316 | $writeln->($text); | |
317 | } | |
318 | ||
319 | for (my $i = 0; $i < scalar(@$tabledata); $i++) { | |
320 | my $coldata = $tabledata->[$i]; | |
321 | ||
322 | $writeln->($borderstring_m) if $border && ($i != 0 || $header); | |
c2bcfdb2 DM |
323 | |
324 | for (my $i = 0; $i < $coldata->{height}; $i++) { | |
325 | ||
874acd77 | 326 | my $text = sprintf $formatstring, map { |
c2bcfdb2 DM |
327 | substr($coldata->{rowdata}->{$_}->{lines}->[$i] // '', 0, $colopts->{$_}->{cutoff}); |
328 | } @$props_to_print; | |
329 | ||
330 | $writeln->($text); | |
331 | } | |
332 | } | |
333 | ||
334 | $writeln->($borderstring_b) if $border; | |
335 | } | |
336 | ||
d012b98c DM |
337 | sub extract_properties_to_print { |
338 | my ($propdef) = @_; | |
339 | ||
340 | my $required = []; | |
341 | my $optional = []; | |
342 | ||
343 | foreach my $key (keys %$propdef) { | |
344 | my $prop = $propdef->{$key}; | |
345 | if ($prop->{optional}) { | |
346 | push @$optional, $key; | |
347 | } else { | |
348 | push @$required, $key; | |
349 | } | |
350 | } | |
351 | ||
352 | return [ sort(@$required), sort(@$optional) ]; | |
353 | } | |
354 | ||
c2bcfdb2 DM |
355 | # prints the result of an API GET call returning an array as a table. |
356 | # takes formatting information from the results property of the call | |
357 | # if $props_to_print is provided, prints only those columns. otherwise | |
358 | # takes all fields of the results property, with a fallback | |
359 | # to all fields occuring in items of $data. | |
360 | sub print_api_list { | |
74ad9c37 | 361 | my ($data, $result_schema, $props_to_print, $options, $terminal_opts) = @_; |
c2bcfdb2 DM |
362 | |
363 | die "can only print object lists\n" | |
364 | if !($result_schema->{type} eq 'array' && $result_schema->{items}->{type} eq 'object'); | |
365 | ||
366 | my $returnprops = $result_schema->{items}->{properties}; | |
367 | ||
d012b98c DM |
368 | $props_to_print = extract_properties_to_print($returnprops) |
369 | if !defined($props_to_print); | |
370 | ||
371 | if (!scalar(@$props_to_print)) { | |
372 | my $all_props = {}; | |
373 | foreach my $obj (@$data) { | |
374 | foreach my $key (keys %$obj) { | |
375 | $all_props->{$key} = 1; | |
c2bcfdb2 | 376 | } |
c2bcfdb2 | 377 | } |
d012b98c | 378 | $props_to_print = [ sort keys %{$all_props} ]; |
c2bcfdb2 DM |
379 | } |
380 | ||
d012b98c DM |
381 | die "unable to detect list properties\n" if !scalar(@$props_to_print); |
382 | ||
74ad9c37 | 383 | print_text_table($data, $returnprops, $props_to_print, $options, $terminal_opts); |
c2bcfdb2 DM |
384 | } |
385 | ||
74ad9c37 DM |
386 | my $guess_type = sub { |
387 | my $data = shift; | |
874acd77 | 388 | |
74ad9c37 DM |
389 | return 'null' if !defined($data); |
390 | ||
391 | my $class = ref($data); | |
392 | return 'string' if !$class; | |
c2bcfdb2 | 393 | |
74ad9c37 DM |
394 | if ($class eq 'HASH') { |
395 | return 'object'; | |
396 | } elsif ($class eq 'ARRAY') { | |
397 | return 'array'; | |
c2bcfdb2 | 398 | } else { |
74ad9c37 | 399 | return 'string'; # better than nothing |
c2bcfdb2 | 400 | } |
74ad9c37 DM |
401 | }; |
402 | ||
403 | sub print_api_result { | |
404 | my ($data, $result_schema, $props_to_print, $options, $terminal_opts) = @_; | |
405 | ||
406 | return if $options->{quiet}; | |
407 | ||
408 | $terminal_opts //= query_terminal_options({}); | |
c2bcfdb2 | 409 | |
5aa25367 | 410 | my $format = $options->{'output-format'} // 'text'; |
874acd77 | 411 | |
74ad9c37 DM |
412 | if ($result_schema && defined($result_schema->{type})) { |
413 | return if $result_schema->{type} eq 'null'; | |
414 | } else { | |
415 | my $type = $guess_type->($data); | |
416 | $result_schema = { type => $type }; | |
417 | $result_schema->{items} = { type => $guess_type->($data->[0]) } if $type eq 'array'; | |
418 | } | |
c2bcfdb2 | 419 | |
74ad9c37 DM |
420 | if ($format eq 'yaml') { |
421 | print encode('UTF-8', CPAN::Meta::YAML::Dump($data)); | |
422 | } elsif ($format eq 'json') { | |
874acd77 DM |
423 | # Note: we always use utf8 encoding for json format |
424 | print to_json($data, {utf8 => 1, allow_nonref => 1, canonical => 1 }) . "\n"; | |
425 | } elsif ($format eq 'json-pretty') { | |
c2bcfdb2 DM |
426 | # Note: we always use utf8 encoding for json format |
427 | print to_json($data, {utf8 => 1, allow_nonref => 1, canonical => 1, pretty => 1 }); | |
874acd77 | 428 | } elsif ($format eq 'text') { |
c2bcfdb2 DM |
429 | my $encoding = $options->{encoding} // 'UTF-8'; |
430 | my $type = $result_schema->{type}; | |
431 | if ($type eq 'object') { | |
d012b98c DM |
432 | $props_to_print = extract_properties_to_print($result_schema->{properties}) |
433 | if !defined($props_to_print); | |
434 | $props_to_print = [ sort keys %$data ] if !scalar(@$props_to_print); | |
c2bcfdb2 DM |
435 | my $kvstore = []; |
436 | foreach my $key (@$props_to_print) { | |
874acd77 | 437 | next if !defined($data->{$key}); |
74ad9c37 | 438 | push @$kvstore, { key => $key, value => data_to_text($data->{$key}, $result_schema->{properties}->{$key}, $options, $terminal_opts) }; |
c2bcfdb2 DM |
439 | } |
440 | my $schema = { type => 'array', items => { type => 'object' }}; | |
74ad9c37 | 441 | print_api_list($kvstore, $schema, ['key', 'value'], $options, $terminal_opts); |
c2bcfdb2 DM |
442 | } elsif ($type eq 'array') { |
443 | return if !scalar(@$data); | |
444 | my $item_type = $result_schema->{items}->{type}; | |
445 | if ($item_type eq 'object') { | |
74ad9c37 | 446 | print_api_list($data, $result_schema, $props_to_print, $options, $terminal_opts); |
c2bcfdb2 | 447 | } else { |
bb27fea1 DM |
448 | my $kvstore = []; |
449 | foreach my $value (@$data) { | |
450 | push @$kvstore, { value => $value }; | |
c2bcfdb2 | 451 | } |
bb27fea1 | 452 | my $schema = { type => 'array', items => { type => 'object', properties => { value => $result_schema->{items} }}}; |
74ad9c37 | 453 | print_api_list($kvstore, $schema, ['value'], { %$options, noheader => 1 }, $terminal_opts); |
c2bcfdb2 DM |
454 | } |
455 | } else { | |
456 | print encode($encoding, "$data\n"); | |
457 | } | |
458 | } else { | |
459 | die "internal error: unknown output format"; # should not happen | |
460 | } | |
461 | } | |
462 | ||
74ad9c37 DM |
463 | sub print_api_result_plain { |
464 | my ($data, $result_schema, $props_to_print, $options) = @_; | |
465 | ||
466 | # avoid borders and header, ignore terminal width | |
467 | $options = $options ? { %$options } : {}; # copy | |
468 | ||
469 | $options->{noheader} //= 1; | |
470 | $options->{noborder} //= 1; | |
471 | ||
472 | print_api_result($data, $result_schema, $props_to_print, $options, {}); | |
473 | } | |
474 | ||
c2bcfdb2 | 475 | 1; |