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