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 $show_border = !$options->{noborder
};
108 my $show_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 $border = { m
=> '', b
=> '', t
=> '', h
=> '' };
132 my $formatstring = '';
134 my $column_count = scalar(@$props_to_print);
138 foreach my $entry (@$data) {
143 for (my $i = 0; $i < $column_count; $i++) {
144 my $prop = $props_to_print->[$i];
145 my $propinfo = $returnprops->{$prop} // {};
147 my $text = data_to_text
($entry->{$prop}, $propinfo, $options, $terminal_opts);
148 my $lines = [ split(/\n/, $text) ];
149 my $linecount = scalar(@$lines);
150 $height = $linecount if $linecount > $height;
153 foreach my $line (@$lines) {
154 my $len = length($line);
155 $width = $len if $len > $width;
158 $width = ($width =~ m/^(\d+)$/) ?
int($1) : 0; # untaint int
160 $rowdata->{$prop} = {
172 for (my $i = 0; $i < $column_count; $i++) {
173 my $prop = $props_to_print->[$i];
174 my $propinfo = $returnprops->{$prop} // {};
175 my $type = $propinfo->{type
} // 'string';
176 my $alignstr = ($type eq 'integer' || $type eq 'number') ?
'' : '-';
178 my $title = $propinfo->{title
} // $prop;
179 my $cutoff = $propinfo->{print_width
} // $propinfo->{maxLength
};
181 # calculate maximal print width and cutoff
182 my $titlelen = length($title);
184 my $longest = $titlelen;
185 foreach my $coldata (@$tabledata) {
186 my $rowdata = $coldata->{rowdata
}->{$prop};
187 $longest = $rowdata->{width
} if $rowdata->{width
} > $longest;
189 $cutoff = $longest if !defined($cutoff) || $cutoff > $longest;
191 $colopts->{$prop} = {
197 if ($i == 0 && ($column_count == 1)) {
199 $formatstring .= "│ %$alignstr${cutoff}s │";
200 $border->{t
} .= "┌─" . ('─' x
$cutoff) . "─┐";
201 $border->{h
} .= "╞═" . ('═' x
$cutoff) . '═╡';
202 $border->{m
} .= "├─" . ('─' x
$cutoff) . "─┤";
203 $border->{b
} .= "└─" . ('─' x
$cutoff) . "─┘";
205 $formatstring .= "| %$alignstr${cutoff}s |";
206 $border->{m
} .= "+-" . ('-' x
$cutoff) . "-+";
207 $border->{h
} .= "+=" . ('=' x
$cutoff) . '=';
211 $formatstring .= "│ %$alignstr${cutoff}s ";
212 $border->{t
} .= "┌─" . ('─' x
$cutoff) . '─';
213 $border->{h
} .= "╞═" . ('═' x
$cutoff) . '═';
214 $border->{m
} .= "├─" . ('─' x
$cutoff) . '─';
215 $border->{b
} .= "└─" . ('─' x
$cutoff) . '─';
217 $formatstring .= "| %$alignstr${cutoff}s ";
218 $border->{m
} .= "+-" . ('-' x
$cutoff) . '-';
219 $border->{h
} .= "+=" . ('=' x
$cutoff) . '=';
221 } elsif ($i == ($column_count - 1)) {
223 $formatstring .= "│ %$alignstr${cutoff}s │";
224 $border->{t
} .= "┬─" . ('─' x
$cutoff) . "─┐";
225 $border->{h
} .= "╪═" . ('═' x
$cutoff) . '═╡';
226 $border->{m
} .= "┼─" . ('─' x
$cutoff) . "─┤";
227 $border->{b
} .= "┴─" . ('─' x
$cutoff) . "─┘";
229 $formatstring .= "| %$alignstr${cutoff}s |";
230 $border->{m
} .= "+-" . ('-' x
$cutoff) . "-+";
231 $border->{h
} .= "+=" . ('=' x
$cutoff) . "=+";
235 $formatstring .= "│ %$alignstr${cutoff}s ";
236 $border->{t
} .= "┬─" . ('─' x
$cutoff) . '─';
237 $border->{h
} .= "╪═" . ('═' x
$cutoff) . '═';
238 $border->{m
} .= "┼─" . ('─' x
$cutoff) . '─';
239 $border->{b
} .= "┴─" . ('─' x
$cutoff) . '─';
241 $formatstring .= "| %$alignstr${cutoff}s ";
242 $border->{m
} .= "+-" . ('-' x
$cutoff) . '-';
243 $border->{h
} .= "+=" . ('=' x
$cutoff) . '=';
247 # skip alignment and cutoff on last column
248 $formatstring .= ($i == ($column_count - 1)) ?
"%s" : "%$alignstr${cutoff}s ";
252 $border->{t
} = $border->{m
} if !length($border->{t
});
253 $border->{b
} = $border->{m
} if !length($border->{b
});
259 print encode
($encoding, substr($text, 0, $columns) . "\n");
261 print encode
($encoding, $text) . "\n";
265 $writeln->($border->{t
}) if $show_border;
268 my $text = sprintf $formatstring, map { $colopts->{$_}->{title
} } @$props_to_print;
270 $border->{sep
} = $border->{h
};
272 $border->{sep
} = $border->{m
};
275 for (my $i = 0; $i < scalar(@$tabledata); $i++) {
276 my $coldata = $tabledata->[$i];
278 if ($show_border && ($i != 0 || $show_header)) {
279 $writeln->($border->{sep
});
280 $border->{sep
} = $border->{m
};
283 for (my $i = 0; $i < $coldata->{height
}; $i++) {
284 my $text = sprintf $formatstring, map {
285 substr($coldata->{rowdata
}->{$_}->{lines
}->[$i] // '', 0, $colopts->{$_}->{cutoff
});
292 $writeln->($border->{b
}) if $show_border;
295 sub extract_properties_to_print
{
301 foreach my $key (keys %$propdef) {
302 my $prop = $propdef->{$key};
303 if ($prop->{optional
}) {
304 push @$optional, $key;
306 push @$required, $key;
310 return [ sort(@$required), sort(@$optional) ];
313 # prints the result of an API GET call returning an array as a table.
314 # takes formatting information from the results property of the call
315 # if $props_to_print is provided, prints only those columns. otherwise
316 # takes all fields of the results property, with a fallback
317 # to all fields occurring in items of $data.
319 my ($data, $result_schema, $props_to_print, $options, $terminal_opts) = @_;
321 die "can only print object lists\n"
322 if !($result_schema->{type
} eq 'array' && $result_schema->{items
}->{type
} eq 'object');
324 my $returnprops = $result_schema->{items
}->{properties
};
326 $props_to_print = extract_properties_to_print
($returnprops)
327 if !defined($props_to_print);
329 if (!scalar(@$props_to_print)) {
331 foreach my $obj (@$data) {
332 foreach my $key (keys %$obj) {
333 $all_props->{$key} = 1;
336 $props_to_print = [ sort keys %{$all_props} ];
339 die "unable to detect list properties\n" if !scalar(@$props_to_print);
341 print_text_table
($data, $returnprops, $props_to_print, $options, $terminal_opts);
344 my $guess_type = sub {
347 return 'null' if !defined($data);
349 my $class = ref($data);
350 return 'string' if !$class;
352 if ($class eq 'HASH') {
354 } elsif ($class eq 'ARRAY') {
357 return 'string'; # better than nothing
361 sub print_api_result
{
362 my ($data, $result_schema, $props_to_print, $options, $terminal_opts) = @_;
364 return if $options->{quiet
};
366 $terminal_opts //= query_terminal_options
({});
368 my $format = $options->{'output-format'} // 'text';
370 if ($result_schema && defined($result_schema->{type
})) {
371 return if $result_schema->{type
} eq 'null';
372 return if $result_schema->{optional
} && !defined($data);
374 my $type = $guess_type->($data);
375 $result_schema = { type
=> $type };
376 $result_schema->{items
} = { type
=> $guess_type->($data->[0]) } if $type eq 'array';
379 if ($format eq 'yaml') {
380 print encode
('UTF-8', YAML
::XS
::Dump
($data));
381 } elsif ($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, $terminal_opts) };
399 my $schema = { type
=> 'array', items
=> { type
=> 'object' }};
400 print_api_list
($kvstore, $schema, ['key', 'value'], $options, $terminal_opts);
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, $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, {});