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