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 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 if (!defined($sort_key) || $sort_key eq 0) {
154 $sort_key = $props_to_print->[0];
157 if (defined($sort_key)) {
158 my $type = $returnprops->{$sort_key}->{type
} // 'string';
159 if ($type eq 'integer' || $type eq 'number') {
160 @$data = sort { $a->{$sort_key} <=> $b->{$sort_key} } @$data;
162 @$data = sort { $a->{$sort_key} cmp $b->{$sort_key} } @$data;
168 my $borderstring_m = '';
169 my $borderstring_b = '';
170 my $borderstring_t = '';
171 my $formatstring = '';
173 my $column_count = scalar(@$props_to_print);
177 foreach my $entry (@$data) {
182 for (my $i = 0; $i < $column_count; $i++) {
183 my $prop = $props_to_print->[$i];
184 my $propinfo = $returnprops->{$prop} // {};
186 my $text = data_to_text
($entry->{$prop}, $propinfo, $options);
187 my $lines = [ split(/\n/, $text) ];
188 my $linecount = scalar(@$lines);
189 $height = $linecount if $linecount > $height;
192 foreach my $line (@$lines) {
193 my $len = length($line);
194 $width = $len if $len > $width;
197 $rowdata->{$prop} = {
209 for (my $i = 0; $i < $column_count; $i++) {
210 my $prop = $props_to_print->[$i];
211 my $propinfo = $returnprops->{$prop} // {};
213 my $title = $propinfo->{title
} // $prop;
214 my $cutoff = $propinfo->{print_width
} // $propinfo->{maxLength
};
216 # calculate maximal print width and cutoff
217 my $titlelen = length($title);
219 my $longest = $titlelen;
220 foreach my $coldata (@$tabledata) {
221 my $rowdata = $coldata->{rowdata
}->{$prop};
222 $longest = $rowdata->{width
} if $rowdata->{width
} > $longest;
224 $cutoff = $longest if !defined($cutoff) || $cutoff > $longest;
226 $colopts->{$prop} = {
232 if ($i == 0 && ($column_count == 1)) {
234 $formatstring .= "│ %-${cutoff}s │";
235 $borderstring_t .= "┌─" . ('─' x
$cutoff) . "─┐";
236 $borderstring_m .= "├─" . ('─' x
$cutoff) . "─┤";
237 $borderstring_b .= "└─" . ('─' x
$cutoff) . "─┘";
239 $formatstring .= "| %-${cutoff}s |";
240 $borderstring_m .= "+-" . ('-' x
$cutoff) . "-+";
244 $formatstring .= "│ %-${cutoff}s ";
245 $borderstring_t .= "┌─" . ('─' x
$cutoff) . '─';
246 $borderstring_m .= "├─" . ('─' x
$cutoff) . '─';
247 $borderstring_b .= "└─" . ('─' x
$cutoff) . '─';
249 $formatstring .= "| %-${cutoff}s ";
250 $borderstring_m .= "+-" . ('-' x
$cutoff) . '-';
252 } elsif ($i == ($column_count - 1)) {
254 $formatstring .= "│ %-${cutoff}s │";
255 $borderstring_t .= "┬─" . ('─' x
$cutoff) . "─┐";
256 $borderstring_m .= "┼─" . ('─' x
$cutoff) . "─┤";
257 $borderstring_b .= "┴─" . ('─' x
$cutoff) . "─┘";
259 $formatstring .= "| %-${cutoff}s |";
260 $borderstring_m .= "+-" . ('-' x
$cutoff) . "-+";
264 $formatstring .= "│ %-${cutoff}s ";
265 $borderstring_t .= "┬─" . ('─' x
$cutoff) . '─';
266 $borderstring_m .= "┼─" . ('─' x
$cutoff) . '─';
267 $borderstring_b .= "┴─" . ('─' x
$cutoff) . '─';
269 $formatstring .= "| %-${cutoff}s ";
270 $borderstring_m .= "+-" . ('-' x
$cutoff) . '-';
274 # skip alignment and cutoff on last column
275 $formatstring .= ($i == ($column_count - 1)) ?
"%s" : "%-${cutoff}s ";
279 $borderstring_t = $borderstring_m if !length($borderstring_t);
280 $borderstring_b = $borderstring_m if !length($borderstring_b);
286 print encode
($encoding, substr($text, 0, $columns) . "\n");
288 print encode
($encoding, $text) . "\n";
292 $writeln->($borderstring_t) if $border;
295 my $text = sprintf $formatstring, map { $colopts->{$_}->{title
} } @$props_to_print;
299 for (my $i = 0; $i < scalar(@$tabledata); $i++) {
300 my $coldata = $tabledata->[$i];
302 $writeln->($borderstring_m) if $border && ($i != 0 || $header);
304 for (my $i = 0; $i < $coldata->{height
}; $i++) {
306 my $text = sprintf $formatstring, map {
307 substr($coldata->{rowdata
}->{$_}->{lines
}->[$i] // '', 0, $colopts->{$_}->{cutoff
});
314 $writeln->($borderstring_b) if $border;
317 sub extract_properties_to_print
{
323 foreach my $key (keys %$propdef) {
324 my $prop = $propdef->{$key};
325 if ($prop->{optional
}) {
326 push @$optional, $key;
328 push @$required, $key;
332 return [ sort(@$required), sort(@$optional) ];
335 # prints the result of an API GET call returning an array as a table.
336 # takes formatting information from the results property of the call
337 # if $props_to_print is provided, prints only those columns. otherwise
338 # takes all fields of the results property, with a fallback
339 # to all fields occuring in items of $data.
341 my ($data, $result_schema, $props_to_print, $options) = @_;
343 die "can only print object lists\n"
344 if !($result_schema->{type
} eq 'array' && $result_schema->{items
}->{type
} eq 'object');
346 my $returnprops = $result_schema->{items
}->{properties
};
348 $props_to_print = extract_properties_to_print
($returnprops)
349 if !defined($props_to_print);
351 if (!scalar(@$props_to_print)) {
353 foreach my $obj (@$data) {
354 foreach my $key (keys %$obj) {
355 $all_props->{$key} = 1;
358 $props_to_print = [ sort keys %{$all_props} ];
361 die "unable to detect list properties\n" if !scalar(@$props_to_print);
363 print_text_table
($data, $returnprops, $props_to_print, $options);
366 sub print_api_result
{
367 my ($data, $result_schema, $props_to_print, $options) = @_;
369 return if $options->{quiet
};
371 if (!defined($options)) {
372 $options = query_terminal_options
({});
374 $options = { %$options }; # copy
377 my $format = $options->{'output-format'} // 'text';
379 return if $result_schema->{type
} eq 'null';
381 if ($format eq 'json') {
382 # Note: we always use utf8 encoding for json format
383 print to_json
($data, {utf8
=> 1, allow_nonref
=> 1, canonical
=> 1 }) . "\n";
384 } elsif ($format eq 'json-pretty') {
385 # Note: we always use utf8 encoding for json format
386 print to_json
($data, {utf8
=> 1, allow_nonref
=> 1, canonical
=> 1, pretty
=> 1 });
387 } elsif ($format eq 'text') {
388 my $encoding = $options->{encoding
} // 'UTF-8';
389 my $type = $result_schema->{type
};
390 if ($type eq 'object') {
391 $props_to_print = extract_properties_to_print
($result_schema->{properties
})
392 if !defined($props_to_print);
393 $props_to_print = [ sort keys %$data ] if !scalar(@$props_to_print);
395 foreach my $key (@$props_to_print) {
396 next if !defined($data->{$key});
397 push @$kvstore, { key
=> $key, value
=> data_to_text
($data->{$key}, $result_schema->{properties
}->{$key}, $options) };
399 my $schema = { type
=> 'array', items
=> { type
=> 'object' }};
400 print_api_list
($kvstore, $schema, ['key', 'value'], $options);
401 } elsif ($type eq 'array') {
402 return if !scalar(@$data);
403 my $item_type = $result_schema->{items
}->{type
};
404 if ($item_type eq 'object') {
405 print_api_list
($data, $result_schema, $props_to_print, $options);
408 foreach my $value (@$data) {
409 push @$kvstore, { value
=> $value };
411 my $schema = { type
=> 'array', items
=> { type
=> 'object', properties
=> { value
=> $result_schema->{items
} }}};
412 $options->{noheader
} = 1;
413 print_api_list
($kvstore, $schema, ['value'], $options);
416 print encode
($encoding, "$data\n");
419 die "internal error: unknown output format"; # should not happen