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