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