]>
Commit | Line | Data |
---|---|---|
1 | package PVE::CLIFormatter; | |
2 | ||
3 | use strict; | |
4 | use warnings; | |
5 | use I18N::Langinfo; | |
6 | use POSIX qw(strftime); | |
7 | use CPAN::Meta::YAML; # comes with perl-modules | |
8 | ||
9 | use PVE::JSONSchema; | |
10 | use PVE::PTY; | |
11 | use JSON; | |
12 | use utf8; | |
13 | use Encode; | |
14 | ||
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 | ||
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 | ||
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 | ||
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 | ||
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 | ||
112 | sub data_to_text { | |
113 | my ($data, $propdef, $options, $terminal_opts) = @_; | |
114 | ||
115 | return '' if !defined($data); | |
116 | ||
117 | $terminal_opts //= {}; | |
118 | ||
119 | my $human_readable = $options->{'human-readable'} // 1; | |
120 | ||
121 | if ($human_readable && defined($propdef)) { | |
122 | if (my $type = $propdef->{type}) { | |
123 | if ($type eq 'boolean') { | |
124 | return $data ? 1 : 0; | |
125 | } | |
126 | } | |
127 | if (!defined($data) && defined($propdef->{default})) { | |
128 | return "($propdef->{default})"; | |
129 | } | |
130 | if (defined(my $renderer = $propdef->{renderer})) { | |
131 | my $code = PVE::JSONSchema::get_renderer($renderer); | |
132 | die "internal error: unknown renderer '$renderer'" if !$code; | |
133 | return $code->($data, $options, $terminal_opts); | |
134 | } | |
135 | } | |
136 | ||
137 | if (my $class = ref($data)) { | |
138 | return to_json($data, { canonical => 1 }); | |
139 | } else { | |
140 | return "$data"; | |
141 | } | |
142 | } | |
143 | ||
144 | # prints a formatted table with a title row. | |
145 | # $data - the data to print (array of objects) | |
146 | # $returnprops -json schema property description | |
147 | # $props_to_print - ordered list of properties to print | |
148 | # $options | |
149 | # - sort_key: can be used to sort after a specific column, if it isn't set we sort | |
150 | # after the leftmost column (with no undef value in $data) this can be | |
151 | # turned off by passing 0 as sort_key | |
152 | # - noborder: print without asciiart border | |
153 | # - noheader: print without table header | |
154 | # - columns: limit output width (if > 0) | |
155 | # - utf8: use utf8 characters for table delimiters | |
156 | ||
157 | sub print_text_table { | |
158 | my ($data, $returnprops, $props_to_print, $options, $terminal_opts) = @_; | |
159 | ||
160 | $terminal_opts //= query_terminal_options({}); | |
161 | ||
162 | my $sort_key = $options->{sort_key}; | |
163 | my $border = !$options->{noborder}; | |
164 | my $header = !$options->{noheader}; | |
165 | ||
166 | my $columns = $terminal_opts->{columns}; | |
167 | my $utf8 = $terminal_opts->{utf8}; | |
168 | my $encoding = $terminal_opts->{encoding} // 'UTF-8'; | |
169 | ||
170 | $sort_key //= $props_to_print->[0]; | |
171 | ||
172 | if (defined($sort_key) && $sort_key ne 0) { | |
173 | my $type = $returnprops->{$sort_key}->{type} // 'string'; | |
174 | if ($type eq 'integer' || $type eq 'number') { | |
175 | @$data = sort { $a->{$sort_key} <=> $b->{$sort_key} } @$data; | |
176 | } else { | |
177 | @$data = sort { $a->{$sort_key} cmp $b->{$sort_key} } @$data; | |
178 | } | |
179 | } | |
180 | ||
181 | my $colopts = {}; | |
182 | ||
183 | my $borderstring_m = ''; | |
184 | my $borderstring_b = ''; | |
185 | my $borderstring_t = ''; | |
186 | my $formatstring = ''; | |
187 | ||
188 | my $column_count = scalar(@$props_to_print); | |
189 | ||
190 | my $tabledata = []; | |
191 | ||
192 | foreach my $entry (@$data) { | |
193 | ||
194 | my $height = 1; | |
195 | my $rowdata = {}; | |
196 | ||
197 | for (my $i = 0; $i < $column_count; $i++) { | |
198 | my $prop = $props_to_print->[$i]; | |
199 | my $propinfo = $returnprops->{$prop} // {}; | |
200 | ||
201 | my $text = data_to_text($entry->{$prop}, $propinfo, $options, $terminal_opts); | |
202 | my $lines = [ split(/\n/, $text) ]; | |
203 | my $linecount = scalar(@$lines); | |
204 | $height = $linecount if $linecount > $height; | |
205 | ||
206 | my $width = 0; | |
207 | foreach my $line (@$lines) { | |
208 | my $len = length($line); | |
209 | $width = $len if $len > $width; | |
210 | } | |
211 | ||
212 | $rowdata->{$prop} = { | |
213 | lines => $lines, | |
214 | width => $width, | |
215 | }; | |
216 | } | |
217 | ||
218 | push @$tabledata, { | |
219 | height => $height, | |
220 | rowdata => $rowdata, | |
221 | }; | |
222 | } | |
223 | ||
224 | for (my $i = 0; $i < $column_count; $i++) { | |
225 | my $prop = $props_to_print->[$i]; | |
226 | my $propinfo = $returnprops->{$prop} // {}; | |
227 | ||
228 | my $title = $propinfo->{title} // $prop; | |
229 | my $cutoff = $propinfo->{print_width} // $propinfo->{maxLength}; | |
230 | ||
231 | # calculate maximal print width and cutoff | |
232 | my $titlelen = length($title); | |
233 | ||
234 | my $longest = $titlelen; | |
235 | foreach my $coldata (@$tabledata) { | |
236 | my $rowdata = $coldata->{rowdata}->{$prop}; | |
237 | $longest = $rowdata->{width} if $rowdata->{width} > $longest; | |
238 | } | |
239 | $cutoff = $longest if !defined($cutoff) || $cutoff > $longest; | |
240 | ||
241 | $colopts->{$prop} = { | |
242 | title => $title, | |
243 | cutoff => $cutoff, | |
244 | }; | |
245 | ||
246 | if ($border) { | |
247 | if ($i == 0 && ($column_count == 1)) { | |
248 | if ($utf8) { | |
249 | $formatstring .= "│ %-${cutoff}s │"; | |
250 | $borderstring_t .= "┌─" . ('─' x $cutoff) . "─┐"; | |
251 | $borderstring_m .= "├─" . ('─' x $cutoff) . "─┤"; | |
252 | $borderstring_b .= "└─" . ('─' x $cutoff) . "─┘"; | |
253 | } else { | |
254 | $formatstring .= "| %-${cutoff}s |"; | |
255 | $borderstring_m .= "+-" . ('-' x $cutoff) . "-+"; | |
256 | } | |
257 | } elsif ($i == 0) { | |
258 | if ($utf8) { | |
259 | $formatstring .= "│ %-${cutoff}s "; | |
260 | $borderstring_t .= "┌─" . ('─' x $cutoff) . '─'; | |
261 | $borderstring_m .= "├─" . ('─' x $cutoff) . '─'; | |
262 | $borderstring_b .= "└─" . ('─' x $cutoff) . '─'; | |
263 | } else { | |
264 | $formatstring .= "| %-${cutoff}s "; | |
265 | $borderstring_m .= "+-" . ('-' x $cutoff) . '-'; | |
266 | } | |
267 | } elsif ($i == ($column_count - 1)) { | |
268 | if ($utf8) { | |
269 | $formatstring .= "│ %-${cutoff}s │"; | |
270 | $borderstring_t .= "┬─" . ('─' x $cutoff) . "─┐"; | |
271 | $borderstring_m .= "┼─" . ('─' x $cutoff) . "─┤"; | |
272 | $borderstring_b .= "┴─" . ('─' x $cutoff) . "─┘"; | |
273 | } else { | |
274 | $formatstring .= "| %-${cutoff}s |"; | |
275 | $borderstring_m .= "+-" . ('-' x $cutoff) . "-+"; | |
276 | } | |
277 | } else { | |
278 | if ($utf8) { | |
279 | $formatstring .= "│ %-${cutoff}s "; | |
280 | $borderstring_t .= "┬─" . ('─' x $cutoff) . '─'; | |
281 | $borderstring_m .= "┼─" . ('─' x $cutoff) . '─'; | |
282 | $borderstring_b .= "┴─" . ('─' x $cutoff) . '─'; | |
283 | } else { | |
284 | $formatstring .= "| %-${cutoff}s "; | |
285 | $borderstring_m .= "+-" . ('-' x $cutoff) . '-'; | |
286 | } | |
287 | } | |
288 | } else { | |
289 | # skip alignment and cutoff on last column | |
290 | $formatstring .= ($i == ($column_count - 1)) ? "%s" : "%-${cutoff}s "; | |
291 | } | |
292 | } | |
293 | ||
294 | $borderstring_t = $borderstring_m if !length($borderstring_t); | |
295 | $borderstring_b = $borderstring_m if !length($borderstring_b); | |
296 | ||
297 | my $writeln = sub { | |
298 | my ($text) = @_; | |
299 | ||
300 | if ($columns) { | |
301 | print encode($encoding, substr($text, 0, $columns) . "\n"); | |
302 | } else { | |
303 | print encode($encoding, $text) . "\n"; | |
304 | } | |
305 | }; | |
306 | ||
307 | $writeln->($borderstring_t) if $border; | |
308 | ||
309 | if ($header) { | |
310 | my $text = sprintf $formatstring, map { $colopts->{$_}->{title} } @$props_to_print; | |
311 | $writeln->($text); | |
312 | } | |
313 | ||
314 | for (my $i = 0; $i < scalar(@$tabledata); $i++) { | |
315 | my $coldata = $tabledata->[$i]; | |
316 | ||
317 | $writeln->($borderstring_m) if $border && ($i != 0 || $header); | |
318 | ||
319 | for (my $i = 0; $i < $coldata->{height}; $i++) { | |
320 | ||
321 | my $text = sprintf $formatstring, map { | |
322 | substr($coldata->{rowdata}->{$_}->{lines}->[$i] // '', 0, $colopts->{$_}->{cutoff}); | |
323 | } @$props_to_print; | |
324 | ||
325 | $writeln->($text); | |
326 | } | |
327 | } | |
328 | ||
329 | $writeln->($borderstring_b) if $border; | |
330 | } | |
331 | ||
332 | sub extract_properties_to_print { | |
333 | my ($propdef) = @_; | |
334 | ||
335 | my $required = []; | |
336 | my $optional = []; | |
337 | ||
338 | foreach my $key (keys %$propdef) { | |
339 | my $prop = $propdef->{$key}; | |
340 | if ($prop->{optional}) { | |
341 | push @$optional, $key; | |
342 | } else { | |
343 | push @$required, $key; | |
344 | } | |
345 | } | |
346 | ||
347 | return [ sort(@$required), sort(@$optional) ]; | |
348 | } | |
349 | ||
350 | # prints the result of an API GET call returning an array as a table. | |
351 | # takes formatting information from the results property of the call | |
352 | # if $props_to_print is provided, prints only those columns. otherwise | |
353 | # takes all fields of the results property, with a fallback | |
354 | # to all fields occuring in items of $data. | |
355 | sub print_api_list { | |
356 | my ($data, $result_schema, $props_to_print, $options, $terminal_opts) = @_; | |
357 | ||
358 | die "can only print object lists\n" | |
359 | if !($result_schema->{type} eq 'array' && $result_schema->{items}->{type} eq 'object'); | |
360 | ||
361 | my $returnprops = $result_schema->{items}->{properties}; | |
362 | ||
363 | $props_to_print = extract_properties_to_print($returnprops) | |
364 | if !defined($props_to_print); | |
365 | ||
366 | if (!scalar(@$props_to_print)) { | |
367 | my $all_props = {}; | |
368 | foreach my $obj (@$data) { | |
369 | foreach my $key (keys %$obj) { | |
370 | $all_props->{$key} = 1; | |
371 | } | |
372 | } | |
373 | $props_to_print = [ sort keys %{$all_props} ]; | |
374 | } | |
375 | ||
376 | die "unable to detect list properties\n" if !scalar(@$props_to_print); | |
377 | ||
378 | print_text_table($data, $returnprops, $props_to_print, $options, $terminal_opts); | |
379 | } | |
380 | ||
381 | sub print_api_result { | |
382 | my ($data, $result_schema, $props_to_print, $options, $terminal_opts) = @_; | |
383 | ||
384 | return if $options->{quiet}; | |
385 | ||
386 | $terminal_opts //= query_terminal_options({}); | |
387 | ||
388 | my $format = $options->{'output-format'} // 'text'; | |
389 | ||
390 | return if $result_schema->{type} eq 'null'; | |
391 | ||
392 | if ($format eq 'json') { | |
393 | # Note: we always use utf8 encoding for json format | |
394 | print to_json($data, {utf8 => 1, allow_nonref => 1, canonical => 1 }) . "\n"; | |
395 | } elsif ($format eq 'json-pretty') { | |
396 | # Note: we always use utf8 encoding for json format | |
397 | print to_json($data, {utf8 => 1, allow_nonref => 1, canonical => 1, pretty => 1 }); | |
398 | } elsif ($format eq 'text') { | |
399 | my $encoding = $options->{encoding} // 'UTF-8'; | |
400 | my $type = $result_schema->{type}; | |
401 | if ($type eq 'object') { | |
402 | $props_to_print = extract_properties_to_print($result_schema->{properties}) | |
403 | if !defined($props_to_print); | |
404 | $props_to_print = [ sort keys %$data ] if !scalar(@$props_to_print); | |
405 | my $kvstore = []; | |
406 | foreach my $key (@$props_to_print) { | |
407 | next if !defined($data->{$key}); | |
408 | push @$kvstore, { key => $key, value => data_to_text($data->{$key}, $result_schema->{properties}->{$key}, $options, $terminal_opts) }; | |
409 | } | |
410 | my $schema = { type => 'array', items => { type => 'object' }}; | |
411 | print_api_list($kvstore, $schema, ['key', 'value'], $options, $terminal_opts); | |
412 | } elsif ($type eq 'array') { | |
413 | return if !scalar(@$data); | |
414 | my $item_type = $result_schema->{items}->{type}; | |
415 | if ($item_type eq 'object') { | |
416 | print_api_list($data, $result_schema, $props_to_print, $options, $terminal_opts); | |
417 | } else { | |
418 | my $kvstore = []; | |
419 | foreach my $value (@$data) { | |
420 | push @$kvstore, { value => $value }; | |
421 | } | |
422 | my $schema = { type => 'array', items => { type => 'object', properties => { value => $result_schema->{items} }}}; | |
423 | print_api_list($kvstore, $schema, ['value'], { %$options, noheader => 1 }, $terminal_opts); | |
424 | } | |
425 | } else { | |
426 | print encode($encoding, "$data\n"); | |
427 | } | |
428 | } else { | |
429 | die "internal error: unknown output format"; # should not happen | |
430 | } | |
431 | } | |
432 | ||
433 | 1; |