]>
Commit | Line | Data |
---|---|---|
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 $border = !$options->{noborder}; | |
108 | my $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 $borderstring_m = ''; | |
132 | my $borderstring_b = ''; | |
133 | my $borderstring_t = ''; | |
134 | my $borderstring_h = ''; | |
135 | my $formatstring = ''; | |
136 | ||
137 | my $column_count = scalar(@$props_to_print); | |
138 | ||
139 | my $tabledata = []; | |
140 | ||
141 | foreach my $entry (@$data) { | |
142 | ||
143 | my $height = 1; | |
144 | my $rowdata = {}; | |
145 | ||
146 | for (my $i = 0; $i < $column_count; $i++) { | |
147 | my $prop = $props_to_print->[$i]; | |
148 | my $propinfo = $returnprops->{$prop} // {}; | |
149 | ||
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; | |
154 | ||
155 | my $width = 0; | |
156 | foreach my $line (@$lines) { | |
157 | my $len = length($line); | |
158 | $width = $len if $len > $width; | |
159 | } | |
160 | ||
161 | $width = ($width =~ m/^(\d+)$/) ? int($1) : 0; # untaint int | |
162 | ||
163 | $rowdata->{$prop} = { | |
164 | lines => $lines, | |
165 | width => $width, | |
166 | }; | |
167 | } | |
168 | ||
169 | push @$tabledata, { | |
170 | height => $height, | |
171 | rowdata => $rowdata, | |
172 | }; | |
173 | } | |
174 | ||
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') ? '' : '-'; | |
180 | ||
181 | my $title = $propinfo->{title} // $prop; | |
182 | my $cutoff = $propinfo->{print_width} // $propinfo->{maxLength}; | |
183 | ||
184 | # calculate maximal print width and cutoff | |
185 | my $titlelen = length($title); | |
186 | ||
187 | my $longest = $titlelen; | |
188 | foreach my $coldata (@$tabledata) { | |
189 | my $rowdata = $coldata->{rowdata}->{$prop}; | |
190 | $longest = $rowdata->{width} if $rowdata->{width} > $longest; | |
191 | } | |
192 | $cutoff = $longest if !defined($cutoff) || $cutoff > $longest; | |
193 | ||
194 | $colopts->{$prop} = { | |
195 | title => $title, | |
196 | cutoff => $cutoff, | |
197 | }; | |
198 | ||
199 | if ($border) { | |
200 | if ($i == 0 && ($column_count == 1)) { | |
201 | if ($utf8) { | |
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) . "─┘"; | |
207 | } else { | |
208 | $formatstring .= "| %$alignstr${cutoff}s |"; | |
209 | $borderstring_m .= "+-" . ('-' x $cutoff) . "-+"; | |
210 | $borderstring_h .= "+=" . ('=' x $cutoff) . '='; | |
211 | } | |
212 | } elsif ($i == 0) { | |
213 | if ($utf8) { | |
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) . '─'; | |
219 | } else { | |
220 | $formatstring .= "| %$alignstr${cutoff}s "; | |
221 | $borderstring_m .= "+-" . ('-' x $cutoff) . '-'; | |
222 | $borderstring_h .= "+=" . ('=' x $cutoff) . '='; | |
223 | } | |
224 | } elsif ($i == ($column_count - 1)) { | |
225 | if ($utf8) { | |
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) . "─┘"; | |
231 | } else { | |
232 | $formatstring .= "| %$alignstr${cutoff}s |"; | |
233 | $borderstring_m .= "+-" . ('-' x $cutoff) . "-+"; | |
234 | $borderstring_h .= "+=" . ('=' x $cutoff) . "=+"; | |
235 | } | |
236 | } else { | |
237 | if ($utf8) { | |
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) . '─'; | |
243 | } else { | |
244 | $formatstring .= "| %$alignstr${cutoff}s "; | |
245 | $borderstring_m .= "+-" . ('-' x $cutoff) . '-'; | |
246 | $borderstring_h .= "+=" . ('=' x $cutoff) . '='; | |
247 | } | |
248 | } | |
249 | } else { | |
250 | # skip alignment and cutoff on last column | |
251 | $formatstring .= ($i == ($column_count - 1)) ? "%s" : "%$alignstr${cutoff}s "; | |
252 | } | |
253 | } | |
254 | ||
255 | $borderstring_t = $borderstring_m if !length($borderstring_t); | |
256 | $borderstring_b = $borderstring_m if !length($borderstring_b); | |
257 | ||
258 | my $writeln = sub { | |
259 | my ($text) = @_; | |
260 | ||
261 | if ($columns) { | |
262 | print encode($encoding, substr($text, 0, $columns) . "\n"); | |
263 | } else { | |
264 | print encode($encoding, $text) . "\n"; | |
265 | } | |
266 | }; | |
267 | ||
268 | $writeln->($borderstring_t) if $border; | |
269 | ||
270 | my $borderstring_sep; | |
271 | if ($header) { | |
272 | my $text = sprintf $formatstring, map { $colopts->{$_}->{title} } @$props_to_print; | |
273 | $writeln->($text); | |
274 | $borderstring_sep = $borderstring_h; | |
275 | } else { | |
276 | $borderstring_sep = $borderstring_m; | |
277 | } | |
278 | ||
279 | for (my $i = 0; $i < scalar(@$tabledata); $i++) { | |
280 | my $coldata = $tabledata->[$i]; | |
281 | ||
282 | if ($border && ($i != 0 || $header)) { | |
283 | $writeln->($borderstring_sep); | |
284 | $borderstring_sep = $borderstring_m; | |
285 | } | |
286 | ||
287 | for (my $i = 0; $i < $coldata->{height}; $i++) { | |
288 | ||
289 | my $text = sprintf $formatstring, map { | |
290 | substr($coldata->{rowdata}->{$_}->{lines}->[$i] // '', 0, $colopts->{$_}->{cutoff}); | |
291 | } @$props_to_print; | |
292 | ||
293 | $writeln->($text); | |
294 | } | |
295 | } | |
296 | ||
297 | $writeln->($borderstring_b) if $border; | |
298 | } | |
299 | ||
300 | sub extract_properties_to_print { | |
301 | my ($propdef) = @_; | |
302 | ||
303 | my $required = []; | |
304 | my $optional = []; | |
305 | ||
306 | foreach my $key (keys %$propdef) { | |
307 | my $prop = $propdef->{$key}; | |
308 | if ($prop->{optional}) { | |
309 | push @$optional, $key; | |
310 | } else { | |
311 | push @$required, $key; | |
312 | } | |
313 | } | |
314 | ||
315 | return [ sort(@$required), sort(@$optional) ]; | |
316 | } | |
317 | ||
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. | |
323 | sub print_api_list { | |
324 | my ($data, $result_schema, $props_to_print, $options, $terminal_opts) = @_; | |
325 | ||
326 | die "can only print object lists\n" | |
327 | if !($result_schema->{type} eq 'array' && $result_schema->{items}->{type} eq 'object'); | |
328 | ||
329 | my $returnprops = $result_schema->{items}->{properties}; | |
330 | ||
331 | $props_to_print = extract_properties_to_print($returnprops) | |
332 | if !defined($props_to_print); | |
333 | ||
334 | if (!scalar(@$props_to_print)) { | |
335 | my $all_props = {}; | |
336 | foreach my $obj (@$data) { | |
337 | foreach my $key (keys %$obj) { | |
338 | $all_props->{$key} = 1; | |
339 | } | |
340 | } | |
341 | $props_to_print = [ sort keys %{$all_props} ]; | |
342 | } | |
343 | ||
344 | die "unable to detect list properties\n" if !scalar(@$props_to_print); | |
345 | ||
346 | print_text_table($data, $returnprops, $props_to_print, $options, $terminal_opts); | |
347 | } | |
348 | ||
349 | my $guess_type = sub { | |
350 | my $data = shift; | |
351 | ||
352 | return 'null' if !defined($data); | |
353 | ||
354 | my $class = ref($data); | |
355 | return 'string' if !$class; | |
356 | ||
357 | if ($class eq 'HASH') { | |
358 | return 'object'; | |
359 | } elsif ($class eq 'ARRAY') { | |
360 | return 'array'; | |
361 | } else { | |
362 | return 'string'; # better than nothing | |
363 | } | |
364 | }; | |
365 | ||
366 | sub print_api_result { | |
367 | my ($data, $result_schema, $props_to_print, $options, $terminal_opts) = @_; | |
368 | ||
369 | return if $options->{quiet}; | |
370 | ||
371 | $terminal_opts //= query_terminal_options({}); | |
372 | ||
373 | my $format = $options->{'output-format'} // 'text'; | |
374 | ||
375 | if ($result_schema && defined($result_schema->{type})) { | |
376 | return if $result_schema->{type} eq 'null'; | |
377 | return if $result_schema->{optional} && !defined($data); | |
378 | } else { | |
379 | my $type = $guess_type->($data); | |
380 | $result_schema = { type => $type }; | |
381 | $result_schema->{items} = { type => $guess_type->($data->[0]) } if $type eq 'array'; | |
382 | } | |
383 | ||
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); | |
399 | my $kvstore = []; | |
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) }; | |
403 | } | |
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); | |
411 | } else { | |
412 | my $kvstore = []; | |
413 | foreach my $value (@$data) { | |
414 | push @$kvstore, { value => $value }; | |
415 | } | |
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); | |
418 | } | |
419 | } else { | |
420 | print encode($encoding, "$data\n"); | |
421 | } | |
422 | } else { | |
423 | die "internal error: unknown output format"; # should not happen | |
424 | } | |
425 | } | |
426 | ||
427 | sub print_api_result_plain { | |
428 | my ($data, $result_schema, $props_to_print, $options) = @_; | |
429 | ||
430 | # avoid borders and header, ignore terminal width | |
431 | $options = $options ? { %$options } : {}; # copy | |
432 | ||
433 | $options->{noheader} //= 1; | |
434 | $options->{noborder} //= 1; | |
435 | ||
436 | print_api_result($data, $result_schema, $props_to_print, $options, {}); | |
437 | } | |
438 | ||
439 | 1; |