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