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