[pve-devel] [PATCH common 2/2] add print_text_table, print_entry to CLIHandler

Stoiko Ivanov s.ivanov at proxmox.com
Tue May 29 16:30:12 CEST 2018


These two function could serve as a generic output sub for various CLI
utilities
 * print_text_table can be configured get a list of items and print them in a
   tabular fashion, the column headers can be optionally provided as argument,
   defaulting to the title attribute or name of the displayed property
   (as defined in the regsiter_method call). An optional cutoff argument limits
   the length of the printed data

 * print_entry prints out a single entry, handling array-refs as properties
 * both are needed for the patch sent for pveum (pve-access-control), and could
   be used in more contexts in the future

Signed-off-by: Stoiko Ivanov <s.ivanov at proxmox.com>
---
 src/PVE/CLIHandler.pm | 46 ++++++++++++++++++++++++++++++++++++++++++++++
 1 file changed, 46 insertions(+)

diff --git a/src/PVE/CLIHandler.pm b/src/PVE/CLIHandler.pm
index 58e7a05..512926c 100644
--- a/src/PVE/CLIHandler.pm
+++ b/src/PVE/CLIHandler.pm
@@ -563,4 +563,50 @@ sub run_cli_handler {
     exit 0;
 }
 
+# used to print the result of listing - expects the API to return an array
+# and to have the results key of the API call defined.
+sub print_text_table {
+    my ($class, $formatopts, $data, $info) = @_;
+    my $returnformats = $info->{"returns"}->{"items"}->{"properties"};
+    my ($formatstring, @keylist, @titles, %defaults, %cutoffs, $last_col);
+    @keylist = map { $_->{'key'} } @$formatopts;
+    $last_col = $$formatopts[$#{$formatopts}];
+    foreach my $col ( @$formatopts ) {
+	my ($key, $title, $cutoff) = @$col{ qw(key title cutoff) };
+	$title = $returnformats->{$key}->{'title'} // $key if !defined $title;
+	$defaults{$key} = $col->{'default'} // $returnformats->{$key}->{'default'};
+	my $titlelen = length $title;
+	push @titles, ($title);
+	my $longest = $titlelen;
+	foreach my $entry (@$data) {
+	    my $len = (length $entry->{$key}) // 0;
+	    $longest = $len if $len > $longest;
+	}
+	$longest = $cutoff if (defined $cutoff && $cutoff < $longest);
+	my $printalign = $longest > $titlelen ? '-' : '';
+	if ($col == $last_col) {
+	    $formatstring .= "%$printalign$titlelen"."s\n";
+	} else {
+	    $formatstring .= "%$printalign$longest".'s ';
+	}
+	$cutoffs{$key} = $longest;
+    }
+    printf $formatstring, @titles;
+    foreach my $line (sort { $a->{$keylist[0]} cmp $b->{$keylist[0]} } @$data){
+        printf $formatstring, map { substr(($line->{$_} // $defaults{$_}),0 , $cutoffs{$_}) } @keylist;
+    }
+}
+
+sub print_entry {
+    my ($class, $entry) = @_;
+    foreach my $item (sort keys %$entry) {
+	if (ref($entry->{$item}) eq 'ARRAY'){
+	    printf "%s: [ %s ]\n", $item, join(", ", @{$entry->{$item}});
+	} else {
+	    printf "%s: %s\n", $item, $entry->{$item};
+	}
+    }
+}
+
+
 1;
-- 
2.11.0





More information about the pve-devel mailing list