]> git.proxmox.com Git - pve-common.git/blame - src/PVE/CLIFormatter.pm
JSONSchema: define 'renderer' property
[pve-common.git] / src / PVE / CLIFormatter.pm
CommitLineData
f53ad23a
DM
1package PVE::CLIFormatter;
2
3use strict;
4use warnings;
4ac85000
DM
5use I18N::Langinfo;
6
84142f1d 7use PVE::JSONSchema;
4ac85000 8use PVE::PTY;
f53ad23a 9use JSON;
eb1c51c2
DM
10use utf8;
11use Encode;
f53ad23a 12
4ac85000
DM
13sub query_terminal_options {
14 my ($options) = @_;
15
16 $options //= {};
17
18 if (-t STDOUT) {
19 ($options->{columns}) = PVE::PTY::tcgetsize(*STDOUT);
20 }
21
22 $options->{encoding} = I18N::Langinfo::langinfo(I18N::Langinfo::CODESET());
23
24 $options->{utf8} = 1 if $options->{encoding} eq 'UTF-8';
25
26 return $options;
27}
28
f53ad23a 29sub data_to_text {
84142f1d 30 my ($data, $propdef) = @_;
f53ad23a 31
3cd6f2f3
DM
32 return '' if !defined($data);
33
84142f1d
DM
34 if (defined($propdef)) {
35 if (my $type = $propdef->{type}) {
36 if ($type eq 'boolean') {
37 return $data ? 1 : 0;
38 }
39 }
40 if (!defined($data) && defined($propdef->{default})) {
41 return "($propdef->{default})";
42 }
43 if (defined(my $renderer = $propdef->{renderer})) {
44 my $code = PVE::JSONSchema::get_renderer($renderer);
45 die "internal error: unknown renderer '$renderer'" if !$code;
46 return $code->($data);
47 }
48 }
f53ad23a
DM
49
50 if (my $class = ref($data)) {
84142f1d 51 return to_json($data, { canonical => 1 });
f53ad23a
DM
52 } else {
53 return "$data";
54 }
55}
56
57# prints a formatted table with a title row.
58# $data - the data to print (array of objects)
59# $returnprops -json schema property description
60# $props_to_print - ordered list of properties to print
0c22b00c
DM
61# $options
62# - sort_key: can be used to sort after a column, if it isn't set we sort
f53ad23a 63# after the leftmost column (with no undef value in $data) this can be
0c22b00c
DM
64# turned off by passing 0 as sort_key
65# - border: print with/without table header and asciiart border
66# - columns: limit output width (if > 0)
67# - utf8: use utf8 characters for table delimiters
68
f53ad23a 69sub print_text_table {
0c22b00c
DM
70 my ($data, $returnprops, $props_to_print, $options) = @_;
71
72 my $sort_key = $options->{sort_key};
73 my $border = $options->{border};
74 my $columns = $options->{columns};
75 my $utf8 = $options->{utf8};
43b104c4 76 my $encoding = $options->{encoding} // 'UTF-8';
f53ad23a 77
ef3c37dd 78 if (!defined($sort_key) || $sort_key eq 0) {
41d554d9
DM
79 $sort_key = $props_to_print->[0];
80 }
81
82 if (defined($sort_key)) {
83 my $type = $returnprops->{$sort_key}->{type} // 'string';
84 if ($type eq 'integer' || $type eq 'number') {
85 @$data = sort { $a->{$sort_key} <=> $b->{$sort_key} } @$data;
86 } else {
87 @$data = sort { $a->{$sort_key} cmp $b->{$sort_key} } @$data;
88 }
f53ad23a
DM
89 }
90
91 my $colopts = {};
793ad69b 92
eb1c51c2
DM
93 my $borderstring_m = '';
94 my $borderstring_b = '';
95 my $borderstring_t = '';
f53ad23a
DM
96 my $formatstring = '';
97
98 my $column_count = scalar(@$props_to_print);
99
41d554d9
DM
100 my $tabledata = [];
101
102 foreach my $entry (@$data) {
103
104 my $height = 1;
105 my $rowdata = {};
106
107 for (my $i = 0; $i < $column_count; $i++) {
108 my $prop = $props_to_print->[$i];
109 my $propinfo = $returnprops->{$prop} // {};
110
111 my $text = data_to_text($entry->{$prop}, $propinfo);
112 my $lines = [ split(/\n/, $text) ];
113 my $linecount = scalar(@$lines);
114 $height = $linecount if $linecount > $height;
115
116 my $width = 0;
117 foreach my $line (@$lines) {
118 my $len = length($line);
119 $width = $len if $len > $width;
120 }
121
122 $rowdata->{$prop} = {
123 lines => $lines,
124 width => $width,
125 };
126 }
127
128 push @$tabledata, {
129 height => $height,
130 rowdata => $rowdata,
131 };
132 }
133
f53ad23a
DM
134 for (my $i = 0; $i < $column_count; $i++) {
135 my $prop = $props_to_print->[$i];
136 my $propinfo = $returnprops->{$prop} // {};
137
138 my $title = $propinfo->{title} // $prop;
139 my $cutoff = $propinfo->{print_width} // $propinfo->{maxLength};
140
141 # calculate maximal print width and cutoff
142 my $titlelen = length($title);
143
144 my $longest = $titlelen;
41d554d9
DM
145 foreach my $coldata (@$tabledata) {
146 my $rowdata = $coldata->{rowdata}->{$prop};
147 $longest = $rowdata->{width} if $rowdata->{width} > $longest;
f53ad23a
DM
148 }
149 $cutoff = $longest if !defined($cutoff) || $cutoff > $longest;
f53ad23a
DM
150
151 $colopts->{$prop} = {
152 title => $title,
f53ad23a
DM
153 cutoff => $cutoff,
154 };
155
793ad69b 156 if ($border) {
eb1c51c2
DM
157 if ($i == 0 && ($column_count == 1)) {
158 if ($utf8) {
41d554d9
DM
159 $formatstring .= "│ %-${cutoff}s │";
160 $borderstring_t .= "┌─" . ('─' x $cutoff) . "─┐";
161 $borderstring_m .= "├─" . ('─' x $cutoff) . "─┤";
162 $borderstring_b .= "└─" . ('─' x $cutoff) . "─┘";
eb1c51c2 163 } else {
41d554d9
DM
164 $formatstring .= "| %-${cutoff}s |";
165 $borderstring_m .= "+-" . ('-' x $cutoff) . "-+";
eb1c51c2
DM
166 }
167 } elsif ($i == 0) {
168 if ($utf8) {
169 $formatstring .= "│ %-${cutoff}s ";
170 $borderstring_t .= "┌─" . ('─' x $cutoff) . '─';
171 $borderstring_m .= "├─" . ('─' x $cutoff) . '─';
172 $borderstring_b .= "└─" . ('─' x $cutoff) . '─';
173 } else {
174 $formatstring .= "| %-${cutoff}s ";
175 $borderstring_m .= "+-" . ('-' x $cutoff) . '-';
176 }
177 } elsif ($i == ($column_count - 1)) {
178 if ($utf8) {
41d554d9
DM
179 $formatstring .= "│ %-${cutoff}s │";
180 $borderstring_t .= "┬─" . ('─' x $cutoff) . "─┐";
181 $borderstring_m .= "┼─" . ('─' x $cutoff) . "─┤";
182 $borderstring_b .= "┴─" . ('─' x $cutoff) . "─┘";
eb1c51c2 183 } else {
41d554d9
DM
184 $formatstring .= "| %-${cutoff}s |";
185 $borderstring_m .= "+-" . ('-' x $cutoff) . "-+";
eb1c51c2 186 }
793ad69b 187 } else {
eb1c51c2
DM
188 if ($utf8) {
189 $formatstring .= "│ %-${cutoff}s ";
190 $borderstring_t .= "┬─" . ('─' x $cutoff) . '─';
191 $borderstring_m .= "┼─" . ('─' x $cutoff) . '─';
192 $borderstring_b .= "┴─" . ('─' x $cutoff) . '─';
193 } else {
194 $formatstring .= "| %-${cutoff}s ";
195 $borderstring_m .= "+-" . ('-' x $cutoff) . '-';
196 }
793ad69b
DM
197 }
198 } else {
199 # skip alignment and cutoff on last column
41d554d9 200 $formatstring .= ($i == ($column_count - 1)) ? "%s" : "%-${cutoff}s ";
f53ad23a
DM
201 }
202 }
203
eb1c51c2
DM
204 $borderstring_t = $borderstring_m if !length($borderstring_t);
205 $borderstring_b = $borderstring_m if !length($borderstring_b);
206
41d554d9
DM
207 my $writeln = sub {
208 my ($text) = @_;
209
210 if ($columns) {
211 print encode($encoding, substr($text, 0, $columns) . "\n");
212 } else {
213 print encode($encoding, $text) . "\n";
214 }
215 };
216
217 $writeln->($borderstring_t) if $border;
cde31da0 218 my $text = sprintf $formatstring, map { $colopts->{$_}->{title} } @$props_to_print;
41d554d9 219 $writeln->($text);
793ad69b 220
41d554d9
DM
221 foreach my $coldata (@$tabledata) {
222 $writeln->($borderstring_m) if $border;
223
224 for (my $i = 0; $i < $coldata->{height}; $i++) {
225
226 $text = sprintf $formatstring, map {
227 substr($coldata->{rowdata}->{$_}->{lines}->[$i] // '', 0, $colopts->{$_}->{cutoff});
228 } @$props_to_print;
229
230 $writeln->($text);
231 }
f53ad23a 232 }
41d554d9
DM
233
234 $writeln->($borderstring_b) if $border;
f53ad23a
DM
235}
236
237# prints the result of an API GET call returning an array as a table.
238# takes formatting information from the results property of the call
239# if $props_to_print is provided, prints only those columns. otherwise
240# takes all fields of the results property, with a fallback
241# to all fields occuring in items of $data.
242sub print_api_list {
0c22b00c 243 my ($data, $result_schema, $props_to_print, $options) = @_;
f53ad23a
DM
244
245 die "can only print object lists\n"
246 if !($result_schema->{type} eq 'array' && $result_schema->{items}->{type} eq 'object');
247
248 my $returnprops = $result_schema->{items}->{properties};
249
250 if (!defined($props_to_print)) {
251 $props_to_print = [ sort keys %$returnprops ];
252 if (!scalar(@$props_to_print)) {
253 my $all_props = {};
254 foreach my $obj (@{$data}) {
255 foreach my $key (keys %{$obj}) {
256 $all_props->{ $key } = 1;
257 }
258 }
259 $props_to_print = [ sort keys %{$all_props} ];
260 }
261 die "unable to detect list properties\n" if !scalar(@$props_to_print);
262 }
263
0c22b00c 264 print_text_table($data, $returnprops, $props_to_print, $options);
f53ad23a
DM
265}
266
267sub print_api_result {
0c22b00c
DM
268 my ($format, $data, $result_schema, $props_to_print, $options) = @_;
269
4ac85000
DM
270 if (!defined($options)) {
271 $options = query_terminal_options({});
272 } else {
273 $options = { %$options }; # copy
274 }
f53ad23a
DM
275
276 return if $result_schema->{type} eq 'null';
277
278 if ($format eq 'json') {
43b104c4 279 # Note: we always use utf8 encoding for json format
f53ad23a 280 print to_json($data, {utf8 => 1, allow_nonref => 1, canonical => 1, pretty => 1 });
793ad69b 281 } elsif ($format eq 'text' || $format eq 'plain') {
43b104c4 282 my $encoding = $options->{encoding} // 'UTF-8';
f53ad23a
DM
283 my $type = $result_schema->{type};
284 if ($type eq 'object') {
285 $props_to_print = [ sort keys %$data ] if !defined($props_to_print);
2a174d2a 286 my $kvstore = [];
f53ad23a 287 foreach my $key (@$props_to_print) {
84142f1d 288 push @$kvstore, { key => $key, value => data_to_text($data->{$key}, $result_schema->{properties}->{$key}) };
f53ad23a 289 }
2a174d2a 290 my $schema = { type => 'array', items => { type => 'object' }};
0c22b00c
DM
291 $options->{border} = $format eq 'text';
292 print_api_list($kvstore, $schema, ['key', 'value'], $options);
f53ad23a
DM
293 } elsif ($type eq 'array') {
294 return if !scalar(@$data);
295 my $item_type = $result_schema->{items}->{type};
296 if ($item_type eq 'object') {
0c22b00c
DM
297 $options->{border} = $format eq 'text';
298 print_api_list($data, $result_schema, $props_to_print, $options);
f53ad23a
DM
299 } else {
300 foreach my $entry (@$data) {
43b104c4 301 print encode($encoding, data_to_text($entry) . "\n");
f53ad23a
DM
302 }
303 }
304 } else {
43b104c4 305 print encode($encoding, "$data\n");
f53ad23a
DM
306 }
307 } else {
308 die "internal error: unknown output format"; # should not happen
309 }
310}
311
3121;