-# prints a formatted table with a title row.
-# $formatopts is an array of hashes, with the following keys:
-# 'key' - key of $data element to print
-# 'title' - column title, defaults to 'key' - won't get cutoff
-# 'cutoff' - maximal (print) length of this column values, if set
-# the last column will never be cutoff
-# 'default' - optional default value for the column
-# formatopts element order defines column order (left to right)
-sub print_text_table {
- my ($formatopts, $data) = @_;
-
- my ($formatstring, @keys, @titles, %cutoffs, %defaults);
- my $last_col = $formatopts->[$#{$formatopts}];
-
- foreach my $col ( @$formatopts ) {
- my ($key, $title, $cutoff) = @$col{qw(key title cutoff)};
- $title //= $key;
-
- push @keys, $key;
- push @titles, $title;
- $defaults{$key} = $col->{default} // '';
-
- # calculate maximal print width and cutoff
- my $titlelen = length($title);
-
- my $longest = $titlelen;
- foreach my $entry (@$data) {
- my $len = length($entry->{$key}) // 0;
- $longest = $len if $len > $longest;
- }
-
- $cutoff = (defined($cutoff) && $cutoff < $longest) ? $cutoff : $longest;
- $cutoffs{$key} = $cutoff;
-
- my $printalign = $cutoff > $titlelen ? '-' : '';
- if ($col == $last_col) {
- $formatstring .= "%${printalign}${titlelen}s\n";
- } else {
- $formatstring .= "%${printalign}${cutoff}s ";
- }
- }
-
- printf $formatstring, @titles;
-
- foreach my $entry (sort { $a->{$keys[0]} cmp $b->{$keys[0]} } @$data) {
- printf $formatstring, map { substr(($entry->{$_} // $defaults{$_}), 0 , $cutoffs{$_}) } @keys;
- }
-}
-
-sub print_entry {
- my $entry = shift;
-
- #TODO: handle objects/hashes as well
- 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};
- }
- }
-}
-
-# prints the result of an API GET call returning an array
-# and to have the results key of the API call defined.
-sub print_api_list {
- my ($props_to_print, $data, $returninfo) = @_;
-
- die "can only print array result" if $returninfo->{type} ne 'array';
-
- my $returnprops = $returninfo->{items}->{properties};
-
- my $formatopts = [];
- foreach my $prop ( @$props_to_print ) {
- my $propinfo = $returnprops->{$prop};
- my $colopts = {
- key => $prop,
- title => $propinfo->{title},
- default => $propinfo->{default},
- cutoff => $propinfo->{print_width} // $propinfo->{maxLength},
- };
- push @$formatopts, $colopts;
- }
-
- print_text_table($formatopts, $data);
-}
-