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