]> git.proxmox.com Git - pve-common.git/blame - src/PVE/CLIFormatter.pm
PVE::CLIFormatter::data_to_text - add parameter $options
[pve-common.git] / src / PVE / CLIFormatter.pm
CommitLineData
f53ad23a
DM
1package PVE::CLIFormatter;
2
3use strict;
4use warnings;
4ac85000 5use I18N::Langinfo;
5e287f60 6use POSIX qw(strftime);
4ac85000 7
84142f1d 8use PVE::JSONSchema;
4ac85000 9use PVE::PTY;
f53ad23a 10use JSON;
eb1c51c2
DM
11use utf8;
12use Encode;
f53ad23a 13
5e287f60
DM
14sub render_timestamp {
15 my ($epoch) = @_;
16
17 # ISO 8601 date format
18 return strftime("%F %H:%M:%S", localtime($epoch));
19}
20
21PVE::JSONSchema::register_renderer('timestamp', \&render_timestamp);
22
f495c868
DM
23sub 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
48PVE::JSONSchema::register_renderer('duration', \&render_duration);
49
50sub render_fraction_as_percentage {
51 my ($fraction) = @_;
52
53 return sprintf("%.2f%%", $fraction*100);
54}
55
56PVE::JSONSchema::register_renderer(
57 'fraction_as_percentage', \&render_fraction_as_percentage);
58
59sub 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
73PVE::JSONSchema::register_renderer('bytes', \&render_bytes);
74
4ac85000
DM
75sub 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
f53ad23a 91sub data_to_text {
1c096521 92 my ($data, $propdef, $options) = @_;
f53ad23a 93
3cd6f2f3
DM
94 return '' if !defined($data);
95
84142f1d
DM
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;
1c096521 108 return $code->($data, $options);
84142f1d
DM
109 }
110 }
f53ad23a
DM
111
112 if (my $class = ref($data)) {
84142f1d 113 return to_json($data, { canonical => 1 });
f53ad23a
DM
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
0c22b00c
DM
123# $options
124# - sort_key: can be used to sort after a column, if it isn't set we sort
f53ad23a 125# after the leftmost column (with no undef value in $data) this can be
0c22b00c
DM
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
f53ad23a 131sub print_text_table {
0c22b00c
DM
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};
43b104c4 138 my $encoding = $options->{encoding} // 'UTF-8';
f53ad23a 139
ef3c37dd 140 if (!defined($sort_key) || $sort_key eq 0) {
41d554d9
DM
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 }
f53ad23a
DM
151 }
152
153 my $colopts = {};
793ad69b 154
eb1c51c2
DM
155 my $borderstring_m = '';
156 my $borderstring_b = '';
157 my $borderstring_t = '';
f53ad23a
DM
158 my $formatstring = '';
159
160 my $column_count = scalar(@$props_to_print);
161
41d554d9
DM
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
1c096521 173 my $text = data_to_text($entry->{$prop}, $propinfo, $options);
41d554d9
DM
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
f53ad23a
DM
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;
41d554d9
DM
207 foreach my $coldata (@$tabledata) {
208 my $rowdata = $coldata->{rowdata}->{$prop};
209 $longest = $rowdata->{width} if $rowdata->{width} > $longest;
f53ad23a
DM
210 }
211 $cutoff = $longest if !defined($cutoff) || $cutoff > $longest;
f53ad23a
DM
212
213 $colopts->{$prop} = {
214 title => $title,
f53ad23a
DM
215 cutoff => $cutoff,
216 };
217
793ad69b 218 if ($border) {
eb1c51c2
DM
219 if ($i == 0 && ($column_count == 1)) {
220 if ($utf8) {
41d554d9
DM
221 $formatstring .= "│ %-${cutoff}s │";
222 $borderstring_t .= "┌─" . ('─' x $cutoff) . "─┐";
223 $borderstring_m .= "├─" . ('─' x $cutoff) . "─┤";
224 $borderstring_b .= "└─" . ('─' x $cutoff) . "─┘";
eb1c51c2 225 } else {
41d554d9
DM
226 $formatstring .= "| %-${cutoff}s |";
227 $borderstring_m .= "+-" . ('-' x $cutoff) . "-+";
eb1c51c2
DM
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) {
41d554d9
DM
241 $formatstring .= "│ %-${cutoff}s │";
242 $borderstring_t .= "┬─" . ('─' x $cutoff) . "─┐";
243 $borderstring_m .= "┼─" . ('─' x $cutoff) . "─┤";
244 $borderstring_b .= "┴─" . ('─' x $cutoff) . "─┘";
eb1c51c2 245 } else {
41d554d9
DM
246 $formatstring .= "| %-${cutoff}s |";
247 $borderstring_m .= "+-" . ('-' x $cutoff) . "-+";
eb1c51c2 248 }
793ad69b 249 } else {
eb1c51c2
DM
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 }
793ad69b
DM
259 }
260 } else {
261 # skip alignment and cutoff on last column
41d554d9 262 $formatstring .= ($i == ($column_count - 1)) ? "%s" : "%-${cutoff}s ";
f53ad23a
DM
263 }
264 }
265
eb1c51c2
DM
266 $borderstring_t = $borderstring_m if !length($borderstring_t);
267 $borderstring_b = $borderstring_m if !length($borderstring_b);
268
41d554d9
DM
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;
cde31da0 280 my $text = sprintf $formatstring, map { $colopts->{$_}->{title} } @$props_to_print;
41d554d9 281 $writeln->($text);
793ad69b 282
41d554d9
DM
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 }
f53ad23a 294 }
41d554d9
DM
295
296 $writeln->($borderstring_b) if $border;
f53ad23a
DM
297}
298
c5adc5f9
DM
299sub 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
f53ad23a
DM
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.
322sub print_api_list {
0c22b00c 323 my ($data, $result_schema, $props_to_print, $options) = @_;
f53ad23a
DM
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
c5adc5f9
DM
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;
f53ad23a 338 }
f53ad23a 339 }
c5adc5f9 340 $props_to_print = [ sort keys %{$all_props} ];
f53ad23a
DM
341 }
342
c5adc5f9
DM
343 die "unable to detect list properties\n" if !scalar(@$props_to_print);
344
0c22b00c 345 print_text_table($data, $returnprops, $props_to_print, $options);
f53ad23a
DM
346}
347
348sub print_api_result {
0c22b00c
DM
349 my ($format, $data, $result_schema, $props_to_print, $options) = @_;
350
4ac85000
DM
351 if (!defined($options)) {
352 $options = query_terminal_options({});
353 } else {
354 $options = { %$options }; # copy
355 }
f53ad23a
DM
356
357 return if $result_schema->{type} eq 'null';
358
359 if ($format eq 'json') {
43b104c4 360 # Note: we always use utf8 encoding for json format
f53ad23a 361 print to_json($data, {utf8 => 1, allow_nonref => 1, canonical => 1, pretty => 1 });
793ad69b 362 } elsif ($format eq 'text' || $format eq 'plain') {
43b104c4 363 my $encoding = $options->{encoding} // 'UTF-8';
f53ad23a
DM
364 my $type = $result_schema->{type};
365 if ($type eq 'object') {
c5adc5f9
DM
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);
2a174d2a 369 my $kvstore = [];
f53ad23a 370 foreach my $key (@$props_to_print) {
1c096521 371 push @$kvstore, { key => $key, value => data_to_text($data->{$key}, $result_schema->{properties}->{$key}, $options) };
f53ad23a 372 }
2a174d2a 373 my $schema = { type => 'array', items => { type => 'object' }};
0c22b00c
DM
374 $options->{border} = $format eq 'text';
375 print_api_list($kvstore, $schema, ['key', 'value'], $options);
f53ad23a
DM
376 } elsif ($type eq 'array') {
377 return if !scalar(@$data);
378 my $item_type = $result_schema->{items}->{type};
379 if ($item_type eq 'object') {
0c22b00c
DM
380 $options->{border} = $format eq 'text';
381 print_api_list($data, $result_schema, $props_to_print, $options);
f53ad23a
DM
382 } else {
383 foreach my $entry (@$data) {
1c096521 384 print encode($encoding, data_to_text($entry, $result_schema->{items}, $options) . "\n");
f53ad23a
DM
385 }
386 }
387 } else {
43b104c4 388 print encode($encoding, "$data\n");
f53ad23a
DM
389 }
390 } else {
391 die "internal error: unknown output format"; # should not happen
392 }
393}
394
3951;