1 package PVE
::APIClient
::CLIFormatter
;
7 use PVE
::APIClient
::JSONSchema
;
8 use PVE
::APIClient
::PTY
;
14 my ($duration_in_seconds) = @_;
17 my $rest = $duration_in_seconds;
20 my ($unit, $unitlength) = @_;
22 if ((my $v = int($rest/$unitlength)) > 0) {
23 $text .= " " if length($text);
24 $text .= "${v}${unit}";
25 $rest -= $v * $unitlength;
29 $step->('w', 7*24*3600);
30 $step->('d', 24*3600);
38 PVE
::APIClient
::JSONSchema
::register_renderer
('duration', \
&render_duration
);
40 sub render_fraction_as_percentage
{
43 return sprintf("%.2f%%", $fraction*100);
46 PVE
::APIClient
::JSONSchema
::register_renderer
(
47 'fraction_as_percentage', \
&render_fraction_as_percentage
);
52 my @units = qw(B KiB MiB GiB TiB PiB);
56 $max_unit = int(log($value)/log(1024));
57 $value /= 1024**($max_unit);
60 return sprintf "%.2f $units[$max_unit]", $value;
63 PVE
::APIClient
::JSONSchema
::register_renderer
('bytes', \
&render_bytes
);
65 sub query_terminal_options
{
71 ($options->{columns
}) = PVE
::APIClient
::PTY
::tcgetsize
(*STDOUT
);
74 $options->{encoding
} = I18N
::Langinfo
::langinfo
(I18N
::Langinfo
::CODESET
());
76 $options->{utf8
} = 1 if $options->{encoding
} eq 'UTF-8';
82 my ($data, $propdef) = @_;
84 return '' if !defined($data);
86 if (defined($propdef)) {
87 if (my $type = $propdef->{type
}) {
88 if ($type eq 'boolean') {
92 if (!defined($data) && defined($propdef->{default})) {
93 return "($propdef->{default})";
95 if (defined(my $renderer = $propdef->{renderer
})) {
96 my $code = PVE
::APIClient
::JSONSchema
::get_renderer
($renderer);
97 die "internal error: unknown renderer '$renderer'" if !$code;
98 return $code->($data);
102 if (my $class = ref($data)) {
103 return to_json
($data, { canonical
=> 1 });
109 # prints a formatted table with a title row.
110 # $data - the data to print (array of objects)
111 # $returnprops -json schema property description
112 # $props_to_print - ordered list of properties to print
114 # - sort_key: can be used to sort after a column, if it isn't set we sort
115 # after the leftmost column (with no undef value in $data) this can be
116 # turned off by passing 0 as sort_key
117 # - border: print with/without table header and asciiart border
118 # - columns: limit output width (if > 0)
119 # - utf8: use utf8 characters for table delimiters
121 sub print_text_table
{
122 my ($data, $returnprops, $props_to_print, $options) = @_;
124 my $sort_key = $options->{sort_key
};
125 my $border = $options->{border
};
126 my $columns = $options->{columns
};
127 my $utf8 = $options->{utf8
};
128 my $encoding = $options->{encoding
} // 'UTF-8';
130 if (!defined($sort_key) || $sort_key eq 0) {
131 $sort_key = $props_to_print->[0];
134 if (defined($sort_key)) {
135 my $type = $returnprops->{$sort_key}->{type
} // 'string';
136 if ($type eq 'integer' || $type eq 'number') {
137 @$data = sort { $a->{$sort_key} <=> $b->{$sort_key} } @$data;
139 @$data = sort { $a->{$sort_key} cmp $b->{$sort_key} } @$data;
145 my $borderstring_m = '';
146 my $borderstring_b = '';
147 my $borderstring_t = '';
148 my $formatstring = '';
150 my $column_count = scalar(@$props_to_print);
154 foreach my $entry (@$data) {
159 for (my $i = 0; $i < $column_count; $i++) {
160 my $prop = $props_to_print->[$i];
161 my $propinfo = $returnprops->{$prop} // {};
163 my $text = data_to_text
($entry->{$prop}, $propinfo);
164 my $lines = [ split(/\n/, $text) ];
165 my $linecount = scalar(@$lines);
166 $height = $linecount if $linecount > $height;
169 foreach my $line (@$lines) {
170 my $len = length($line);
171 $width = $len if $len > $width;
174 $rowdata->{$prop} = {
186 for (my $i = 0; $i < $column_count; $i++) {
187 my $prop = $props_to_print->[$i];
188 my $propinfo = $returnprops->{$prop} // {};
190 my $title = $propinfo->{title
} // $prop;
191 my $cutoff = $propinfo->{print_width
} // $propinfo->{maxLength
};
193 # calculate maximal print width and cutoff
194 my $titlelen = length($title);
196 my $longest = $titlelen;
197 foreach my $coldata (@$tabledata) {
198 my $rowdata = $coldata->{rowdata
}->{$prop};
199 $longest = $rowdata->{width
} if $rowdata->{width
} > $longest;
201 $cutoff = $longest if !defined($cutoff) || $cutoff > $longest;
203 $colopts->{$prop} = {
209 if ($i == 0 && ($column_count == 1)) {
211 $formatstring .= "│ %-${cutoff}s │";
212 $borderstring_t .= "┌─" . ('─' x
$cutoff) . "─┐";
213 $borderstring_m .= "├─" . ('─' x
$cutoff) . "─┤";
214 $borderstring_b .= "└─" . ('─' x
$cutoff) . "─┘";
216 $formatstring .= "| %-${cutoff}s |";
217 $borderstring_m .= "+-" . ('-' x
$cutoff) . "-+";
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) . '-';
229 } elsif ($i == ($column_count - 1)) {
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) . "-+";
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 # skip alignment and cutoff on last column
252 $formatstring .= ($i == ($column_count - 1)) ?
"%s" : "%-${cutoff}s ";
256 $borderstring_t = $borderstring_m if !length($borderstring_t);
257 $borderstring_b = $borderstring_m if !length($borderstring_b);
263 print encode
($encoding, substr($text, 0, $columns) . "\n");
265 print encode
($encoding, $text) . "\n";
269 $writeln->($borderstring_t) if $border;
270 my $text = sprintf $formatstring, map { $colopts->{$_}->{title
} } @$props_to_print;
273 foreach my $coldata (@$tabledata) {
274 $writeln->($borderstring_m) if $border;
276 for (my $i = 0; $i < $coldata->{height
}; $i++) {
278 $text = sprintf $formatstring, map {
279 substr($coldata->{rowdata
}->{$_}->{lines
}->[$i] // '', 0, $colopts->{$_}->{cutoff
});
286 $writeln->($borderstring_b) if $border;
289 sub extract_properties_to_print
{
295 foreach my $key (keys %$propdef) {
296 my $prop = $propdef->{$key};
297 if ($prop->{optional
}) {
298 push @$optional, $key;
300 push @$required, $key;
304 return [ sort(@$required), sort(@$optional) ];
307 # prints the result of an API GET call returning an array as a table.
308 # takes formatting information from the results property of the call
309 # if $props_to_print is provided, prints only those columns. otherwise
310 # takes all fields of the results property, with a fallback
311 # to all fields occuring in items of $data.
313 my ($data, $result_schema, $props_to_print, $options) = @_;
315 die "can only print object lists\n"
316 if !($result_schema->{type
} eq 'array' && $result_schema->{items
}->{type
} eq 'object');
318 my $returnprops = $result_schema->{items
}->{properties
};
320 $props_to_print = extract_properties_to_print
($returnprops)
321 if !defined($props_to_print);
323 if (!scalar(@$props_to_print)) {
325 foreach my $obj (@$data) {
326 foreach my $key (keys %$obj) {
327 $all_props->{$key} = 1;
330 $props_to_print = [ sort keys %{$all_props} ];
333 die "unable to detect list properties\n" if !scalar(@$props_to_print);
335 print_text_table
($data, $returnprops, $props_to_print, $options);
338 sub print_api_result
{
339 my ($format, $data, $result_schema, $props_to_print, $options) = @_;
341 if (!defined($options)) {
342 $options = query_terminal_options
({});
344 $options = { %$options }; # copy
347 return if $result_schema->{type
} eq 'null';
349 if ($format eq 'json') {
350 # Note: we always use utf8 encoding for json format
351 print to_json
($data, {utf8
=> 1, allow_nonref
=> 1, canonical
=> 1, pretty
=> 1 });
352 } elsif ($format eq 'text' || $format eq 'plain') {
353 my $encoding = $options->{encoding
} // 'UTF-8';
354 my $type = $result_schema->{type
};
355 if ($type eq 'object') {
356 $props_to_print = extract_properties_to_print
($result_schema->{properties
})
357 if !defined($props_to_print);
358 $props_to_print = [ sort keys %$data ] if !scalar(@$props_to_print);
360 foreach my $key (@$props_to_print) {
361 push @$kvstore, { key
=> $key, value
=> data_to_text
($data->{$key}, $result_schema->{properties
}->{$key}) };
363 my $schema = { type
=> 'array', items
=> { type
=> 'object' }};
364 $options->{border
} = $format eq 'text';
365 print_api_list
($kvstore, $schema, ['key', 'value'], $options);
366 } elsif ($type eq 'array') {
367 return if !scalar(@$data);
368 my $item_type = $result_schema->{items
}->{type
};
369 if ($item_type eq 'object') {
370 $options->{border
} = $format eq 'text';
371 print_api_list
($data, $result_schema, $props_to_print, $options);
373 foreach my $entry (@$data) {
374 print encode
($encoding, data_to_text
($entry) . "\n");
378 print encode
($encoding, "$data\n");
381 die "internal error: unknown output format"; # should not happen