1 package PVE
::CLIFormatter
;
6 use POSIX
qw(strftime);
7 use CPAN
::Meta
::YAML
; # comes with perl-modules
15 sub render_timestamp
{
18 # ISO 8601 date format
19 return strftime
("%F %H:%M:%S", localtime($epoch));
22 PVE
::JSONSchema
::register_renderer
('timestamp', \
&render_timestamp
);
24 sub render_timestamp_gmt
{
27 # ISO 8601 date format, standard Greenwich time zone
28 return strftime
("%F %H:%M:%S", gmtime($epoch));
31 PVE
::JSONSchema
::register_renderer
('timestamp_gmt', \
&render_timestamp_gmt
);
34 my ($duration_in_seconds) = @_;
37 my $rest = $duration_in_seconds;
40 my ($unit, $unitlength) = @_;
42 if ((my $v = int($rest/$unitlength)) > 0) {
43 $text .= " " if length($text);
44 $text .= "${v}${unit}";
45 $rest -= $v * $unitlength;
49 $step->('w', 7*24*3600);
50 $step->('d', 24*3600);
58 PVE
::JSONSchema
::register_renderer
('duration', \
&render_duration
);
60 sub render_fraction_as_percentage
{
63 return sprintf("%.2f%%", $fraction*100);
66 PVE
::JSONSchema
::register_renderer
(
67 'fraction_as_percentage', \
&render_fraction_as_percentage
);
72 return $value if $value !~ m/^(\d+)$/;
73 $value = int($1); # untaint for sprintf
75 my @units = qw(B KiB MiB GiB TiB PiB);
79 $max_unit = int(log($value)/log(1024));
80 $value /= 1024**($max_unit);
83 return sprintf "%.2f $units[$max_unit]", $value;
86 PVE
::JSONSchema
::register_renderer
('bytes', \
&render_bytes
);
91 my $data = CPAN
::Meta
::YAML
::Dump
($value);
92 $data =~ s/^---[\n\s]//; # remove yaml marker
97 PVE
::JSONSchema
::register_renderer
('yaml', \
&render_yaml
);
99 sub query_terminal_options
{
105 ($options->{columns
}) = PVE
::PTY
::tcgetsize
(*STDOUT
);
108 $options->{encoding
} = I18N
::Langinfo
::langinfo
(I18N
::Langinfo
::CODESET
());
110 $options->{utf8
} = 1 if $options->{encoding
} eq 'UTF-8';
116 my ($data, $propdef, $options, $terminal_opts) = @_;
118 return '' if !defined($data);
120 $terminal_opts //= {};
122 my $human_readable = $options->{'human-readable'} // 1;
124 if ($human_readable && defined($propdef)) {
125 if (my $type = $propdef->{type
}) {
126 if ($type eq 'boolean') {
127 return $data ?
1 : 0;
130 if (!defined($data) && defined($propdef->{default})) {
131 return "($propdef->{default})";
133 if (defined(my $renderer = $propdef->{renderer
})) {
134 my $code = PVE
::JSONSchema
::get_renderer
($renderer);
135 die "internal error: unknown renderer '$renderer'" if !$code;
136 return $code->($data, $options, $terminal_opts);
140 if (my $class = ref($data)) {
141 # JSON::PP::Boolean requires allow_nonref
142 return to_json
($data, { allow_nonref
=> 1, canonical
=> 1 });
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
153 # - sort_key: can be used to sort after a specific column, if it isn't set we sort
154 # after the leftmost column (with no undef value in $data) this can be
155 # turned off by passing 0 as sort_key
156 # - noborder: print without asciiart border
157 # - noheader: print without table header
158 # - columns: limit output width (if > 0)
159 # - utf8: use utf8 characters for table delimiters
161 sub print_text_table
{
162 my ($data, $returnprops, $props_to_print, $options, $terminal_opts) = @_;
164 $terminal_opts //= query_terminal_options
({});
166 my $sort_key = $options->{sort_key
};
167 my $border = !$options->{noborder
};
168 my $header = !$options->{noheader
};
170 my $columns = $terminal_opts->{columns
};
171 my $utf8 = $terminal_opts->{utf8
};
172 my $encoding = $terminal_opts->{encoding
} // 'UTF-8';
174 $sort_key //= $props_to_print->[0];
176 if (defined($sort_key) && $sort_key ne 0) {
177 my $type = $returnprops->{$sort_key}->{type
} // 'string';
178 if ($type eq 'integer' || $type eq 'number') {
179 @$data = sort { $a->{$sort_key} <=> $b->{$sort_key} } @$data;
181 @$data = sort { $a->{$sort_key} cmp $b->{$sort_key} } @$data;
187 my $borderstring_m = '';
188 my $borderstring_b = '';
189 my $borderstring_t = '';
190 my $formatstring = '';
192 my $column_count = scalar(@$props_to_print);
196 foreach my $entry (@$data) {
201 for (my $i = 0; $i < $column_count; $i++) {
202 my $prop = $props_to_print->[$i];
203 my $propinfo = $returnprops->{$prop} // {};
205 my $text = data_to_text
($entry->{$prop}, $propinfo, $options, $terminal_opts);
206 my $lines = [ split(/\n/, $text) ];
207 my $linecount = scalar(@$lines);
208 $height = $linecount if $linecount > $height;
211 foreach my $line (@$lines) {
212 my $len = length($line);
213 $width = $len if $len > $width;
216 $width = ($width =~ m/^(\d+)$/) ?
int($1) : 0; # untaint int
218 $rowdata->{$prop} = {
230 for (my $i = 0; $i < $column_count; $i++) {
231 my $prop = $props_to_print->[$i];
232 my $propinfo = $returnprops->{$prop} // {};
233 my $type = $propinfo->{type
} // 'string';
234 my $alignstr = ($type eq 'integer' || $type eq 'number') ?
'' : '-';
236 my $title = $propinfo->{title
} // $prop;
237 my $cutoff = $propinfo->{print_width
} // $propinfo->{maxLength
};
239 # calculate maximal print width and cutoff
240 my $titlelen = length($title);
242 my $longest = $titlelen;
243 foreach my $coldata (@$tabledata) {
244 my $rowdata = $coldata->{rowdata
}->{$prop};
245 $longest = $rowdata->{width
} if $rowdata->{width
} > $longest;
247 $cutoff = $longest if !defined($cutoff) || $cutoff > $longest;
249 $colopts->{$prop} = {
255 if ($i == 0 && ($column_count == 1)) {
257 $formatstring .= "│ %$alignstr${cutoff}s │";
258 $borderstring_t .= "┌─" . ('─' x
$cutoff) . "─┐";
259 $borderstring_m .= "├─" . ('─' x
$cutoff) . "─┤";
260 $borderstring_b .= "└─" . ('─' x
$cutoff) . "─┘";
262 $formatstring .= "| %$alignstr${cutoff}s |";
263 $borderstring_m .= "+-" . ('-' x
$cutoff) . "-+";
267 $formatstring .= "│ %$alignstr${cutoff}s ";
268 $borderstring_t .= "┌─" . ('─' x
$cutoff) . '─';
269 $borderstring_m .= "├─" . ('─' x
$cutoff) . '─';
270 $borderstring_b .= "└─" . ('─' x
$cutoff) . '─';
272 $formatstring .= "| %$alignstr${cutoff}s ";
273 $borderstring_m .= "+-" . ('-' x
$cutoff) . '-';
275 } elsif ($i == ($column_count - 1)) {
277 $formatstring .= "│ %$alignstr${cutoff}s │";
278 $borderstring_t .= "┬─" . ('─' x
$cutoff) . "─┐";
279 $borderstring_m .= "┼─" . ('─' x
$cutoff) . "─┤";
280 $borderstring_b .= "┴─" . ('─' x
$cutoff) . "─┘";
282 $formatstring .= "| %$alignstr${cutoff}s |";
283 $borderstring_m .= "+-" . ('-' x
$cutoff) . "-+";
287 $formatstring .= "│ %$alignstr${cutoff}s ";
288 $borderstring_t .= "┬─" . ('─' x
$cutoff) . '─';
289 $borderstring_m .= "┼─" . ('─' x
$cutoff) . '─';
290 $borderstring_b .= "┴─" . ('─' x
$cutoff) . '─';
292 $formatstring .= "| %$alignstr${cutoff}s ";
293 $borderstring_m .= "+-" . ('-' x
$cutoff) . '-';
297 # skip alignment and cutoff on last column
298 $formatstring .= ($i == ($column_count - 1)) ?
"%s" : "%$alignstr${cutoff}s ";
302 $borderstring_t = $borderstring_m if !length($borderstring_t);
303 $borderstring_b = $borderstring_m if !length($borderstring_b);
309 print encode
($encoding, substr($text, 0, $columns) . "\n");
311 print encode
($encoding, $text) . "\n";
315 $writeln->($borderstring_t) if $border;
318 my $text = sprintf $formatstring, map { $colopts->{$_}->{title
} } @$props_to_print;
322 for (my $i = 0; $i < scalar(@$tabledata); $i++) {
323 my $coldata = $tabledata->[$i];
325 $writeln->($borderstring_m) if $border && ($i != 0 || $header);
327 for (my $i = 0; $i < $coldata->{height
}; $i++) {
329 my $text = sprintf $formatstring, map {
330 substr($coldata->{rowdata
}->{$_}->{lines
}->[$i] // '', 0, $colopts->{$_}->{cutoff
});
337 $writeln->($borderstring_b) if $border;
340 sub extract_properties_to_print
{
346 foreach my $key (keys %$propdef) {
347 my $prop = $propdef->{$key};
348 if ($prop->{optional
}) {
349 push @$optional, $key;
351 push @$required, $key;
355 return [ sort(@$required), sort(@$optional) ];
358 # prints the result of an API GET call returning an array as a table.
359 # takes formatting information from the results property of the call
360 # if $props_to_print is provided, prints only those columns. otherwise
361 # takes all fields of the results property, with a fallback
362 # to all fields occuring in items of $data.
364 my ($data, $result_schema, $props_to_print, $options, $terminal_opts) = @_;
366 die "can only print object lists\n"
367 if !($result_schema->{type
} eq 'array' && $result_schema->{items
}->{type
} eq 'object');
369 my $returnprops = $result_schema->{items
}->{properties
};
371 $props_to_print = extract_properties_to_print
($returnprops)
372 if !defined($props_to_print);
374 if (!scalar(@$props_to_print)) {
376 foreach my $obj (@$data) {
377 foreach my $key (keys %$obj) {
378 $all_props->{$key} = 1;
381 $props_to_print = [ sort keys %{$all_props} ];
384 die "unable to detect list properties\n" if !scalar(@$props_to_print);
386 print_text_table
($data, $returnprops, $props_to_print, $options, $terminal_opts);
389 my $guess_type = sub {
392 return 'null' if !defined($data);
394 my $class = ref($data);
395 return 'string' if !$class;
397 if ($class eq 'HASH') {
399 } elsif ($class eq 'ARRAY') {
402 return 'string'; # better than nothing
406 sub print_api_result
{
407 my ($data, $result_schema, $props_to_print, $options, $terminal_opts) = @_;
409 return if $options->{quiet
};
411 $terminal_opts //= query_terminal_options
({});
413 my $format = $options->{'output-format'} // 'text';
415 if ($result_schema) {
416 return if $result_schema->{type
} eq 'null';
418 my $type = $guess_type->($data);
419 $result_schema = { type
=> $type };
420 $result_schema->{items
} = { type
=> $guess_type->($data->[0]) } if $type eq 'array';
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);
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) };
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);
452 foreach my $value (@$data) {
453 push @$kvstore, { value
=> $value };
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);
459 print encode
($encoding, "$data\n");
462 die "internal error: unknown output format"; # should not happen
466 sub print_api_result_plain
{
467 my ($data, $result_schema, $props_to_print, $options) = @_;
469 # avoid borders and header, ignore terminal width
470 $options = $options ?
{ %$options } : {}; # copy
472 $options->{noheader
} //= 1;
473 $options->{noborder
} //= 1;
475 print_api_result
($data, $result_schema, $props_to_print, $options, {});