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