]> git.proxmox.com Git - pve-common.git/blob - src/PVE/CLIFormatter.pm
cli format: refactoring and code bloat reduction
[pve-common.git] / src / PVE / CLIFormatter.pm
1 package PVE::CLIFormatter;
2
3 use strict;
4 use warnings;
5
6 use I18N::Langinfo;
7 use YAML::XS; # supports Dumping JSON::PP::Boolean
8 $YAML::XS::Boolean = "JSON::PP";
9
10 use PVE::JSONSchema;
11 use PVE::PTY;
12 use PVE::Format;
13
14 use JSON;
15 use utf8;
16 use Encode;
17
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);
28
29 sub render_yaml {
30 my ($value) = @_;
31
32 my $data = YAML::XS::Dump($value);
33 $data =~ s/^---[\n\s]//; # remove yaml marker
34
35 return $data;
36 }
37
38 PVE::JSONSchema::register_renderer('yaml', \&render_yaml);
39
40 sub query_terminal_options {
41 my ($options) = @_;
42
43 $options //= {};
44
45 if (-t STDOUT) {
46 ($options->{columns}) = PVE::PTY::tcgetsize(*STDOUT);
47 }
48
49 $options->{encoding} = I18N::Langinfo::langinfo(I18N::Langinfo::CODESET());
50
51 $options->{utf8} = 1 if $options->{encoding} eq 'UTF-8';
52
53 return $options;
54 }
55
56 sub data_to_text {
57 my ($data, $propdef, $options, $terminal_opts) = @_;
58
59 return '' if !defined($data);
60
61 $terminal_opts //= {};
62
63 my $human_readable = $options->{'human-readable'} // 1;
64
65 if ($human_readable && defined($propdef)) {
66 if (my $type = $propdef->{type}) {
67 if ($type eq 'boolean') {
68 return $data ? 1 : 0;
69 }
70 }
71 if (!defined($data) && defined($propdef->{default})) {
72 return "($propdef->{default})";
73 }
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);
78 }
79 }
80
81 if (my $class = ref($data)) {
82 # JSON::PP::Boolean requires allow_nonref
83 return to_json($data, { allow_nonref => 1, canonical => 1 });
84 } else {
85 return "$data";
86 }
87 }
88
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
93 # $options
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
100
101 sub print_text_table {
102 my ($data, $returnprops, $props_to_print, $options, $terminal_opts) = @_;
103
104 $terminal_opts //= query_terminal_options({});
105
106 my $sort_key = $options->{sort_key};
107 my $show_border = !$options->{noborder};
108 my $show_header = !$options->{noheader};
109
110 my $columns = $terminal_opts->{columns};
111 my $utf8 = $terminal_opts->{utf8};
112 my $encoding = $terminal_opts->{encoding} // 'UTF-8';
113
114 $sort_key //= $props_to_print->[0];
115
116 if (defined($sort_key) && $sort_key ne 0) {
117 my $type = $returnprops->{$sort_key}->{type} // 'string';
118 my $cmpfn;
119 if ($type eq 'integer' || $type eq 'number') {
120 $cmpfn = sub { $_[0] <=> $_[1] };
121 } else {
122 $cmpfn = sub { $_[0] cmp $_[1] };
123 }
124 @$data = sort {
125 PVE::Tools::safe_compare($a->{$sort_key}, $b->{$sort_key}, $cmpfn)
126 } @$data;
127 }
128
129 my $colopts = {};
130
131 my $border = { m => '', b => '', t => '', h => '' };
132 my $formatstring = '';
133
134 my $column_count = scalar(@$props_to_print);
135
136 my $tabledata = [];
137
138 foreach my $entry (@$data) {
139
140 my $height = 1;
141 my $rowdata = {};
142
143 for (my $i = 0; $i < $column_count; $i++) {
144 my $prop = $props_to_print->[$i];
145 my $propinfo = $returnprops->{$prop} // {};
146
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;
151
152 my $width = 0;
153 foreach my $line (@$lines) {
154 my $len = length($line);
155 $width = $len if $len > $width;
156 }
157
158 $width = ($width =~ m/^(\d+)$/) ? int($1) : 0; # untaint int
159
160 $rowdata->{$prop} = {
161 lines => $lines,
162 width => $width,
163 };
164 }
165
166 push @$tabledata, {
167 height => $height,
168 rowdata => $rowdata,
169 };
170 }
171
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') ? '' : '-';
177
178 my $title = $propinfo->{title} // $prop;
179 my $cutoff = $propinfo->{print_width} // $propinfo->{maxLength};
180
181 # calculate maximal print width and cutoff
182 my $titlelen = length($title);
183
184 my $longest = $titlelen;
185 foreach my $coldata (@$tabledata) {
186 my $rowdata = $coldata->{rowdata}->{$prop};
187 $longest = $rowdata->{width} if $rowdata->{width} > $longest;
188 }
189 $cutoff = $longest if !defined($cutoff) || $cutoff > $longest;
190
191 $colopts->{$prop} = {
192 title => $title,
193 cutoff => $cutoff,
194 };
195
196 if ($show_border) {
197 if ($i == 0 && ($column_count == 1)) {
198 if ($utf8) {
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) . "─┘";
204 } else {
205 $formatstring .= "| %$alignstr${cutoff}s |";
206 $border->{m} .= "+-" . ('-' x $cutoff) . "-+";
207 $border->{h} .= "+=" . ('=' x $cutoff) . '=';
208 }
209 } elsif ($i == 0) {
210 if ($utf8) {
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) . '─';
216 } else {
217 $formatstring .= "| %$alignstr${cutoff}s ";
218 $border->{m} .= "+-" . ('-' x $cutoff) . '-';
219 $border->{h} .= "+=" . ('=' x $cutoff) . '=';
220 }
221 } elsif ($i == ($column_count - 1)) {
222 if ($utf8) {
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) . "─┘";
228 } else {
229 $formatstring .= "| %$alignstr${cutoff}s |";
230 $border->{m} .= "+-" . ('-' x $cutoff) . "-+";
231 $border->{h} .= "+=" . ('=' x $cutoff) . "=+";
232 }
233 } else {
234 if ($utf8) {
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) . '─';
240 } else {
241 $formatstring .= "| %$alignstr${cutoff}s ";
242 $border->{m} .= "+-" . ('-' x $cutoff) . '-';
243 $border->{h} .= "+=" . ('=' x $cutoff) . '=';
244 }
245 }
246 } else {
247 # skip alignment and cutoff on last column
248 $formatstring .= ($i == ($column_count - 1)) ? "%s" : "%$alignstr${cutoff}s ";
249 }
250 }
251
252 $border->{t} = $border->{m} if !length($border->{t});
253 $border->{b} = $border->{m} if !length($border->{b});
254
255 my $writeln = sub {
256 my ($text) = @_;
257
258 if ($columns) {
259 print encode($encoding, substr($text, 0, $columns) . "\n");
260 } else {
261 print encode($encoding, $text) . "\n";
262 }
263 };
264
265 $writeln->($border->{t}) if $show_border;
266
267 if ($show_header) {
268 my $text = sprintf $formatstring, map { $colopts->{$_}->{title} } @$props_to_print;
269 $writeln->($text);
270 $border->{sep} = $border->{h};
271 } else {
272 $border->{sep} = $border->{m};
273 }
274
275 for (my $i = 0; $i < scalar(@$tabledata); $i++) {
276 my $coldata = $tabledata->[$i];
277
278 if ($show_border && ($i != 0 || $show_header)) {
279 $writeln->($border->{sep});
280 $border->{sep} = $border->{m};
281 }
282
283 for (my $i = 0; $i < $coldata->{height}; $i++) {
284 my $text = sprintf $formatstring, map {
285 substr($coldata->{rowdata}->{$_}->{lines}->[$i] // '', 0, $colopts->{$_}->{cutoff});
286 } @$props_to_print;
287
288 $writeln->($text);
289 }
290 }
291
292 $writeln->($border->{b}) if $show_border;
293 }
294
295 sub extract_properties_to_print {
296 my ($propdef) = @_;
297
298 my $required = [];
299 my $optional = [];
300
301 foreach my $key (keys %$propdef) {
302 my $prop = $propdef->{$key};
303 if ($prop->{optional}) {
304 push @$optional, $key;
305 } else {
306 push @$required, $key;
307 }
308 }
309
310 return [ sort(@$required), sort(@$optional) ];
311 }
312
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.
318 sub print_api_list {
319 my ($data, $result_schema, $props_to_print, $options, $terminal_opts) = @_;
320
321 die "can only print object lists\n"
322 if !($result_schema->{type} eq 'array' && $result_schema->{items}->{type} eq 'object');
323
324 my $returnprops = $result_schema->{items}->{properties};
325
326 $props_to_print = extract_properties_to_print($returnprops)
327 if !defined($props_to_print);
328
329 if (!scalar(@$props_to_print)) {
330 my $all_props = {};
331 foreach my $obj (@$data) {
332 foreach my $key (keys %$obj) {
333 $all_props->{$key} = 1;
334 }
335 }
336 $props_to_print = [ sort keys %{$all_props} ];
337 }
338
339 die "unable to detect list properties\n" if !scalar(@$props_to_print);
340
341 print_text_table($data, $returnprops, $props_to_print, $options, $terminal_opts);
342 }
343
344 my $guess_type = sub {
345 my $data = shift;
346
347 return 'null' if !defined($data);
348
349 my $class = ref($data);
350 return 'string' if !$class;
351
352 if ($class eq 'HASH') {
353 return 'object';
354 } elsif ($class eq 'ARRAY') {
355 return 'array';
356 } else {
357 return 'string'; # better than nothing
358 }
359 };
360
361 sub print_api_result {
362 my ($data, $result_schema, $props_to_print, $options, $terminal_opts) = @_;
363
364 return if $options->{quiet};
365
366 $terminal_opts //= query_terminal_options({});
367
368 my $format = $options->{'output-format'} // 'text';
369
370 if ($result_schema && defined($result_schema->{type})) {
371 return if $result_schema->{type} eq 'null';
372 return if $result_schema->{optional} && !defined($data);
373 } else {
374 my $type = $guess_type->($data);
375 $result_schema = { type => $type };
376 $result_schema->{items} = { type => $guess_type->($data->[0]) } if $type eq 'array';
377 }
378
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);
394 my $kvstore = [];
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) };
398 }
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);
406 } else {
407 my $kvstore = [];
408 foreach my $value (@$data) {
409 push @$kvstore, { value => $value };
410 }
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);
413 }
414 } else {
415 print encode($encoding, "$data\n");
416 }
417 } else {
418 die "internal error: unknown output format"; # should not happen
419 }
420 }
421
422 sub print_api_result_plain {
423 my ($data, $result_schema, $props_to_print, $options) = @_;
424
425 # avoid borders and header, ignore terminal width
426 $options = $options ? { %$options } : {}; # copy
427
428 $options->{noheader} //= 1;
429 $options->{noborder} //= 1;
430
431 print_api_result($data, $result_schema, $props_to_print, $options, {});
432 }
433
434 1;