[pve-devel] [RFC pve-common] cli: data_to_text: pass property info

Dietmar Maurer dietmar at proxmox.com
Wed Jun 27 14:38:03 CEST 2018


So that we can display defaults, render boolean nicely, or call arbitrary render
functions ...

Signed-off-by: Dietmar Maurer <dietmar at proxmox.com>
---
 src/PVE/CLIHandler.pm | 21 +++++++++++++++++----
 1 file changed, 17 insertions(+), 4 deletions(-)

diff --git a/src/PVE/CLIHandler.pm b/src/PVE/CLIHandler.pm
index 1d68708..136a49f 100644
--- a/src/PVE/CLIHandler.pm
+++ b/src/PVE/CLIHandler.pm
@@ -430,8 +430,21 @@ my $print_bash_completion = sub {
 };
 
 sub data_to_text {
-    my ($data) = @_;
+    my ($data, $propdef) = @_;
 
+    if (defined($propdef)) {
+	if (my $type = $propdef->{type}) {
+	    if ($type eq 'boolean') {
+		return $data ? 1 : 0;
+	    }
+	}
+	if (!defined($data) && defined($propdef->{default})) {
+	    return "($propdef->{default})";
+	}
+	if (defined(my $renderer = $propdef->{renderer})) {
+	    return $renderer->($data);
+	}
+    }
     return '' if !defined($data);
 
     if (my $class = ref($data)) {
@@ -478,7 +491,7 @@ sub print_text_table {
 	my $longest = $titlelen;
 	my $sortable = $autosort;
 	foreach my $entry (@$data) {
-	    my $len = length(data_to_text($entry->{$prop})) // 0;
+	    my $len = length(data_to_text($entry->{$prop}, $propinfo)) // 0;
 	    $longest = $len if $len > $longest;
 	    $sortable = 0 if !defined($entry->{$prop});
 	}
@@ -520,7 +533,7 @@ sub print_text_table {
     foreach my $entry (@$data) {
 	print $borderstring if $border;
         printf $formatstring, map {
-	    substr(data_to_text($entry->{$_}) // $colopts->{$_}->{default},
+	    substr(data_to_text($entry->{$_}, $returnprops->{$_}) // $colopts->{$_}->{default},
 		   0, $colopts->{$_}->{cutoff});
 	} @$props_to_print;
     }
@@ -570,7 +583,7 @@ sub print_api_result {
 	    $props_to_print = [ sort keys %$data ] if !defined($props_to_print);
 	    my $kvstore = [];
 	    foreach my $key (@$props_to_print) {
-		push @$kvstore, { key => $key, value => data_to_text($data->{$key}) };
+		push @$kvstore, { key => $key, value => data_to_text($data->{$key}, $result_schema->{properties}->{$key}) };
 	    }
 	    my $schema = { type => 'array', items => { type => 'object' }};
 	    print_api_list($kvstore, $schema, ['key', 'value'], 0, $format eq 'text');
-- 
2.11.0




More information about the pve-devel mailing list