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