]> git.proxmox.com Git - pve-common.git/blob - src/PVE/CLIFormatter.pm
7a92f7a286dbd630a34fe392e37d9cade211fe37
[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 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 if (!defined($sort_key) || $sort_key eq 0) {
154 $sort_key = $props_to_print->[0];
155 }
156
157 if (defined($sort_key)) {
158 my $type = $returnprops->{$sort_key}->{type} // 'string';
159 if ($type eq 'integer' || $type eq 'number') {
160 @$data = sort { $a->{$sort_key} <=> $b->{$sort_key} } @$data;
161 } else {
162 @$data = sort { $a->{$sort_key} cmp $b->{$sort_key} } @$data;
163 }
164 }
165
166 my $colopts = {};
167
168 my $borderstring_m = '';
169 my $borderstring_b = '';
170 my $borderstring_t = '';
171 my $formatstring = '';
172
173 my $column_count = scalar(@$props_to_print);
174
175 my $tabledata = [];
176
177 foreach my $entry (@$data) {
178
179 my $height = 1;
180 my $rowdata = {};
181
182 for (my $i = 0; $i < $column_count; $i++) {
183 my $prop = $props_to_print->[$i];
184 my $propinfo = $returnprops->{$prop} // {};
185
186 my $text = data_to_text($entry->{$prop}, $propinfo, $options);
187 my $lines = [ split(/\n/, $text) ];
188 my $linecount = scalar(@$lines);
189 $height = $linecount if $linecount > $height;
190
191 my $width = 0;
192 foreach my $line (@$lines) {
193 my $len = length($line);
194 $width = $len if $len > $width;
195 }
196
197 $rowdata->{$prop} = {
198 lines => $lines,
199 width => $width,
200 };
201 }
202
203 push @$tabledata, {
204 height => $height,
205 rowdata => $rowdata,
206 };
207 }
208
209 for (my $i = 0; $i < $column_count; $i++) {
210 my $prop = $props_to_print->[$i];
211 my $propinfo = $returnprops->{$prop} // {};
212
213 my $title = $propinfo->{title} // $prop;
214 my $cutoff = $propinfo->{print_width} // $propinfo->{maxLength};
215
216 # calculate maximal print width and cutoff
217 my $titlelen = length($title);
218
219 my $longest = $titlelen;
220 foreach my $coldata (@$tabledata) {
221 my $rowdata = $coldata->{rowdata}->{$prop};
222 $longest = $rowdata->{width} if $rowdata->{width} > $longest;
223 }
224 $cutoff = $longest if !defined($cutoff) || $cutoff > $longest;
225
226 $colopts->{$prop} = {
227 title => $title,
228 cutoff => $cutoff,
229 };
230
231 if ($border) {
232 if ($i == 0 && ($column_count == 1)) {
233 if ($utf8) {
234 $formatstring .= "│ %-${cutoff}s │";
235 $borderstring_t .= "┌─" . ('─' x $cutoff) . "─┐";
236 $borderstring_m .= "├─" . ('─' x $cutoff) . "─┤";
237 $borderstring_b .= "└─" . ('─' x $cutoff) . "─┘";
238 } else {
239 $formatstring .= "| %-${cutoff}s |";
240 $borderstring_m .= "+-" . ('-' x $cutoff) . "-+";
241 }
242 } elsif ($i == 0) {
243 if ($utf8) {
244 $formatstring .= "│ %-${cutoff}s ";
245 $borderstring_t .= "┌─" . ('─' x $cutoff) . '─';
246 $borderstring_m .= "├─" . ('─' x $cutoff) . '─';
247 $borderstring_b .= "└─" . ('─' x $cutoff) . '─';
248 } else {
249 $formatstring .= "| %-${cutoff}s ";
250 $borderstring_m .= "+-" . ('-' x $cutoff) . '-';
251 }
252 } elsif ($i == ($column_count - 1)) {
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 } else {
263 if ($utf8) {
264 $formatstring .= "│ %-${cutoff}s ";
265 $borderstring_t .= "┬─" . ('─' x $cutoff) . '─';
266 $borderstring_m .= "┼─" . ('─' x $cutoff) . '─';
267 $borderstring_b .= "┴─" . ('─' x $cutoff) . '─';
268 } else {
269 $formatstring .= "| %-${cutoff}s ";
270 $borderstring_m .= "+-" . ('-' x $cutoff) . '-';
271 }
272 }
273 } else {
274 # skip alignment and cutoff on last column
275 $formatstring .= ($i == ($column_count - 1)) ? "%s" : "%-${cutoff}s ";
276 }
277 }
278
279 $borderstring_t = $borderstring_m if !length($borderstring_t);
280 $borderstring_b = $borderstring_m if !length($borderstring_b);
281
282 my $writeln = sub {
283 my ($text) = @_;
284
285 if ($columns) {
286 print encode($encoding, substr($text, 0, $columns) . "\n");
287 } else {
288 print encode($encoding, $text) . "\n";
289 }
290 };
291
292 $writeln->($borderstring_t) if $border;
293
294 if ($header) {
295 my $text = sprintf $formatstring, map { $colopts->{$_}->{title} } @$props_to_print;
296 $writeln->($text);
297 }
298
299 for (my $i = 0; $i < scalar(@$tabledata); $i++) {
300 my $coldata = $tabledata->[$i];
301
302 $writeln->($borderstring_m) if $border && ($i != 0 || $header);
303
304 for (my $i = 0; $i < $coldata->{height}; $i++) {
305
306 my $text = sprintf $formatstring, map {
307 substr($coldata->{rowdata}->{$_}->{lines}->[$i] // '', 0, $colopts->{$_}->{cutoff});
308 } @$props_to_print;
309
310 $writeln->($text);
311 }
312 }
313
314 $writeln->($borderstring_b) if $border;
315 }
316
317 sub extract_properties_to_print {
318 my ($propdef) = @_;
319
320 my $required = [];
321 my $optional = [];
322
323 foreach my $key (keys %$propdef) {
324 my $prop = $propdef->{$key};
325 if ($prop->{optional}) {
326 push @$optional, $key;
327 } else {
328 push @$required, $key;
329 }
330 }
331
332 return [ sort(@$required), sort(@$optional) ];
333 }
334
335 # prints the result of an API GET call returning an array as a table.
336 # takes formatting information from the results property of the call
337 # if $props_to_print is provided, prints only those columns. otherwise
338 # takes all fields of the results property, with a fallback
339 # to all fields occuring in items of $data.
340 sub print_api_list {
341 my ($data, $result_schema, $props_to_print, $options) = @_;
342
343 die "can only print object lists\n"
344 if !($result_schema->{type} eq 'array' && $result_schema->{items}->{type} eq 'object');
345
346 my $returnprops = $result_schema->{items}->{properties};
347
348 $props_to_print = extract_properties_to_print($returnprops)
349 if !defined($props_to_print);
350
351 if (!scalar(@$props_to_print)) {
352 my $all_props = {};
353 foreach my $obj (@$data) {
354 foreach my $key (keys %$obj) {
355 $all_props->{$key} = 1;
356 }
357 }
358 $props_to_print = [ sort keys %{$all_props} ];
359 }
360
361 die "unable to detect list properties\n" if !scalar(@$props_to_print);
362
363 print_text_table($data, $returnprops, $props_to_print, $options);
364 }
365
366 sub print_api_result {
367 my ($data, $result_schema, $props_to_print, $options) = @_;
368
369 return if $options->{quiet};
370
371 if (!defined($options)) {
372 $options = query_terminal_options({});
373 } else {
374 $options = { %$options }; # copy
375 }
376
377 my $format = $options->{format} // 'text';
378
379 return if $result_schema->{type} eq 'null';
380
381 if ($format eq 'json') {
382 # Note: we always use utf8 encoding for json format
383 print to_json($data, {utf8 => 1, allow_nonref => 1, canonical => 1 }) . "\n";
384 } elsif ($format eq 'json-pretty') {
385 # Note: we always use utf8 encoding for json format
386 print to_json($data, {utf8 => 1, allow_nonref => 1, canonical => 1, pretty => 1 });
387 } elsif ($format eq 'text') {
388 my $encoding = $options->{encoding} // 'UTF-8';
389 my $type = $result_schema->{type};
390 if ($type eq 'object') {
391 $props_to_print = extract_properties_to_print($result_schema->{properties})
392 if !defined($props_to_print);
393 $props_to_print = [ sort keys %$data ] if !scalar(@$props_to_print);
394 my $kvstore = [];
395 foreach my $key (@$props_to_print) {
396 next if !defined($data->{$key});
397 push @$kvstore, { key => $key, value => data_to_text($data->{$key}, $result_schema->{properties}->{$key}, $options) };
398 }
399 my $schema = { type => 'array', items => { type => 'object' }};
400 print_api_list($kvstore, $schema, ['key', 'value'], $options);
401 } elsif ($type eq 'array') {
402 return if !scalar(@$data);
403 my $item_type = $result_schema->{items}->{type};
404 if ($item_type eq 'object') {
405 print_api_list($data, $result_schema, $props_to_print, $options);
406 } else {
407 my $kvstore = [];
408 foreach my $value (@$data) {
409 push @$kvstore, { value => $value };
410 }
411 my $schema = { type => 'array', items => { type => 'object', properties => { value => $result_schema->{items} }}};
412 $options->{noheader} = 1;
413 print_api_list($kvstore, $schema, ['value'], $options);
414 }
415 } else {
416 print encode($encoding, "$data\n");
417 }
418 } else {
419 die "internal error: unknown output format"; # should not happen
420 }
421 }
422
423 1;