1 package PVE
::CLIFormatter
;
7 use YAML
::XS
; # supports Dumping JSON::PP::Boolean
8 $YAML::XS
::Boolean
= "JSON::PP";
18 PVE
::JSONSchema
::register_renderer
('timestamp',
19 \
&PVE
::Format
::render_timestamp
);
20 PVE
::JSONSchema
::register_renderer
('timestamp_gmt',
21 \
&PVE
::Format
::render_timestamp_gmt
);
22 PVE
::JSONSchema
::register_renderer
('duration',
23 \
&PVE
::Format
::render_duration
);
24 PVE
::JSONSchema
::register_renderer
('fraction_as_percentage',
25 \
&PVE
::Format
::render_fraction_as_percentage
);
26 PVE
::JSONSchema
::register_renderer
('bytes',
27 \
&PVE
::Format
::render_bytes
);
32 my $data = YAML
::XS
::Dump
($value);
33 $data =~ s/^---[\n\s]//; # remove yaml marker
38 PVE
::JSONSchema
::register_renderer
('yaml', \
&render_yaml
);
40 sub query_terminal_options
{
46 ($options->{columns
}) = PVE
::PTY
::tcgetsize
(*STDOUT
);
49 $options->{encoding
} = I18N
::Langinfo
::langinfo
(I18N
::Langinfo
::CODESET
());
51 $options->{utf8
} = 1 if $options->{encoding
} eq 'UTF-8';
57 my ($data, $propdef, $options, $terminal_opts) = @_;
59 return '' if !defined($data);
61 $terminal_opts //= {};
63 my $human_readable = $options->{'human-readable'} // 1;
65 if ($human_readable && defined($propdef)) {
66 if (my $type = $propdef->{type
}) {
67 if ($type eq 'boolean') {
71 if (!defined($data) && defined($propdef->{default})) {
72 return "($propdef->{default})";
74 if (defined(my $renderer = $propdef->{renderer
})) {
75 my $code = PVE
::JSONSchema
::get_renderer
($renderer);
76 die "internal error: unknown renderer '$renderer'" if !$code;
77 return $code->($data, $options, $terminal_opts);
81 if (my $class = ref($data)) {
82 # JSON::PP::Boolean requires allow_nonref
83 return to_json
($data, { allow_nonref
=> 1, canonical
=> 1 });
89 # prints a formatted table with a title row.
90 # $data - the data to print (array of objects)
91 # $returnprops -json schema property description
92 # $props_to_print - ordered list of properties to print
94 # - sort_key: can be used to sort after a specific column, if it isn't set we sort
95 # after the leftmost column. This can be turned off by passing 0 as sort_key
96 # - noborder: print without asciiart border
97 # - noheader: print without table header
98 # - columns: limit output width (if > 0)
99 # - utf8: use utf8 characters for table delimiters
101 sub print_text_table
{
102 my ($data, $returnprops, $props_to_print, $options, $terminal_opts) = @_;
104 $terminal_opts //= query_terminal_options
({});
106 my $sort_key = $options->{sort_key
};
107 my $border = !$options->{noborder
};
108 my $header = !$options->{noheader
};
110 my $columns = $terminal_opts->{columns
};
111 my $utf8 = $terminal_opts->{utf8
};
112 my $encoding = $terminal_opts->{encoding
} // 'UTF-8';
114 $sort_key //= $props_to_print->[0];
116 if (defined($sort_key) && $sort_key ne 0) {
117 my $type = $returnprops->{$sort_key}->{type
} // 'string';
119 if ($type eq 'integer' || $type eq 'number') {
120 $cmpfn = sub { $_[0] <=> $_[1] };
122 $cmpfn = sub { $_[0] cmp $_[1] };
125 PVE
::Tools
::safe_compare
($a->{$sort_key}, $b->{$sort_key}, $cmpfn)
131 my $borderstring_m = '';
132 my $borderstring_b = '';
133 my $borderstring_t = '';
134 my $borderstring_h = '';
135 my $formatstring = '';
137 my $column_count = scalar(@$props_to_print);
141 foreach my $entry (@$data) {
146 for (my $i = 0; $i < $column_count; $i++) {
147 my $prop = $props_to_print->[$i];
148 my $propinfo = $returnprops->{$prop} // {};
150 my $text = data_to_text
($entry->{$prop}, $propinfo, $options, $terminal_opts);
151 my $lines = [ split(/\n/, $text) ];
152 my $linecount = scalar(@$lines);
153 $height = $linecount if $linecount > $height;
156 foreach my $line (@$lines) {
157 my $len = length($line);
158 $width = $len if $len > $width;
161 $width = ($width =~ m/^(\d+)$/) ?
int($1) : 0; # untaint int
163 $rowdata->{$prop} = {
175 for (my $i = 0; $i < $column_count; $i++) {
176 my $prop = $props_to_print->[$i];
177 my $propinfo = $returnprops->{$prop} // {};
178 my $type = $propinfo->{type
} // 'string';
179 my $alignstr = ($type eq 'integer' || $type eq 'number') ?
'' : '-';
181 my $title = $propinfo->{title
} // $prop;
182 my $cutoff = $propinfo->{print_width
} // $propinfo->{maxLength
};
184 # calculate maximal print width and cutoff
185 my $titlelen = length($title);
187 my $longest = $titlelen;
188 foreach my $coldata (@$tabledata) {
189 my $rowdata = $coldata->{rowdata
}->{$prop};
190 $longest = $rowdata->{width
} if $rowdata->{width
} > $longest;
192 $cutoff = $longest if !defined($cutoff) || $cutoff > $longest;
194 $colopts->{$prop} = {
200 if ($i == 0 && ($column_count == 1)) {
202 $formatstring .= "│ %$alignstr${cutoff}s │";
203 $borderstring_t .= "┌─" . ('─' x
$cutoff) . "─┐";
204 $borderstring_h .= "╞═" . ('═' x
$cutoff) . '═╡';
205 $borderstring_m .= "├─" . ('─' x
$cutoff) . "─┤";
206 $borderstring_b .= "└─" . ('─' x
$cutoff) . "─┘";
208 $formatstring .= "| %$alignstr${cutoff}s |";
209 $borderstring_m .= "+-" . ('-' x
$cutoff) . "-+";
210 $borderstring_h .= "+=" . ('=' x
$cutoff) . '=';
214 $formatstring .= "│ %$alignstr${cutoff}s ";
215 $borderstring_t .= "┌─" . ('─' x
$cutoff) . '─';
216 $borderstring_h .= "╞═" . ('═' x
$cutoff) . '═';
217 $borderstring_m .= "├─" . ('─' x
$cutoff) . '─';
218 $borderstring_b .= "└─" . ('─' x
$cutoff) . '─';
220 $formatstring .= "| %$alignstr${cutoff}s ";
221 $borderstring_m .= "+-" . ('-' x
$cutoff) . '-';
222 $borderstring_h .= "+=" . ('=' x
$cutoff) . '=';
224 } elsif ($i == ($column_count - 1)) {
226 $formatstring .= "│ %$alignstr${cutoff}s │";
227 $borderstring_t .= "┬─" . ('─' x
$cutoff) . "─┐";
228 $borderstring_h .= "╪═" . ('═' x
$cutoff) . '═╡';
229 $borderstring_m .= "┼─" . ('─' x
$cutoff) . "─┤";
230 $borderstring_b .= "┴─" . ('─' x
$cutoff) . "─┘";
232 $formatstring .= "| %$alignstr${cutoff}s |";
233 $borderstring_m .= "+-" . ('-' x
$cutoff) . "-+";
234 $borderstring_h .= "+=" . ('=' x
$cutoff) . "=+";
238 $formatstring .= "│ %$alignstr${cutoff}s ";
239 $borderstring_t .= "┬─" . ('─' x
$cutoff) . '─';
240 $borderstring_h .= "╪═" . ('═' x
$cutoff) . '═';
241 $borderstring_m .= "┼─" . ('─' x
$cutoff) . '─';
242 $borderstring_b .= "┴─" . ('─' x
$cutoff) . '─';
244 $formatstring .= "| %$alignstr${cutoff}s ";
245 $borderstring_m .= "+-" . ('-' x
$cutoff) . '-';
246 $borderstring_h .= "+=" . ('=' x
$cutoff) . '=';
250 # skip alignment and cutoff on last column
251 $formatstring .= ($i == ($column_count - 1)) ?
"%s" : "%$alignstr${cutoff}s ";
255 $borderstring_t = $borderstring_m if !length($borderstring_t);
256 $borderstring_b = $borderstring_m if !length($borderstring_b);
262 print encode
($encoding, substr($text, 0, $columns) . "\n");
264 print encode
($encoding, $text) . "\n";
268 $writeln->($borderstring_t) if $border;
270 my $borderstring_sep;
272 my $text = sprintf $formatstring, map { $colopts->{$_}->{title
} } @$props_to_print;
274 $borderstring_sep = $borderstring_h;
276 $borderstring_sep = $borderstring_m;
279 for (my $i = 0; $i < scalar(@$tabledata); $i++) {
280 my $coldata = $tabledata->[$i];
282 if ($border && ($i != 0 || $header)) {
283 $writeln->($borderstring_sep);
284 $borderstring_sep = $borderstring_m;
287 for (my $i = 0; $i < $coldata->{height
}; $i++) {
289 my $text = sprintf $formatstring, map {
290 substr($coldata->{rowdata
}->{$_}->{lines
}->[$i] // '', 0, $colopts->{$_}->{cutoff
});
297 $writeln->($borderstring_b) if $border;
300 sub extract_properties_to_print
{
306 foreach my $key (keys %$propdef) {
307 my $prop = $propdef->{$key};
308 if ($prop->{optional
}) {
309 push @$optional, $key;
311 push @$required, $key;
315 return [ sort(@$required), sort(@$optional) ];
318 # prints the result of an API GET call returning an array as a table.
319 # takes formatting information from the results property of the call
320 # if $props_to_print is provided, prints only those columns. otherwise
321 # takes all fields of the results property, with a fallback
322 # to all fields occurring in items of $data.
324 my ($data, $result_schema, $props_to_print, $options, $terminal_opts) = @_;
326 die "can only print object lists\n"
327 if !($result_schema->{type
} eq 'array' && $result_schema->{items
}->{type
} eq 'object');
329 my $returnprops = $result_schema->{items
}->{properties
};
331 $props_to_print = extract_properties_to_print
($returnprops)
332 if !defined($props_to_print);
334 if (!scalar(@$props_to_print)) {
336 foreach my $obj (@$data) {
337 foreach my $key (keys %$obj) {
338 $all_props->{$key} = 1;
341 $props_to_print = [ sort keys %{$all_props} ];
344 die "unable to detect list properties\n" if !scalar(@$props_to_print);
346 print_text_table
($data, $returnprops, $props_to_print, $options, $terminal_opts);
349 my $guess_type = sub {
352 return 'null' if !defined($data);
354 my $class = ref($data);
355 return 'string' if !$class;
357 if ($class eq 'HASH') {
359 } elsif ($class eq 'ARRAY') {
362 return 'string'; # better than nothing
366 sub print_api_result
{
367 my ($data, $result_schema, $props_to_print, $options, $terminal_opts) = @_;
369 return if $options->{quiet
};
371 $terminal_opts //= query_terminal_options
({});
373 my $format = $options->{'output-format'} // 'text';
375 if ($result_schema && defined($result_schema->{type
})) {
376 return if $result_schema->{type
} eq 'null';
377 return if $result_schema->{optional
} && !defined($data);
379 my $type = $guess_type->($data);
380 $result_schema = { type
=> $type };
381 $result_schema->{items
} = { type
=> $guess_type->($data->[0]) } if $type eq 'array';
384 if ($format eq 'yaml') {
385 print encode
('UTF-8', YAML
::XS
::Dump
($data));
386 } elsif ($format eq 'json') {
387 # Note: we always use utf8 encoding for json format
388 print to_json
($data, {utf8
=> 1, allow_nonref
=> 1, canonical
=> 1 }) . "\n";
389 } elsif ($format eq 'json-pretty') {
390 # Note: we always use utf8 encoding for json format
391 print to_json
($data, {utf8
=> 1, allow_nonref
=> 1, canonical
=> 1, pretty
=> 1 });
392 } elsif ($format eq 'text') {
393 my $encoding = $options->{encoding
} // 'UTF-8';
394 my $type = $result_schema->{type
};
395 if ($type eq 'object') {
396 $props_to_print = extract_properties_to_print
($result_schema->{properties
})
397 if !defined($props_to_print);
398 $props_to_print = [ sort keys %$data ] if !scalar(@$props_to_print);
400 foreach my $key (@$props_to_print) {
401 next if !defined($data->{$key});
402 push @$kvstore, { key
=> $key, value
=> data_to_text
($data->{$key}, $result_schema->{properties
}->{$key}, $options, $terminal_opts) };
404 my $schema = { type
=> 'array', items
=> { type
=> 'object' }};
405 print_api_list
($kvstore, $schema, ['key', 'value'], $options, $terminal_opts);
406 } elsif ($type eq 'array') {
407 return if !scalar(@$data);
408 my $item_type = $result_schema->{items
}->{type
};
409 if ($item_type eq 'object') {
410 print_api_list
($data, $result_schema, $props_to_print, $options, $terminal_opts);
413 foreach my $value (@$data) {
414 push @$kvstore, { value
=> $value };
416 my $schema = { type
=> 'array', items
=> { type
=> 'object', properties
=> { value
=> $result_schema->{items
} }}};
417 print_api_list
($kvstore, $schema, ['value'], { %$options, noheader
=> 1 }, $terminal_opts);
420 print encode
($encoding, "$data\n");
423 die "internal error: unknown output format"; # should not happen
427 sub print_api_result_plain
{
428 my ($data, $result_schema, $props_to_print, $options) = @_;
430 # avoid borders and header, ignore terminal width
431 $options = $options ?
{ %$options } : {}; # copy
433 $options->{noheader
} //= 1;
434 $options->{noborder
} //= 1;
436 print_api_result
($data, $result_schema, $props_to_print, $options, {});