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