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 my $human_readable = $options->{'human-readable'} // 1;
107 if ($human_readable && defined($propdef)) {
108 if (my $type = $propdef->{type
}) {
109 if ($type eq 'boolean') {
110 return $data ?
1 : 0;
113 if (!defined($data) && defined($propdef->{default})) {
114 return "($propdef->{default})";
116 if (defined(my $renderer = $propdef->{renderer
})) {
117 my $code = PVE
::JSONSchema
::get_renderer
($renderer);
118 die "internal error: unknown renderer '$renderer'" if !$code;
119 return $code->($data, $options);
123 if (my $class = ref($data)) {
124 return to_json
($data, { canonical
=> 1 });
130 # prints a formatted table with a title row.
131 # $data - the data to print (array of objects)
132 # $returnprops -json schema property description
133 # $props_to_print - ordered list of properties to print
135 # - sort_key: can be used to sort after a specific column, if it isn't set we sort
136 # after the leftmost column (with no undef value in $data) this can be
137 # turned off by passing 0 as sort_key
138 # - noborder: print without asciiart border
139 # - noheader: print without table header
140 # - columns: limit output width (if > 0)
141 # - utf8: use utf8 characters for table delimiters
143 sub print_text_table
{
144 my ($data, $returnprops, $props_to_print, $options) = @_;
146 my $sort_key = $options->{sort_key
};
147 my $border = !$options->{noborder
};
148 my $header = !$options->{noheader
};
149 my $columns = $options->{columns
};
150 my $utf8 = $options->{utf8
};
151 my $encoding = $options->{encoding
} // 'UTF-8';
153 $sort_key //= $props_to_print->[0];
155 if (defined($sort_key) && $sort_key ne 0) {
156 my $type = $returnprops->{$sort_key}->{type
} // 'string';
157 if ($type eq 'integer' || $type eq 'number') {
158 @$data = sort { $a->{$sort_key} <=> $b->{$sort_key} } @$data;
160 @$data = sort { $a->{$sort_key} cmp $b->{$sort_key} } @$data;
166 my $borderstring_m = '';
167 my $borderstring_b = '';
168 my $borderstring_t = '';
169 my $formatstring = '';
171 my $column_count = scalar(@$props_to_print);
175 foreach my $entry (@$data) {
180 for (my $i = 0; $i < $column_count; $i++) {
181 my $prop = $props_to_print->[$i];
182 my $propinfo = $returnprops->{$prop} // {};
184 my $text = data_to_text
($entry->{$prop}, $propinfo, $options);
185 my $lines = [ split(/\n/, $text) ];
186 my $linecount = scalar(@$lines);
187 $height = $linecount if $linecount > $height;
190 foreach my $line (@$lines) {
191 my $len = length($line);
192 $width = $len if $len > $width;
195 $rowdata->{$prop} = {
207 for (my $i = 0; $i < $column_count; $i++) {
208 my $prop = $props_to_print->[$i];
209 my $propinfo = $returnprops->{$prop} // {};
211 my $title = $propinfo->{title
} // $prop;
212 my $cutoff = $propinfo->{print_width
} // $propinfo->{maxLength
};
214 # calculate maximal print width and cutoff
215 my $titlelen = length($title);
217 my $longest = $titlelen;
218 foreach my $coldata (@$tabledata) {
219 my $rowdata = $coldata->{rowdata
}->{$prop};
220 $longest = $rowdata->{width
} if $rowdata->{width
} > $longest;
222 $cutoff = $longest if !defined($cutoff) || $cutoff > $longest;
224 $colopts->{$prop} = {
230 if ($i == 0 && ($column_count == 1)) {
232 $formatstring .= "│ %-${cutoff}s │";
233 $borderstring_t .= "┌─" . ('─' x
$cutoff) . "─┐";
234 $borderstring_m .= "├─" . ('─' x
$cutoff) . "─┤";
235 $borderstring_b .= "└─" . ('─' x
$cutoff) . "─┘";
237 $formatstring .= "| %-${cutoff}s |";
238 $borderstring_m .= "+-" . ('-' x
$cutoff) . "-+";
242 $formatstring .= "│ %-${cutoff}s ";
243 $borderstring_t .= "┌─" . ('─' x
$cutoff) . '─';
244 $borderstring_m .= "├─" . ('─' x
$cutoff) . '─';
245 $borderstring_b .= "└─" . ('─' x
$cutoff) . '─';
247 $formatstring .= "| %-${cutoff}s ";
248 $borderstring_m .= "+-" . ('-' x
$cutoff) . '-';
250 } elsif ($i == ($column_count - 1)) {
252 $formatstring .= "│ %-${cutoff}s │";
253 $borderstring_t .= "┬─" . ('─' x
$cutoff) . "─┐";
254 $borderstring_m .= "┼─" . ('─' x
$cutoff) . "─┤";
255 $borderstring_b .= "┴─" . ('─' x
$cutoff) . "─┘";
257 $formatstring .= "| %-${cutoff}s |";
258 $borderstring_m .= "+-" . ('-' x
$cutoff) . "-+";
262 $formatstring .= "│ %-${cutoff}s ";
263 $borderstring_t .= "┬─" . ('─' x
$cutoff) . '─';
264 $borderstring_m .= "┼─" . ('─' x
$cutoff) . '─';
265 $borderstring_b .= "┴─" . ('─' x
$cutoff) . '─';
267 $formatstring .= "| %-${cutoff}s ";
268 $borderstring_m .= "+-" . ('-' x
$cutoff) . '-';
272 # skip alignment and cutoff on last column
273 $formatstring .= ($i == ($column_count - 1)) ?
"%s" : "%-${cutoff}s ";
277 $borderstring_t = $borderstring_m if !length($borderstring_t);
278 $borderstring_b = $borderstring_m if !length($borderstring_b);
284 print encode
($encoding, substr($text, 0, $columns) . "\n");
286 print encode
($encoding, $text) . "\n";
290 $writeln->($borderstring_t) if $border;
293 my $text = sprintf $formatstring, map { $colopts->{$_}->{title
} } @$props_to_print;
297 for (my $i = 0; $i < scalar(@$tabledata); $i++) {
298 my $coldata = $tabledata->[$i];
300 $writeln->($borderstring_m) if $border && ($i != 0 || $header);
302 for (my $i = 0; $i < $coldata->{height
}; $i++) {
304 my $text = sprintf $formatstring, map {
305 substr($coldata->{rowdata
}->{$_}->{lines
}->[$i] // '', 0, $colopts->{$_}->{cutoff
});
312 $writeln->($borderstring_b) if $border;
315 sub extract_properties_to_print
{
321 foreach my $key (keys %$propdef) {
322 my $prop = $propdef->{$key};
323 if ($prop->{optional
}) {
324 push @$optional, $key;
326 push @$required, $key;
330 return [ sort(@$required), sort(@$optional) ];
333 # prints the result of an API GET call returning an array as a table.
334 # takes formatting information from the results property of the call
335 # if $props_to_print is provided, prints only those columns. otherwise
336 # takes all fields of the results property, with a fallback
337 # to all fields occuring in items of $data.
339 my ($data, $result_schema, $props_to_print, $options) = @_;
341 die "can only print object lists\n"
342 if !($result_schema->{type
} eq 'array' && $result_schema->{items
}->{type
} eq 'object');
344 my $returnprops = $result_schema->{items
}->{properties
};
346 $props_to_print = extract_properties_to_print
($returnprops)
347 if !defined($props_to_print);
349 if (!scalar(@$props_to_print)) {
351 foreach my $obj (@$data) {
352 foreach my $key (keys %$obj) {
353 $all_props->{$key} = 1;
356 $props_to_print = [ sort keys %{$all_props} ];
359 die "unable to detect list properties\n" if !scalar(@$props_to_print);
361 print_text_table
($data, $returnprops, $props_to_print, $options);
364 sub print_api_result
{
365 my ($data, $result_schema, $props_to_print, $options) = @_;
367 return if $options->{quiet
};
369 if (!defined($options)) {
370 $options = query_terminal_options
({});
372 $options = { %$options }; # copy
375 my $format = $options->{'output-format'} // 'text';
377 return if $result_schema->{type
} eq 'null';
379 if ($format eq 'json') {
380 # Note: we always use utf8 encoding for json format
381 print to_json
($data, {utf8
=> 1, allow_nonref
=> 1, canonical
=> 1 }) . "\n";
382 } elsif ($format eq 'json-pretty') {
383 # Note: we always use utf8 encoding for json format
384 print to_json
($data, {utf8
=> 1, allow_nonref
=> 1, canonical
=> 1, pretty
=> 1 });
385 } elsif ($format eq 'text') {
386 my $encoding = $options->{encoding
} // 'UTF-8';
387 my $type = $result_schema->{type
};
388 if ($type eq 'object') {
389 $props_to_print = extract_properties_to_print
($result_schema->{properties
})
390 if !defined($props_to_print);
391 $props_to_print = [ sort keys %$data ] if !scalar(@$props_to_print);
393 foreach my $key (@$props_to_print) {
394 next if !defined($data->{$key});
395 push @$kvstore, { key
=> $key, value
=> data_to_text
($data->{$key}, $result_schema->{properties
}->{$key}, $options) };
397 my $schema = { type
=> 'array', items
=> { type
=> 'object' }};
398 print_api_list
($kvstore, $schema, ['key', 'value'], $options);
399 } elsif ($type eq 'array') {
400 return if !scalar(@$data);
401 my $item_type = $result_schema->{items
}->{type
};
402 if ($item_type eq 'object') {
403 print_api_list
($data, $result_schema, $props_to_print, $options);
406 foreach my $value (@$data) {
407 push @$kvstore, { value
=> $value };
409 my $schema = { type
=> 'array', items
=> { type
=> 'object', properties
=> { value
=> $result_schema->{items
} }}};
410 $options->{noheader
} = 1;
411 print_api_list
($kvstore, $schema, ['value'], $options);
414 print encode
($encoding, "$data\n");
417 die "internal error: unknown output format"; # should not happen