1 package PVE
::CLIFormatter
;
6 use POSIX
qw(strftime);
14 sub render_timestamp
{
17 # ISO 8601 date format
18 return strftime
("%F %H:%M:%S", localtime($epoch));
21 PVE
::JSONSchema
::register_renderer
('timestamp', \
&render_timestamp
);
23 sub render_timestamp_gmt
{
26 # ISO 8601 date format, standard Greenwich time zone
27 return strftime
("%F %H:%M:%S", gmtime($epoch));
30 PVE
::JSONSchema
::register_renderer
('timestamp_gmt', \
&render_timestamp_gmt
);
33 my ($duration_in_seconds) = @_;
36 my $rest = $duration_in_seconds;
39 my ($unit, $unitlength) = @_;
41 if ((my $v = int($rest/$unitlength)) > 0) {
42 $text .= " " if length($text);
43 $text .= "${v}${unit}";
44 $rest -= $v * $unitlength;
48 $step->('w', 7*24*3600);
49 $step->('d', 24*3600);
57 PVE
::JSONSchema
::register_renderer
('duration', \
&render_duration
);
59 sub render_fraction_as_percentage
{
62 return sprintf("%.2f%%", $fraction*100);
65 PVE
::JSONSchema
::register_renderer
(
66 'fraction_as_percentage', \
&render_fraction_as_percentage
);
71 my @units = qw(B KiB MiB GiB TiB PiB);
75 $max_unit = int(log($value)/log(1024));
76 $value /= 1024**($max_unit);
79 return sprintf "%.2f $units[$max_unit]", $value;
82 PVE
::JSONSchema
::register_renderer
('bytes', \
&render_bytes
);
84 sub query_terminal_options
{
90 ($options->{columns
}) = PVE
::PTY
::tcgetsize
(*STDOUT
);
93 $options->{encoding
} = I18N
::Langinfo
::langinfo
(I18N
::Langinfo
::CODESET
());
95 $options->{utf8
} = 1 if $options->{encoding
} eq 'UTF-8';
101 my ($data, $propdef, $options) = @_;
103 return '' if !defined($data);
105 if (defined($propdef)) {
106 if (my $type = $propdef->{type
}) {
107 if ($type eq 'boolean') {
108 return $data ?
1 : 0;
111 if (!defined($data) && defined($propdef->{default})) {
112 return "($propdef->{default})";
114 if (defined(my $renderer = $propdef->{renderer
})) {
115 my $code = PVE
::JSONSchema
::get_renderer
($renderer);
116 die "internal error: unknown renderer '$renderer'" if !$code;
117 return $code->($data, $options);
121 if (my $class = ref($data)) {
122 return to_json
($data, { canonical
=> 1 });
128 # prints a formatted table with a title row.
129 # $data - the data to print (array of objects)
130 # $returnprops -json schema property description
131 # $props_to_print - ordered list of properties to print
133 # - sort_key: can be used to sort after a column, if it isn't set we sort
134 # after the leftmost column (with no undef value in $data) this can be
135 # turned off by passing 0 as sort_key
136 # - border: print with/without table header and asciiart border
137 # - columns: limit output width (if > 0)
138 # - utf8: use utf8 characters for table delimiters
140 sub print_text_table
{
141 my ($data, $returnprops, $props_to_print, $options) = @_;
143 my $sort_key = $options->{sort_key
};
144 my $border = $options->{border
};
145 my $columns = $options->{columns
};
146 my $utf8 = $options->{utf8
};
147 my $encoding = $options->{encoding
} // 'UTF-8';
149 if (!defined($sort_key) || $sort_key eq 0) {
150 $sort_key = $props_to_print->[0];
153 if (defined($sort_key)) {
154 my $type = $returnprops->{$sort_key}->{type
} // 'string';
155 if ($type eq 'integer' || $type eq 'number') {
156 @$data = sort { $a->{$sort_key} <=> $b->{$sort_key} } @$data;
158 @$data = sort { $a->{$sort_key} cmp $b->{$sort_key} } @$data;
164 my $borderstring_m = '';
165 my $borderstring_b = '';
166 my $borderstring_t = '';
167 my $formatstring = '';
169 my $column_count = scalar(@$props_to_print);
173 foreach my $entry (@$data) {
178 for (my $i = 0; $i < $column_count; $i++) {
179 my $prop = $props_to_print->[$i];
180 my $propinfo = $returnprops->{$prop} // {};
182 my $text = data_to_text
($entry->{$prop}, $propinfo, $options);
183 my $lines = [ split(/\n/, $text) ];
184 my $linecount = scalar(@$lines);
185 $height = $linecount if $linecount > $height;
188 foreach my $line (@$lines) {
189 my $len = length($line);
190 $width = $len if $len > $width;
193 $rowdata->{$prop} = {
205 for (my $i = 0; $i < $column_count; $i++) {
206 my $prop = $props_to_print->[$i];
207 my $propinfo = $returnprops->{$prop} // {};
209 my $title = $propinfo->{title
} // $prop;
210 my $cutoff = $propinfo->{print_width
} // $propinfo->{maxLength
};
212 # calculate maximal print width and cutoff
213 my $titlelen = length($title);
215 my $longest = $titlelen;
216 foreach my $coldata (@$tabledata) {
217 my $rowdata = $coldata->{rowdata
}->{$prop};
218 $longest = $rowdata->{width
} if $rowdata->{width
} > $longest;
220 $cutoff = $longest if !defined($cutoff) || $cutoff > $longest;
222 $colopts->{$prop} = {
228 if ($i == 0 && ($column_count == 1)) {
230 $formatstring .= "│ %-${cutoff}s │";
231 $borderstring_t .= "┌─" . ('─' x
$cutoff) . "─┐";
232 $borderstring_m .= "├─" . ('─' x
$cutoff) . "─┤";
233 $borderstring_b .= "└─" . ('─' x
$cutoff) . "─┘";
235 $formatstring .= "| %-${cutoff}s |";
236 $borderstring_m .= "+-" . ('-' x
$cutoff) . "-+";
240 $formatstring .= "│ %-${cutoff}s ";
241 $borderstring_t .= "┌─" . ('─' x
$cutoff) . '─';
242 $borderstring_m .= "├─" . ('─' x
$cutoff) . '─';
243 $borderstring_b .= "└─" . ('─' x
$cutoff) . '─';
245 $formatstring .= "| %-${cutoff}s ";
246 $borderstring_m .= "+-" . ('-' x
$cutoff) . '-';
248 } elsif ($i == ($column_count - 1)) {
250 $formatstring .= "│ %-${cutoff}s │";
251 $borderstring_t .= "┬─" . ('─' x
$cutoff) . "─┐";
252 $borderstring_m .= "┼─" . ('─' x
$cutoff) . "─┤";
253 $borderstring_b .= "┴─" . ('─' x
$cutoff) . "─┘";
255 $formatstring .= "| %-${cutoff}s |";
256 $borderstring_m .= "+-" . ('-' x
$cutoff) . "-+";
260 $formatstring .= "│ %-${cutoff}s ";
261 $borderstring_t .= "┬─" . ('─' x
$cutoff) . '─';
262 $borderstring_m .= "┼─" . ('─' x
$cutoff) . '─';
263 $borderstring_b .= "┴─" . ('─' x
$cutoff) . '─';
265 $formatstring .= "| %-${cutoff}s ";
266 $borderstring_m .= "+-" . ('-' x
$cutoff) . '-';
270 # skip alignment and cutoff on last column
271 $formatstring .= ($i == ($column_count - 1)) ?
"%s" : "%-${cutoff}s ";
275 $borderstring_t = $borderstring_m if !length($borderstring_t);
276 $borderstring_b = $borderstring_m if !length($borderstring_b);
282 print encode
($encoding, substr($text, 0, $columns) . "\n");
284 print encode
($encoding, $text) . "\n";
288 $writeln->($borderstring_t) if $border;
289 my $text = sprintf $formatstring, map { $colopts->{$_}->{title
} } @$props_to_print;
292 foreach my $coldata (@$tabledata) {
293 $writeln->($borderstring_m) if $border;
295 for (my $i = 0; $i < $coldata->{height
}; $i++) {
297 $text = sprintf $formatstring, map {
298 substr($coldata->{rowdata
}->{$_}->{lines
}->[$i] // '', 0, $colopts->{$_}->{cutoff
});
305 $writeln->($borderstring_b) if $border;
308 sub extract_properties_to_print
{
314 foreach my $key (keys %$propdef) {
315 my $prop = $propdef->{$key};
316 if ($prop->{optional
}) {
317 push @$optional, $key;
319 push @$required, $key;
323 return [ sort(@$required), sort(@$optional) ];
326 # prints the result of an API GET call returning an array as a table.
327 # takes formatting information from the results property of the call
328 # if $props_to_print is provided, prints only those columns. otherwise
329 # takes all fields of the results property, with a fallback
330 # to all fields occuring in items of $data.
332 my ($data, $result_schema, $props_to_print, $options) = @_;
334 die "can only print object lists\n"
335 if !($result_schema->{type
} eq 'array' && $result_schema->{items
}->{type
} eq 'object');
337 my $returnprops = $result_schema->{items
}->{properties
};
339 $props_to_print = extract_properties_to_print
($returnprops)
340 if !defined($props_to_print);
342 if (!scalar(@$props_to_print)) {
344 foreach my $obj (@$data) {
345 foreach my $key (keys %$obj) {
346 $all_props->{$key} = 1;
349 $props_to_print = [ sort keys %{$all_props} ];
352 die "unable to detect list properties\n" if !scalar(@$props_to_print);
354 print_text_table
($data, $returnprops, $props_to_print, $options);
357 sub print_api_result
{
358 my ($format, $data, $result_schema, $props_to_print, $options) = @_;
360 if (!defined($options)) {
361 $options = query_terminal_options
({});
363 $options = { %$options }; # copy
366 return if $result_schema->{type
} eq 'null';
368 if ($format eq 'json') {
369 # Note: we always use utf8 encoding for json format
370 print to_json
($data, {utf8
=> 1, allow_nonref
=> 1, canonical
=> 1, pretty
=> 1 });
371 } elsif ($format eq 'text' || $format eq 'plain') {
372 my $encoding = $options->{encoding
} // 'UTF-8';
373 my $type = $result_schema->{type
};
374 if ($type eq 'object') {
375 $props_to_print = extract_properties_to_print
($result_schema->{properties
})
376 if !defined($props_to_print);
377 $props_to_print = [ sort keys %$data ] if !scalar(@$props_to_print);
379 foreach my $key (@$props_to_print) {
380 push @$kvstore, { key
=> $key, value
=> data_to_text
($data->{$key}, $result_schema->{properties
}->{$key}, $options) };
382 my $schema = { type
=> 'array', items
=> { type
=> 'object' }};
383 $options->{border
} = $format eq 'text';
384 print_api_list
($kvstore, $schema, ['key', 'value'], $options);
385 } elsif ($type eq 'array') {
386 return if !scalar(@$data);
387 my $item_type = $result_schema->{items
}->{type
};
388 if ($item_type eq 'object') {
389 $options->{border
} = $format eq 'text';
390 print_api_list
($data, $result_schema, $props_to_print, $options);
392 foreach my $entry (@$data) {
393 print encode
($encoding, data_to_text
($entry, $result_schema->{items
}, $options) . "\n");
397 print encode
($encoding, "$data\n");
400 die "internal error: unknown output format"; # should not happen