]>
Commit | Line | Data |
---|---|---|
f53ad23a DM |
1 | package PVE::CLIFormatter; |
2 | ||
3 | use strict; | |
4 | use warnings; | |
4ac85000 | 5 | use I18N::Langinfo; |
5e287f60 | 6 | use POSIX qw(strftime); |
ba752c80 | 7 | use CPAN::Meta::YAML; # comes with perl-modules |
4ac85000 | 8 | |
84142f1d | 9 | use PVE::JSONSchema; |
4ac85000 | 10 | use PVE::PTY; |
f53ad23a | 11 | use JSON; |
eb1c51c2 DM |
12 | use utf8; |
13 | use Encode; | |
f53ad23a | 14 | |
5e287f60 DM |
15 | sub render_timestamp { |
16 | my ($epoch) = @_; | |
17 | ||
18 | # ISO 8601 date format | |
19 | return strftime("%F %H:%M:%S", localtime($epoch)); | |
20 | } | |
21 | ||
22 | PVE::JSONSchema::register_renderer('timestamp', \&render_timestamp); | |
23 | ||
e735d7b0 DM |
24 | sub render_timestamp_gmt { |
25 | my ($epoch) = @_; | |
26 | ||
27 | # ISO 8601 date format, standard Greenwich time zone | |
28 | return strftime("%F %H:%M:%S", gmtime($epoch)); | |
29 | } | |
30 | ||
31 | PVE::JSONSchema::register_renderer('timestamp_gmt', \&render_timestamp_gmt); | |
32 | ||
f495c868 DM |
33 | sub render_duration { |
34 | my ($duration_in_seconds) = @_; | |
35 | ||
36 | my $text = ''; | |
37 | my $rest = $duration_in_seconds; | |
38 | ||
39 | my $step = sub { | |
40 | my ($unit, $unitlength) = @_; | |
41 | ||
42 | if ((my $v = int($rest/$unitlength)) > 0) { | |
43 | $text .= " " if length($text); | |
44 | $text .= "${v}${unit}"; | |
45 | $rest -= $v * $unitlength; | |
46 | } | |
47 | }; | |
48 | ||
49 | $step->('w', 7*24*3600); | |
50 | $step->('d', 24*3600); | |
51 | $step->('h', 3600); | |
52 | $step->('m', 60); | |
53 | $step->('s', 1); | |
54 | ||
55 | return $text; | |
56 | } | |
57 | ||
58 | PVE::JSONSchema::register_renderer('duration', \&render_duration); | |
59 | ||
60 | sub render_fraction_as_percentage { | |
61 | my ($fraction) = @_; | |
62 | ||
63 | return sprintf("%.2f%%", $fraction*100); | |
64 | } | |
65 | ||
66 | PVE::JSONSchema::register_renderer( | |
67 | 'fraction_as_percentage', \&render_fraction_as_percentage); | |
68 | ||
69 | sub render_bytes { | |
70 | my ($value) = @_; | |
71 | ||
72 | my @units = qw(B KiB MiB GiB TiB PiB); | |
73 | ||
74 | my $max_unit = 0; | |
75 | if ($value > 1023) { | |
76 | $max_unit = int(log($value)/log(1024)); | |
77 | $value /= 1024**($max_unit); | |
78 | } | |
79 | ||
80 | return sprintf "%.2f $units[$max_unit]", $value; | |
81 | } | |
82 | ||
83 | PVE::JSONSchema::register_renderer('bytes', \&render_bytes); | |
84 | ||
ba752c80 DM |
85 | sub render_yaml { |
86 | my ($value) = @_; | |
87 | ||
88 | my $data = CPAN::Meta::YAML::Dump($value); | |
89 | $data =~ s/^---[\n\s]//; # remove yaml marker | |
90 | ||
91 | return $data; | |
92 | } | |
93 | ||
94 | PVE::JSONSchema::register_renderer('yaml', \&render_yaml); | |
95 | ||
4ac85000 DM |
96 | sub query_terminal_options { |
97 | my ($options) = @_; | |
98 | ||
99 | $options //= {}; | |
100 | ||
101 | if (-t STDOUT) { | |
102 | ($options->{columns}) = PVE::PTY::tcgetsize(*STDOUT); | |
103 | } | |
104 | ||
105 | $options->{encoding} = I18N::Langinfo::langinfo(I18N::Langinfo::CODESET()); | |
106 | ||
107 | $options->{utf8} = 1 if $options->{encoding} eq 'UTF-8'; | |
108 | ||
109 | return $options; | |
110 | } | |
111 | ||
f53ad23a | 112 | sub data_to_text { |
1c096521 | 113 | my ($data, $propdef, $options) = @_; |
f53ad23a | 114 | |
3cd6f2f3 DM |
115 | return '' if !defined($data); |
116 | ||
352b7a14 DM |
117 | my $human_readable = $options->{'human-readable'} // 1; |
118 | ||
119 | if ($human_readable && defined($propdef)) { | |
84142f1d DM |
120 | if (my $type = $propdef->{type}) { |
121 | if ($type eq 'boolean') { | |
122 | return $data ? 1 : 0; | |
123 | } | |
124 | } | |
125 | if (!defined($data) && defined($propdef->{default})) { | |
126 | return "($propdef->{default})"; | |
127 | } | |
128 | if (defined(my $renderer = $propdef->{renderer})) { | |
129 | my $code = PVE::JSONSchema::get_renderer($renderer); | |
130 | die "internal error: unknown renderer '$renderer'" if !$code; | |
1c096521 | 131 | return $code->($data, $options); |
84142f1d DM |
132 | } |
133 | } | |
f53ad23a DM |
134 | |
135 | if (my $class = ref($data)) { | |
84142f1d | 136 | return to_json($data, { canonical => 1 }); |
f53ad23a DM |
137 | } else { |
138 | return "$data"; | |
139 | } | |
140 | } | |
141 | ||
142 | # prints a formatted table with a title row. | |
143 | # $data - the data to print (array of objects) | |
144 | # $returnprops -json schema property description | |
145 | # $props_to_print - ordered list of properties to print | |
0c22b00c | 146 | # $options |
2e2a4502 | 147 | # - sort_key: can be used to sort after a specific column, if it isn't set we sort |
f53ad23a | 148 | # after the leftmost column (with no undef value in $data) this can be |
0c22b00c | 149 | # turned off by passing 0 as sort_key |
352b7a14 DM |
150 | # - noborder: print without asciiart border |
151 | # - noheader: print without table header | |
0c22b00c DM |
152 | # - columns: limit output width (if > 0) |
153 | # - utf8: use utf8 characters for table delimiters | |
154 | ||
f53ad23a | 155 | sub print_text_table { |
0c22b00c DM |
156 | my ($data, $returnprops, $props_to_print, $options) = @_; |
157 | ||
158 | my $sort_key = $options->{sort_key}; | |
352b7a14 DM |
159 | my $border = !$options->{noborder}; |
160 | my $header = !$options->{noheader}; | |
0c22b00c DM |
161 | my $columns = $options->{columns}; |
162 | my $utf8 = $options->{utf8}; | |
43b104c4 | 163 | my $encoding = $options->{encoding} // 'UTF-8'; |
f53ad23a | 164 | |
2e2a4502 | 165 | $sort_key //= $props_to_print->[0]; |
41d554d9 | 166 | |
2e2a4502 | 167 | if (defined($sort_key) && $sort_key ne 0) { |
41d554d9 DM |
168 | my $type = $returnprops->{$sort_key}->{type} // 'string'; |
169 | if ($type eq 'integer' || $type eq 'number') { | |
170 | @$data = sort { $a->{$sort_key} <=> $b->{$sort_key} } @$data; | |
171 | } else { | |
172 | @$data = sort { $a->{$sort_key} cmp $b->{$sort_key} } @$data; | |
173 | } | |
f53ad23a DM |
174 | } |
175 | ||
176 | my $colopts = {}; | |
793ad69b | 177 | |
eb1c51c2 DM |
178 | my $borderstring_m = ''; |
179 | my $borderstring_b = ''; | |
180 | my $borderstring_t = ''; | |
f53ad23a DM |
181 | my $formatstring = ''; |
182 | ||
183 | my $column_count = scalar(@$props_to_print); | |
184 | ||
41d554d9 DM |
185 | my $tabledata = []; |
186 | ||
187 | foreach my $entry (@$data) { | |
188 | ||
189 | my $height = 1; | |
190 | my $rowdata = {}; | |
191 | ||
192 | for (my $i = 0; $i < $column_count; $i++) { | |
193 | my $prop = $props_to_print->[$i]; | |
194 | my $propinfo = $returnprops->{$prop} // {}; | |
195 | ||
1c096521 | 196 | my $text = data_to_text($entry->{$prop}, $propinfo, $options); |
41d554d9 DM |
197 | my $lines = [ split(/\n/, $text) ]; |
198 | my $linecount = scalar(@$lines); | |
199 | $height = $linecount if $linecount > $height; | |
200 | ||
201 | my $width = 0; | |
202 | foreach my $line (@$lines) { | |
203 | my $len = length($line); | |
204 | $width = $len if $len > $width; | |
205 | } | |
206 | ||
207 | $rowdata->{$prop} = { | |
208 | lines => $lines, | |
209 | width => $width, | |
210 | }; | |
211 | } | |
212 | ||
213 | push @$tabledata, { | |
214 | height => $height, | |
215 | rowdata => $rowdata, | |
216 | }; | |
217 | } | |
218 | ||
f53ad23a DM |
219 | for (my $i = 0; $i < $column_count; $i++) { |
220 | my $prop = $props_to_print->[$i]; | |
221 | my $propinfo = $returnprops->{$prop} // {}; | |
222 | ||
223 | my $title = $propinfo->{title} // $prop; | |
224 | my $cutoff = $propinfo->{print_width} // $propinfo->{maxLength}; | |
225 | ||
226 | # calculate maximal print width and cutoff | |
227 | my $titlelen = length($title); | |
228 | ||
229 | my $longest = $titlelen; | |
41d554d9 DM |
230 | foreach my $coldata (@$tabledata) { |
231 | my $rowdata = $coldata->{rowdata}->{$prop}; | |
232 | $longest = $rowdata->{width} if $rowdata->{width} > $longest; | |
f53ad23a DM |
233 | } |
234 | $cutoff = $longest if !defined($cutoff) || $cutoff > $longest; | |
f53ad23a DM |
235 | |
236 | $colopts->{$prop} = { | |
237 | title => $title, | |
f53ad23a DM |
238 | cutoff => $cutoff, |
239 | }; | |
240 | ||
793ad69b | 241 | if ($border) { |
eb1c51c2 DM |
242 | if ($i == 0 && ($column_count == 1)) { |
243 | if ($utf8) { | |
41d554d9 DM |
244 | $formatstring .= "│ %-${cutoff}s │"; |
245 | $borderstring_t .= "┌─" . ('─' x $cutoff) . "─┐"; | |
246 | $borderstring_m .= "├─" . ('─' x $cutoff) . "─┤"; | |
247 | $borderstring_b .= "└─" . ('─' x $cutoff) . "─┘"; | |
eb1c51c2 | 248 | } else { |
41d554d9 DM |
249 | $formatstring .= "| %-${cutoff}s |"; |
250 | $borderstring_m .= "+-" . ('-' x $cutoff) . "-+"; | |
eb1c51c2 DM |
251 | } |
252 | } elsif ($i == 0) { | |
253 | if ($utf8) { | |
254 | $formatstring .= "│ %-${cutoff}s "; | |
255 | $borderstring_t .= "┌─" . ('─' x $cutoff) . '─'; | |
256 | $borderstring_m .= "├─" . ('─' x $cutoff) . '─'; | |
257 | $borderstring_b .= "└─" . ('─' x $cutoff) . '─'; | |
258 | } else { | |
259 | $formatstring .= "| %-${cutoff}s "; | |
260 | $borderstring_m .= "+-" . ('-' x $cutoff) . '-'; | |
261 | } | |
262 | } elsif ($i == ($column_count - 1)) { | |
263 | if ($utf8) { | |
41d554d9 DM |
264 | $formatstring .= "│ %-${cutoff}s │"; |
265 | $borderstring_t .= "┬─" . ('─' x $cutoff) . "─┐"; | |
266 | $borderstring_m .= "┼─" . ('─' x $cutoff) . "─┤"; | |
267 | $borderstring_b .= "┴─" . ('─' x $cutoff) . "─┘"; | |
eb1c51c2 | 268 | } else { |
41d554d9 DM |
269 | $formatstring .= "| %-${cutoff}s |"; |
270 | $borderstring_m .= "+-" . ('-' x $cutoff) . "-+"; | |
eb1c51c2 | 271 | } |
793ad69b | 272 | } else { |
eb1c51c2 DM |
273 | if ($utf8) { |
274 | $formatstring .= "│ %-${cutoff}s "; | |
275 | $borderstring_t .= "┬─" . ('─' x $cutoff) . '─'; | |
276 | $borderstring_m .= "┼─" . ('─' x $cutoff) . '─'; | |
277 | $borderstring_b .= "┴─" . ('─' x $cutoff) . '─'; | |
278 | } else { | |
279 | $formatstring .= "| %-${cutoff}s "; | |
280 | $borderstring_m .= "+-" . ('-' x $cutoff) . '-'; | |
281 | } | |
793ad69b DM |
282 | } |
283 | } else { | |
284 | # skip alignment and cutoff on last column | |
41d554d9 | 285 | $formatstring .= ($i == ($column_count - 1)) ? "%s" : "%-${cutoff}s "; |
f53ad23a DM |
286 | } |
287 | } | |
288 | ||
eb1c51c2 DM |
289 | $borderstring_t = $borderstring_m if !length($borderstring_t); |
290 | $borderstring_b = $borderstring_m if !length($borderstring_b); | |
291 | ||
41d554d9 DM |
292 | my $writeln = sub { |
293 | my ($text) = @_; | |
294 | ||
295 | if ($columns) { | |
296 | print encode($encoding, substr($text, 0, $columns) . "\n"); | |
297 | } else { | |
298 | print encode($encoding, $text) . "\n"; | |
299 | } | |
300 | }; | |
301 | ||
302 | $writeln->($borderstring_t) if $border; | |
793ad69b | 303 | |
352b7a14 DM |
304 | if ($header) { |
305 | my $text = sprintf $formatstring, map { $colopts->{$_}->{title} } @$props_to_print; | |
306 | $writeln->($text); | |
307 | } | |
308 | ||
309 | for (my $i = 0; $i < scalar(@$tabledata); $i++) { | |
310 | my $coldata = $tabledata->[$i]; | |
311 | ||
312 | $writeln->($borderstring_m) if $border && ($i != 0 || $header); | |
41d554d9 DM |
313 | |
314 | for (my $i = 0; $i < $coldata->{height}; $i++) { | |
315 | ||
352b7a14 | 316 | my $text = sprintf $formatstring, map { |
41d554d9 DM |
317 | substr($coldata->{rowdata}->{$_}->{lines}->[$i] // '', 0, $colopts->{$_}->{cutoff}); |
318 | } @$props_to_print; | |
319 | ||
320 | $writeln->($text); | |
321 | } | |
f53ad23a | 322 | } |
41d554d9 DM |
323 | |
324 | $writeln->($borderstring_b) if $border; | |
f53ad23a DM |
325 | } |
326 | ||
c5adc5f9 DM |
327 | sub extract_properties_to_print { |
328 | my ($propdef) = @_; | |
329 | ||
330 | my $required = []; | |
331 | my $optional = []; | |
332 | ||
333 | foreach my $key (keys %$propdef) { | |
334 | my $prop = $propdef->{$key}; | |
335 | if ($prop->{optional}) { | |
336 | push @$optional, $key; | |
337 | } else { | |
338 | push @$required, $key; | |
339 | } | |
340 | } | |
341 | ||
342 | return [ sort(@$required), sort(@$optional) ]; | |
343 | } | |
344 | ||
f53ad23a DM |
345 | # prints the result of an API GET call returning an array as a table. |
346 | # takes formatting information from the results property of the call | |
347 | # if $props_to_print is provided, prints only those columns. otherwise | |
348 | # takes all fields of the results property, with a fallback | |
349 | # to all fields occuring in items of $data. | |
350 | sub print_api_list { | |
0c22b00c | 351 | my ($data, $result_schema, $props_to_print, $options) = @_; |
f53ad23a DM |
352 | |
353 | die "can only print object lists\n" | |
354 | if !($result_schema->{type} eq 'array' && $result_schema->{items}->{type} eq 'object'); | |
355 | ||
356 | my $returnprops = $result_schema->{items}->{properties}; | |
357 | ||
c5adc5f9 DM |
358 | $props_to_print = extract_properties_to_print($returnprops) |
359 | if !defined($props_to_print); | |
360 | ||
361 | if (!scalar(@$props_to_print)) { | |
362 | my $all_props = {}; | |
363 | foreach my $obj (@$data) { | |
364 | foreach my $key (keys %$obj) { | |
365 | $all_props->{$key} = 1; | |
f53ad23a | 366 | } |
f53ad23a | 367 | } |
c5adc5f9 | 368 | $props_to_print = [ sort keys %{$all_props} ]; |
f53ad23a DM |
369 | } |
370 | ||
c5adc5f9 DM |
371 | die "unable to detect list properties\n" if !scalar(@$props_to_print); |
372 | ||
0c22b00c | 373 | print_text_table($data, $returnprops, $props_to_print, $options); |
f53ad23a DM |
374 | } |
375 | ||
376 | sub print_api_result { | |
f0bcf4d4 | 377 | my ($data, $result_schema, $props_to_print, $options) = @_; |
0c22b00c | 378 | |
352b7a14 DM |
379 | return if $options->{quiet}; |
380 | ||
4ac85000 DM |
381 | if (!defined($options)) { |
382 | $options = query_terminal_options({}); | |
383 | } else { | |
384 | $options = { %$options }; # copy | |
385 | } | |
f53ad23a | 386 | |
4cbcd138 | 387 | my $format = $options->{'output-format'} // 'text'; |
f0bcf4d4 | 388 | |
f53ad23a DM |
389 | return if $result_schema->{type} eq 'null'; |
390 | ||
391 | if ($format eq 'json') { | |
cd6591d3 DM |
392 | # Note: we always use utf8 encoding for json format |
393 | print to_json($data, {utf8 => 1, allow_nonref => 1, canonical => 1 }) . "\n"; | |
394 | } elsif ($format eq 'json-pretty') { | |
43b104c4 | 395 | # Note: we always use utf8 encoding for json format |
f53ad23a | 396 | print to_json($data, {utf8 => 1, allow_nonref => 1, canonical => 1, pretty => 1 }); |
cd6591d3 | 397 | } elsif ($format eq 'text') { |
43b104c4 | 398 | my $encoding = $options->{encoding} // 'UTF-8'; |
f53ad23a DM |
399 | my $type = $result_schema->{type}; |
400 | if ($type eq 'object') { | |
c5adc5f9 DM |
401 | $props_to_print = extract_properties_to_print($result_schema->{properties}) |
402 | if !defined($props_to_print); | |
403 | $props_to_print = [ sort keys %$data ] if !scalar(@$props_to_print); | |
2a174d2a | 404 | my $kvstore = []; |
f53ad23a | 405 | foreach my $key (@$props_to_print) { |
a05db8b5 | 406 | next if !defined($data->{$key}); |
1c096521 | 407 | push @$kvstore, { key => $key, value => data_to_text($data->{$key}, $result_schema->{properties}->{$key}, $options) }; |
f53ad23a | 408 | } |
2a174d2a | 409 | my $schema = { type => 'array', items => { type => 'object' }}; |
0c22b00c | 410 | print_api_list($kvstore, $schema, ['key', 'value'], $options); |
f53ad23a DM |
411 | } elsif ($type eq 'array') { |
412 | return if !scalar(@$data); | |
413 | my $item_type = $result_schema->{items}->{type}; | |
414 | if ($item_type eq 'object') { | |
0c22b00c | 415 | print_api_list($data, $result_schema, $props_to_print, $options); |
f53ad23a | 416 | } else { |
c850b998 DM |
417 | my $kvstore = []; |
418 | foreach my $value (@$data) { | |
419 | push @$kvstore, { value => $value }; | |
f53ad23a | 420 | } |
c850b998 | 421 | my $schema = { type => 'array', items => { type => 'object', properties => { value => $result_schema->{items} }}}; |
352b7a14 | 422 | $options->{noheader} = 1; |
c850b998 | 423 | print_api_list($kvstore, $schema, ['value'], $options); |
f53ad23a DM |
424 | } |
425 | } else { | |
43b104c4 | 426 | print encode($encoding, "$data\n"); |
f53ad23a DM |
427 | } |
428 | } else { | |
429 | die "internal error: unknown output format"; # should not happen | |
430 | } | |
431 | } | |
432 | ||
433 | 1; |