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 my @units = qw(B KiB MiB GiB TiB PiB);
76 $max_unit = int(log($value)/log(1024));
77 $value /= 1024**($max_unit);
80 return sprintf "%.2f $units[$max_unit]", $value;
83 PVE
::JSONSchema
::register_renderer
('bytes', \
&render_bytes
);
88 my $data = CPAN
::Meta
::YAML
::Dump
($value);
89 $data =~ s/^---[\n\s]//; # remove yaml marker
94 PVE
::JSONSchema
::register_renderer
('yaml', \
&render_yaml
);
96 sub query_terminal_options
{
102 ($options->{columns
}) = PVE
::PTY
::tcgetsize
(*STDOUT
);
105 $options->{encoding
} = I18N
::Langinfo
::langinfo
(I18N
::Langinfo
::CODESET
());
107 $options->{utf8
} = 1 if $options->{encoding
} eq 'UTF-8';
113 my ($data, $propdef, $options, $terminal_opts) = @_;
115 return '' if !defined($data);
117 $terminal_opts //= {};
119 my $human_readable = $options->{'human-readable'} // 1;
121 if ($human_readable && defined($propdef)) {
122 if (my $type = $propdef->{type
}) {
123 if ($type eq 'boolean') {
124 return $data ?
1 : 0;
127 if (!defined($data) && defined($propdef->{default})) {
128 return "($propdef->{default})";
130 if (defined(my $renderer = $propdef->{renderer
})) {
131 my $code = PVE
::JSONSchema
::get_renderer
($renderer);
132 die "internal error: unknown renderer '$renderer'" if !$code;
133 return $code->($data, $options, $terminal_opts);
137 if (my $class = ref($data)) {
138 return to_json
($data, { canonical
=> 1 });
144 # prints a formatted table with a title row.
145 # $data - the data to print (array of objects)
146 # $returnprops -json schema property description
147 # $props_to_print - ordered list of properties to print
149 # - sort_key: can be used to sort after a specific column, if it isn't set we sort
150 # after the leftmost column (with no undef value in $data) this can be
151 # turned off by passing 0 as sort_key
152 # - noborder: print without asciiart border
153 # - noheader: print without table header
154 # - columns: limit output width (if > 0)
155 # - utf8: use utf8 characters for table delimiters
157 sub print_text_table
{
158 my ($data, $returnprops, $props_to_print, $options, $terminal_opts) = @_;
160 $terminal_opts //= query_terminal_options
({});
162 my $sort_key = $options->{sort_key
};
163 my $border = !$options->{noborder
};
164 my $header = !$options->{noheader
};
166 my $columns = $terminal_opts->{columns
};
167 my $utf8 = $terminal_opts->{utf8
};
168 my $encoding = $terminal_opts->{encoding
} // 'UTF-8';
170 $sort_key //= $props_to_print->[0];
172 if (defined($sort_key) && $sort_key ne 0) {
173 my $type = $returnprops->{$sort_key}->{type
} // 'string';
174 if ($type eq 'integer' || $type eq 'number') {
175 @$data = sort { $a->{$sort_key} <=> $b->{$sort_key} } @$data;
177 @$data = sort { $a->{$sort_key} cmp $b->{$sort_key} } @$data;
183 my $borderstring_m = '';
184 my $borderstring_b = '';
185 my $borderstring_t = '';
186 my $formatstring = '';
188 my $column_count = scalar(@$props_to_print);
192 foreach my $entry (@$data) {
197 for (my $i = 0; $i < $column_count; $i++) {
198 my $prop = $props_to_print->[$i];
199 my $propinfo = $returnprops->{$prop} // {};
201 my $text = data_to_text
($entry->{$prop}, $propinfo, $options, $terminal_opts);
202 my $lines = [ split(/\n/, $text) ];
203 my $linecount = scalar(@$lines);
204 $height = $linecount if $linecount > $height;
207 foreach my $line (@$lines) {
208 my $len = length($line);
209 $width = $len if $len > $width;
212 $width = ($width =~ m/^(\d+)$/) ?
int($1) : 0; # untaint int
214 $rowdata->{$prop} = {
226 for (my $i = 0; $i < $column_count; $i++) {
227 my $prop = $props_to_print->[$i];
228 my $propinfo = $returnprops->{$prop} // {};
230 my $title = $propinfo->{title
} // $prop;
231 my $cutoff = $propinfo->{print_width
} // $propinfo->{maxLength
};
233 # calculate maximal print width and cutoff
234 my $titlelen = length($title);
236 my $longest = $titlelen;
237 foreach my $coldata (@$tabledata) {
238 my $rowdata = $coldata->{rowdata
}->{$prop};
239 $longest = $rowdata->{width
} if $rowdata->{width
} > $longest;
241 $cutoff = $longest if !defined($cutoff) || $cutoff > $longest;
243 $colopts->{$prop} = {
249 if ($i == 0 && ($column_count == 1)) {
251 $formatstring .= "│ %-${cutoff}s │";
252 $borderstring_t .= "┌─" . ('─' x
$cutoff) . "─┐";
253 $borderstring_m .= "├─" . ('─' x
$cutoff) . "─┤";
254 $borderstring_b .= "└─" . ('─' x
$cutoff) . "─┘";
256 $formatstring .= "| %-${cutoff}s |";
257 $borderstring_m .= "+-" . ('-' x
$cutoff) . "-+";
261 $formatstring .= "│ %-${cutoff}s ";
262 $borderstring_t .= "┌─" . ('─' x
$cutoff) . '─';
263 $borderstring_m .= "├─" . ('─' x
$cutoff) . '─';
264 $borderstring_b .= "└─" . ('─' x
$cutoff) . '─';
266 $formatstring .= "| %-${cutoff}s ";
267 $borderstring_m .= "+-" . ('-' x
$cutoff) . '-';
269 } elsif ($i == ($column_count - 1)) {
271 $formatstring .= "│ %-${cutoff}s │";
272 $borderstring_t .= "┬─" . ('─' x
$cutoff) . "─┐";
273 $borderstring_m .= "┼─" . ('─' x
$cutoff) . "─┤";
274 $borderstring_b .= "┴─" . ('─' x
$cutoff) . "─┘";
276 $formatstring .= "| %-${cutoff}s |";
277 $borderstring_m .= "+-" . ('-' x
$cutoff) . "-+";
281 $formatstring .= "│ %-${cutoff}s ";
282 $borderstring_t .= "┬─" . ('─' x
$cutoff) . '─';
283 $borderstring_m .= "┼─" . ('─' x
$cutoff) . '─';
284 $borderstring_b .= "┴─" . ('─' x
$cutoff) . '─';
286 $formatstring .= "| %-${cutoff}s ";
287 $borderstring_m .= "+-" . ('-' x
$cutoff) . '-';
291 # skip alignment and cutoff on last column
292 $formatstring .= ($i == ($column_count - 1)) ?
"%s" : "%-${cutoff}s ";
296 $borderstring_t = $borderstring_m if !length($borderstring_t);
297 $borderstring_b = $borderstring_m if !length($borderstring_b);
303 print encode
($encoding, substr($text, 0, $columns) . "\n");
305 print encode
($encoding, $text) . "\n";
309 $writeln->($borderstring_t) if $border;
312 my $text = sprintf $formatstring, map { $colopts->{$_}->{title
} } @$props_to_print;
316 for (my $i = 0; $i < scalar(@$tabledata); $i++) {
317 my $coldata = $tabledata->[$i];
319 $writeln->($borderstring_m) if $border && ($i != 0 || $header);
321 for (my $i = 0; $i < $coldata->{height
}; $i++) {
323 my $text = sprintf $formatstring, map {
324 substr($coldata->{rowdata
}->{$_}->{lines
}->[$i] // '', 0, $colopts->{$_}->{cutoff
});
331 $writeln->($borderstring_b) if $border;
334 sub extract_properties_to_print
{
340 foreach my $key (keys %$propdef) {
341 my $prop = $propdef->{$key};
342 if ($prop->{optional
}) {
343 push @$optional, $key;
345 push @$required, $key;
349 return [ sort(@$required), sort(@$optional) ];
352 # prints the result of an API GET call returning an array as a table.
353 # takes formatting information from the results property of the call
354 # if $props_to_print is provided, prints only those columns. otherwise
355 # takes all fields of the results property, with a fallback
356 # to all fields occuring in items of $data.
358 my ($data, $result_schema, $props_to_print, $options, $terminal_opts) = @_;
360 die "can only print object lists\n"
361 if !($result_schema->{type
} eq 'array' && $result_schema->{items
}->{type
} eq 'object');
363 my $returnprops = $result_schema->{items
}->{properties
};
365 $props_to_print = extract_properties_to_print
($returnprops)
366 if !defined($props_to_print);
368 if (!scalar(@$props_to_print)) {
370 foreach my $obj (@$data) {
371 foreach my $key (keys %$obj) {
372 $all_props->{$key} = 1;
375 $props_to_print = [ sort keys %{$all_props} ];
378 die "unable to detect list properties\n" if !scalar(@$props_to_print);
380 print_text_table
($data, $returnprops, $props_to_print, $options, $terminal_opts);
383 sub print_api_result
{
384 my ($data, $result_schema, $props_to_print, $options, $terminal_opts) = @_;
386 return if $options->{quiet
};
388 $terminal_opts //= query_terminal_options
({});
390 my $format = $options->{'output-format'} // 'text';
392 return if $result_schema->{type
} eq 'null';
394 if ($format eq 'yaml') {
395 print encode
('UTF-8', CPAN
::Meta
::YAML
::Dump
($data));
396 } elsif ($format eq 'json') {
397 # Note: we always use utf8 encoding for json format
398 print to_json
($data, {utf8
=> 1, allow_nonref
=> 1, canonical
=> 1 }) . "\n";
399 } elsif ($format eq 'json-pretty') {
400 # Note: we always use utf8 encoding for json format
401 print to_json
($data, {utf8
=> 1, allow_nonref
=> 1, canonical
=> 1, pretty
=> 1 });
402 } elsif ($format eq 'text') {
403 my $encoding = $options->{encoding
} // 'UTF-8';
404 my $type = $result_schema->{type
};
405 if ($type eq 'object') {
406 $props_to_print = extract_properties_to_print
($result_schema->{properties
})
407 if !defined($props_to_print);
408 $props_to_print = [ sort keys %$data ] if !scalar(@$props_to_print);
410 foreach my $key (@$props_to_print) {
411 next if !defined($data->{$key});
412 push @$kvstore, { key
=> $key, value
=> data_to_text
($data->{$key}, $result_schema->{properties
}->{$key}, $options, $terminal_opts) };
414 my $schema = { type
=> 'array', items
=> { type
=> 'object' }};
415 print_api_list
($kvstore, $schema, ['key', 'value'], $options, $terminal_opts);
416 } elsif ($type eq 'array') {
417 return if !scalar(@$data);
418 my $item_type = $result_schema->{items
}->{type
};
419 if ($item_type eq 'object') {
420 print_api_list
($data, $result_schema, $props_to_print, $options, $terminal_opts);
423 foreach my $value (@$data) {
424 push @$kvstore, { value
=> $value };
426 my $schema = { type
=> 'array', items
=> { type
=> 'object', properties
=> { value
=> $result_schema->{items
} }}};
427 print_api_list
($kvstore, $schema, ['value'], { %$options, noheader
=> 1 }, $terminal_opts);
430 print encode
($encoding, "$data\n");
433 die "internal error: unknown output format"; # should not happen