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