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', \
&PVE
::Format
::render_timestamp
);
19 PVE
::JSONSchema
::register_renderer
('timestamp_gmt', \
&PVE
::Format
::render_timestamp_gmt
);
20 PVE
::JSONSchema
::register_renderer
('duration', \
&PVE
::Format
::render_duration
);
21 PVE
::JSONSchema
::register_renderer
('fraction_as_percentage', \
&PVE
::Format
::render_fraction_as_percentage
);
22 PVE
::JSONSchema
::register_renderer
('bytes', \
&PVE
::Format
::render_bytes
);
27 my $data = YAML
::XS
::Dump
($value);
28 $data =~ s/^---[\n\s]//; # remove yaml marker
33 PVE
::JSONSchema
::register_renderer
('yaml', \
&render_yaml
);
35 sub query_terminal_options
{
41 ($options->{columns
}) = PVE
::PTY
::tcgetsize
(*STDOUT
);
44 $options->{encoding
} = I18N
::Langinfo
::langinfo
(I18N
::Langinfo
::CODESET
());
46 $options->{utf8
} = 1 if $options->{encoding
} eq 'UTF-8';
52 my ($data, $propdef, $options, $terminal_opts) = @_;
54 return '' if !defined($data);
56 $terminal_opts //= {};
58 my $human_readable = $options->{'human-readable'} // 1;
60 if ($human_readable && defined($propdef)) {
61 if (my $type = $propdef->{type
}) {
62 if ($type eq 'boolean') {
66 if (!defined($data) && defined($propdef->{default})) {
67 return "($propdef->{default})";
69 if (defined(my $renderer = $propdef->{renderer
})) {
70 my $code = PVE
::JSONSchema
::get_renderer
($renderer);
71 die "internal error: unknown renderer '$renderer'" if !$code;
72 return $code->($data, $options, $terminal_opts);
76 if (my $class = ref($data)) {
77 # JSON::PP::Boolean requires allow_nonref
78 return to_json
($data, { allow_nonref
=> 1, canonical
=> 1 });
84 # prints a formatted table with a title row.
85 # $data - the data to print (array of objects)
86 # $returnprops -json schema property description
87 # $props_to_print - ordered list of properties to print
89 # - sort_key: can be used to sort after a specific column, if it isn't set we sort
90 # after the leftmost column. This can be turned off by passing 0 as sort_key
91 # - noborder: print without asciiart border
92 # - noheader: print without table header
93 # - columns: limit output width (if > 0)
94 # - utf8: use utf8 characters for table delimiters
96 sub print_text_table
{
97 my ($data, $returnprops, $props_to_print, $options, $terminal_opts) = @_;
99 $terminal_opts //= query_terminal_options
({});
101 my $sort_key = $options->{sort_key
};
102 my $show_border = !$options->{noborder
};
103 my $show_header = !$options->{noheader
};
105 my $columns = $terminal_opts->{columns
};
106 my $utf8 = $terminal_opts->{utf8
};
107 my $encoding = $terminal_opts->{encoding
} // 'UTF-8';
109 $sort_key //= $props_to_print->[0];
111 if (defined($sort_key) && $sort_key ne 0) {
112 my $type = $returnprops->{$sort_key}->{type
} // 'string';
114 if ($type eq 'integer' || $type eq 'number') {
115 $cmpfn = sub { $_[0] <=> $_[1] };
117 $cmpfn = sub { $_[0] cmp $_[1] };
120 PVE
::Tools
::safe_compare
($a->{$sort_key}, $b->{$sort_key}, $cmpfn)
126 my $border = { m
=> '', b
=> '', t
=> '', h
=> '' };
127 my $formatstring = '';
129 my $column_count = scalar(@$props_to_print);
133 foreach my $entry (@$data) {
138 for (my $i = 0; $i < $column_count; $i++) {
139 my $prop = $props_to_print->[$i];
140 my $propinfo = $returnprops->{$prop} // {};
142 my $text = data_to_text
($entry->{$prop}, $propinfo, $options, $terminal_opts);
143 my $lines = [ split(/\n/, $text) ];
144 my $linecount = scalar(@$lines);
145 $height = $linecount if $linecount > $height;
148 foreach my $line (@$lines) {
149 my $len = length($line);
150 $width = $len if $len > $width;
153 $width = ($width =~ m/^(\d+)$/) ?
int($1) : 0; # untaint int
155 $rowdata->{$prop} = {
167 for (my $i = 0; $i < $column_count; $i++) {
168 my $prop = $props_to_print->[$i];
169 my $propinfo = $returnprops->{$prop} // {};
170 my $type = $propinfo->{type
} // 'string';
171 my $alignstr = ($type eq 'integer' || $type eq 'number') ?
'' : '-';
173 my $title = $propinfo->{title
} // $prop;
174 my $cutoff = $propinfo->{print_width
} // $propinfo->{maxLength
};
176 # calculate maximal print width and cutoff
177 my $titlelen = length($title);
179 my $longest = $titlelen;
180 foreach my $coldata (@$tabledata) {
181 my $rowdata = $coldata->{rowdata
}->{$prop};
182 $longest = $rowdata->{width
} if $rowdata->{width
} > $longest;
184 $cutoff = $longest if !defined($cutoff) || $cutoff > $longest;
186 $colopts->{$prop} = {
192 if ($i == 0 && ($column_count == 1)) {
194 $formatstring .= "│ %$alignstr${cutoff}s │";
195 $border->{t
} .= "┌─" . ('─' x
$cutoff) . "─┐";
196 $border->{h
} .= "╞═" . ('═' x
$cutoff) . '═╡';
197 $border->{m
} .= "├─" . ('─' x
$cutoff) . "─┤";
198 $border->{b
} .= "└─" . ('─' x
$cutoff) . "─┘";
200 $formatstring .= "| %$alignstr${cutoff}s |";
201 $border->{m
} .= "+-" . ('-' x
$cutoff) . "-+";
202 $border->{h
} .= "+=" . ('=' x
$cutoff) . '=';
206 $formatstring .= "│ %$alignstr${cutoff}s ";
207 $border->{t
} .= "┌─" . ('─' x
$cutoff) . '─';
208 $border->{h
} .= "╞═" . ('═' x
$cutoff) . '═';
209 $border->{m
} .= "├─" . ('─' x
$cutoff) . '─';
210 $border->{b
} .= "└─" . ('─' x
$cutoff) . '─';
212 $formatstring .= "| %$alignstr${cutoff}s ";
213 $border->{m
} .= "+-" . ('-' x
$cutoff) . '-';
214 $border->{h
} .= "+=" . ('=' x
$cutoff) . '=';
216 } elsif ($i == ($column_count - 1)) {
218 $formatstring .= "│ %$alignstr${cutoff}s │";
219 $border->{t
} .= "┬─" . ('─' x
$cutoff) . "─┐";
220 $border->{h
} .= "╪═" . ('═' x
$cutoff) . '═╡';
221 $border->{m
} .= "┼─" . ('─' x
$cutoff) . "─┤";
222 $border->{b
} .= "┴─" . ('─' x
$cutoff) . "─┘";
224 $formatstring .= "| %$alignstr${cutoff}s |";
225 $border->{m
} .= "+-" . ('-' x
$cutoff) . "-+";
226 $border->{h
} .= "+=" . ('=' x
$cutoff) . "=+";
230 $formatstring .= "│ %$alignstr${cutoff}s ";
231 $border->{t
} .= "┬─" . ('─' x
$cutoff) . '─';
232 $border->{h
} .= "╪═" . ('═' x
$cutoff) . '═';
233 $border->{m
} .= "┼─" . ('─' x
$cutoff) . '─';
234 $border->{b
} .= "┴─" . ('─' x
$cutoff) . '─';
236 $formatstring .= "| %$alignstr${cutoff}s ";
237 $border->{m
} .= "+-" . ('-' x
$cutoff) . '-';
238 $border->{h
} .= "+=" . ('=' x
$cutoff) . '=';
242 # skip alignment and cutoff on last column
243 $formatstring .= ($i == ($column_count - 1)) ?
"%s" : "%$alignstr${cutoff}s ";
247 $border->{t
} = $border->{m
} if !length($border->{t
});
248 $border->{b
} = $border->{m
} if !length($border->{b
});
254 print encode
($encoding, substr($text, 0, $columns) . "\n");
256 print encode
($encoding, $text) . "\n";
260 $writeln->($border->{t
}) if $show_border;
263 my $text = sprintf $formatstring, map { $colopts->{$_}->{title
} } @$props_to_print;
265 $border->{sep
} = $border->{h
};
267 $border->{sep
} = $border->{m
};
270 for (my $i = 0; $i < scalar(@$tabledata); $i++) {
271 my $coldata = $tabledata->[$i];
273 if ($show_border && ($i != 0 || $show_header)) {
274 $writeln->($border->{sep
});
275 $border->{sep
} = $border->{m
};
278 for (my $i = 0; $i < $coldata->{height
}; $i++) {
279 my $text = sprintf $formatstring, map {
280 substr($coldata->{rowdata
}->{$_}->{lines
}->[$i] // '', 0, $colopts->{$_}->{cutoff
});
287 $writeln->($border->{b
}) if $show_border;
290 sub extract_properties_to_print
{
296 foreach my $key (keys %$propdef) {
297 my $prop = $propdef->{$key};
298 if ($prop->{optional
}) {
299 push @$optional, $key;
301 push @$required, $key;
305 return [ sort(@$required), sort(@$optional) ];
308 # prints the result of an API GET call returning an array as a table.
309 # takes formatting information from the results property of the call
310 # if $props_to_print is provided, prints only those columns. otherwise
311 # takes all fields of the results property, with a fallback
312 # to all fields occurring in items of $data.
314 my ($data, $result_schema, $props_to_print, $options, $terminal_opts) = @_;
316 die "can only print object lists\n"
317 if !($result_schema->{type
} eq 'array' && $result_schema->{items
}->{type
} eq 'object');
319 my $returnprops = $result_schema->{items
}->{properties
};
321 $props_to_print = extract_properties_to_print
($returnprops)
322 if !defined($props_to_print);
324 if (!scalar(@$props_to_print)) {
326 foreach my $obj (@$data) {
327 foreach my $key (keys %$obj) {
328 $all_props->{$key} = 1;
331 $props_to_print = [ sort keys %{$all_props} ];
334 die "unable to detect list properties\n" if !scalar(@$props_to_print);
336 print_text_table
($data, $returnprops, $props_to_print, $options, $terminal_opts);
339 my $guess_type = sub {
342 return 'null' if !defined($data);
344 my $class = ref($data);
345 return 'string' if !$class;
347 if ($class eq 'HASH') {
349 } elsif ($class eq 'ARRAY') {
352 return 'string'; # better than nothing
356 sub print_api_result
{
357 my ($data, $result_schema, $props_to_print, $options, $terminal_opts) = @_;
359 return if $options->{quiet
};
361 $terminal_opts //= query_terminal_options
({});
363 my $format = $options->{'output-format'} // 'text';
365 if ($result_schema && defined($result_schema->{type
})) {
366 return if $result_schema->{type
} eq 'null';
367 return if $result_schema->{optional
} && !defined($data);
369 my $type = $guess_type->($data);
370 $result_schema = { type
=> $type };
371 $result_schema->{items
} = { type
=> $guess_type->($data->[0]) } if $type eq 'array';
374 if ($format eq 'yaml') {
375 print encode
('UTF-8', YAML
::XS
::Dump
($data));
376 } elsif ($format eq 'json') {
377 # Note: we always use utf8 encoding for json format
378 print to_json
($data, {utf8
=> 1, allow_nonref
=> 1, canonical
=> 1 }) . "\n";
379 } elsif ($format eq 'json-pretty') {
380 # Note: we always use utf8 encoding for json format
381 print to_json
($data, {utf8
=> 1, allow_nonref
=> 1, canonical
=> 1, pretty
=> 1 });
382 } elsif ($format eq 'text') {
383 my $encoding = $options->{encoding
} // 'UTF-8';
384 my $type = $result_schema->{type
};
385 if ($type eq 'object') {
386 $props_to_print = extract_properties_to_print
($result_schema->{properties
})
387 if !defined($props_to_print);
388 $props_to_print = [ sort keys %$data ] if !scalar(@$props_to_print);
390 foreach my $key (@$props_to_print) {
391 next if !defined($data->{$key});
392 push @$kvstore, { key
=> $key, value
=> data_to_text
($data->{$key}, $result_schema->{properties
}->{$key}, $options, $terminal_opts) };
394 my $schema = { type
=> 'array', items
=> { type
=> 'object' }};
395 print_api_list
($kvstore, $schema, ['key', 'value'], $options, $terminal_opts);
396 } elsif ($type eq 'array') {
397 if (ref($data) eq 'ARRAY') {
398 return if !scalar(@$data);
399 } elsif (ref($data) eq 'HASH') {
400 return if !scalar($data->%*);
401 die "got hash object, but result schema specified array!\n"
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, $terminal_opts);
408 foreach my $value (@$data) {
409 push @$kvstore, { value
=> $value };
411 my $schema = { type
=> 'array', items
=> { type
=> 'object', properties
=> { value
=> $result_schema->{items
} }}};
412 print_api_list
($kvstore, $schema, ['value'], { %$options, noheader
=> 1 }, $terminal_opts);
415 print encode
($encoding, "$data\n");
418 die "internal error: unknown output format"; # should not happen
422 sub print_api_result_plain
{
423 my ($data, $result_schema, $props_to_print, $options) = @_;
425 # avoid borders and header, ignore terminal width
426 $options = $options ?
{ %$options } : {}; # copy
428 $options->{noheader
} //= 1;
429 $options->{noborder
} //= 1;
431 print_api_result
($data, $result_schema, $props_to_print, $options, {});