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
);
24 my ($duration_in_seconds) = @_;
27 my $rest = $duration_in_seconds;
30 my ($unit, $unitlength) = @_;
32 if ((my $v = int($rest/$unitlength)) > 0) {
33 $text .= " " if length($text);
34 $text .= "${v}${unit}";
35 $rest -= $v * $unitlength;
39 $step->('w', 7*24*3600);
40 $step->('d', 24*3600);
48 PVE
::JSONSchema
::register_renderer
('duration', \
&render_duration
);
50 sub render_fraction_as_percentage
{
53 return sprintf("%.2f%%", $fraction*100);
56 PVE
::JSONSchema
::register_renderer
(
57 'fraction_as_percentage', \
&render_fraction_as_percentage
);
62 my @units = qw(B KiB MiB GiB TiB PiB);
66 $max_unit = int(log($value)/log(1024));
67 $value /= 1024**($max_unit);
70 return sprintf "%.2f $units[$max_unit]", $value;
73 PVE
::JSONSchema
::register_renderer
('bytes', \
&render_bytes
);
75 sub query_terminal_options
{
81 ($options->{columns
}) = PVE
::PTY
::tcgetsize
(*STDOUT
);
84 $options->{encoding
} = I18N
::Langinfo
::langinfo
(I18N
::Langinfo
::CODESET
());
86 $options->{utf8
} = 1 if $options->{encoding
} eq 'UTF-8';
92 my ($data, $propdef, $options) = @_;
94 return '' if !defined($data);
96 if (defined($propdef)) {
97 if (my $type = $propdef->{type
}) {
98 if ($type eq 'boolean') {
102 if (!defined($data) && defined($propdef->{default})) {
103 return "($propdef->{default})";
105 if (defined(my $renderer = $propdef->{renderer
})) {
106 my $code = PVE
::JSONSchema
::get_renderer
($renderer);
107 die "internal error: unknown renderer '$renderer'" if !$code;
108 return $code->($data, $options);
112 if (my $class = ref($data)) {
113 return to_json
($data, { canonical
=> 1 });
119 # prints a formatted table with a title row.
120 # $data - the data to print (array of objects)
121 # $returnprops -json schema property description
122 # $props_to_print - ordered list of properties to print
124 # - sort_key: can be used to sort after a column, if it isn't set we sort
125 # after the leftmost column (with no undef value in $data) this can be
126 # turned off by passing 0 as sort_key
127 # - border: print with/without table header and asciiart border
128 # - columns: limit output width (if > 0)
129 # - utf8: use utf8 characters for table delimiters
131 sub print_text_table
{
132 my ($data, $returnprops, $props_to_print, $options) = @_;
134 my $sort_key = $options->{sort_key
};
135 my $border = $options->{border
};
136 my $columns = $options->{columns
};
137 my $utf8 = $options->{utf8
};
138 my $encoding = $options->{encoding
} // 'UTF-8';
140 if (!defined($sort_key) || $sort_key eq 0) {
141 $sort_key = $props_to_print->[0];
144 if (defined($sort_key)) {
145 my $type = $returnprops->{$sort_key}->{type
} // 'string';
146 if ($type eq 'integer' || $type eq 'number') {
147 @$data = sort { $a->{$sort_key} <=> $b->{$sort_key} } @$data;
149 @$data = sort { $a->{$sort_key} cmp $b->{$sort_key} } @$data;
155 my $borderstring_m = '';
156 my $borderstring_b = '';
157 my $borderstring_t = '';
158 my $formatstring = '';
160 my $column_count = scalar(@$props_to_print);
164 foreach my $entry (@$data) {
169 for (my $i = 0; $i < $column_count; $i++) {
170 my $prop = $props_to_print->[$i];
171 my $propinfo = $returnprops->{$prop} // {};
173 my $text = data_to_text
($entry->{$prop}, $propinfo, $options);
174 my $lines = [ split(/\n/, $text) ];
175 my $linecount = scalar(@$lines);
176 $height = $linecount if $linecount > $height;
179 foreach my $line (@$lines) {
180 my $len = length($line);
181 $width = $len if $len > $width;
184 $rowdata->{$prop} = {
196 for (my $i = 0; $i < $column_count; $i++) {
197 my $prop = $props_to_print->[$i];
198 my $propinfo = $returnprops->{$prop} // {};
200 my $title = $propinfo->{title
} // $prop;
201 my $cutoff = $propinfo->{print_width
} // $propinfo->{maxLength
};
203 # calculate maximal print width and cutoff
204 my $titlelen = length($title);
206 my $longest = $titlelen;
207 foreach my $coldata (@$tabledata) {
208 my $rowdata = $coldata->{rowdata
}->{$prop};
209 $longest = $rowdata->{width
} if $rowdata->{width
} > $longest;
211 $cutoff = $longest if !defined($cutoff) || $cutoff > $longest;
213 $colopts->{$prop} = {
219 if ($i == 0 && ($column_count == 1)) {
221 $formatstring .= "│ %-${cutoff}s │";
222 $borderstring_t .= "┌─" . ('─' x
$cutoff) . "─┐";
223 $borderstring_m .= "├─" . ('─' x
$cutoff) . "─┤";
224 $borderstring_b .= "└─" . ('─' x
$cutoff) . "─┘";
226 $formatstring .= "| %-${cutoff}s |";
227 $borderstring_m .= "+-" . ('-' x
$cutoff) . "-+";
231 $formatstring .= "│ %-${cutoff}s ";
232 $borderstring_t .= "┌─" . ('─' x
$cutoff) . '─';
233 $borderstring_m .= "├─" . ('─' x
$cutoff) . '─';
234 $borderstring_b .= "└─" . ('─' x
$cutoff) . '─';
236 $formatstring .= "| %-${cutoff}s ";
237 $borderstring_m .= "+-" . ('-' x
$cutoff) . '-';
239 } elsif ($i == ($column_count - 1)) {
241 $formatstring .= "│ %-${cutoff}s │";
242 $borderstring_t .= "┬─" . ('─' x
$cutoff) . "─┐";
243 $borderstring_m .= "┼─" . ('─' x
$cutoff) . "─┤";
244 $borderstring_b .= "┴─" . ('─' x
$cutoff) . "─┘";
246 $formatstring .= "| %-${cutoff}s |";
247 $borderstring_m .= "+-" . ('-' x
$cutoff) . "-+";
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 # skip alignment and cutoff on last column
262 $formatstring .= ($i == ($column_count - 1)) ?
"%s" : "%-${cutoff}s ";
266 $borderstring_t = $borderstring_m if !length($borderstring_t);
267 $borderstring_b = $borderstring_m if !length($borderstring_b);
273 print encode
($encoding, substr($text, 0, $columns) . "\n");
275 print encode
($encoding, $text) . "\n";
279 $writeln->($borderstring_t) if $border;
280 my $text = sprintf $formatstring, map { $colopts->{$_}->{title
} } @$props_to_print;
283 foreach my $coldata (@$tabledata) {
284 $writeln->($borderstring_m) if $border;
286 for (my $i = 0; $i < $coldata->{height
}; $i++) {
288 $text = sprintf $formatstring, map {
289 substr($coldata->{rowdata
}->{$_}->{lines
}->[$i] // '', 0, $colopts->{$_}->{cutoff
});
296 $writeln->($borderstring_b) if $border;
299 sub extract_properties_to_print
{
305 foreach my $key (keys %$propdef) {
306 my $prop = $propdef->{$key};
307 if ($prop->{optional
}) {
308 push @$optional, $key;
310 push @$required, $key;
314 return [ sort(@$required), sort(@$optional) ];
317 # prints the result of an API GET call returning an array as a table.
318 # takes formatting information from the results property of the call
319 # if $props_to_print is provided, prints only those columns. otherwise
320 # takes all fields of the results property, with a fallback
321 # to all fields occuring in items of $data.
323 my ($data, $result_schema, $props_to_print, $options) = @_;
325 die "can only print object lists\n"
326 if !($result_schema->{type
} eq 'array' && $result_schema->{items
}->{type
} eq 'object');
328 my $returnprops = $result_schema->{items
}->{properties
};
330 $props_to_print = extract_properties_to_print
($returnprops)
331 if !defined($props_to_print);
333 if (!scalar(@$props_to_print)) {
335 foreach my $obj (@$data) {
336 foreach my $key (keys %$obj) {
337 $all_props->{$key} = 1;
340 $props_to_print = [ sort keys %{$all_props} ];
343 die "unable to detect list properties\n" if !scalar(@$props_to_print);
345 print_text_table
($data, $returnprops, $props_to_print, $options);
348 sub print_api_result
{
349 my ($format, $data, $result_schema, $props_to_print, $options) = @_;
351 if (!defined($options)) {
352 $options = query_terminal_options
({});
354 $options = { %$options }; # copy
357 return if $result_schema->{type
} eq 'null';
359 if ($format eq 'json') {
360 # Note: we always use utf8 encoding for json format
361 print to_json
($data, {utf8
=> 1, allow_nonref
=> 1, canonical
=> 1, pretty
=> 1 });
362 } elsif ($format eq 'text' || $format eq 'plain') {
363 my $encoding = $options->{encoding
} // 'UTF-8';
364 my $type = $result_schema->{type
};
365 if ($type eq 'object') {
366 $props_to_print = extract_properties_to_print
($result_schema->{properties
})
367 if !defined($props_to_print);
368 $props_to_print = [ sort keys %$data ] if !scalar(@$props_to_print);
370 foreach my $key (@$props_to_print) {
371 push @$kvstore, { key
=> $key, value
=> data_to_text
($data->{$key}, $result_schema->{properties
}->{$key}, $options) };
373 my $schema = { type
=> 'array', items
=> { type
=> 'object' }};
374 $options->{border
} = $format eq 'text';
375 print_api_list
($kvstore, $schema, ['key', 'value'], $options);
376 } elsif ($type eq 'array') {
377 return if !scalar(@$data);
378 my $item_type = $result_schema->{items
}->{type
};
379 if ($item_type eq 'object') {
380 $options->{border
} = $format eq 'text';
381 print_api_list
($data, $result_schema, $props_to_print, $options);
383 foreach my $entry (@$data) {
384 print encode
($encoding, data_to_text
($entry, $result_schema->{items
}, $options) . "\n");
388 print encode
($encoding, "$data\n");
391 die "internal error: unknown output format"; # should not happen