[pve-devel] [PATCH v2 common] cli-formatter: avoid warning when trying to sort on undefined key

Thomas Lamprecht t.lamprecht at proxmox.com
Wed Nov 27 16:59:22 CET 2019


On 11/26/19 1:10 PM, Christian Ebner wrote:
> Example:
>     pvesh get /nodes/{node}/qemu/{vmid}/rrddata --timeframe day
> 
> If the sorting key is not defined in the dataset, e.g. when a VM was not running
> for some time within the given timeframe, this resulted in several ugly warnings.
> 
> Signed-off-by: Christian Ebner <c.ebner at proxmox.com>
> ---
> 
> v2: Oops, v1 is nonsense and breaks sorting.
> 
>  src/PVE/CLIFormatter.pm | 6 ++++--
>  1 file changed, 4 insertions(+), 2 deletions(-)
> 
> diff --git a/src/PVE/CLIFormatter.pm b/src/PVE/CLIFormatter.pm
> index 0e9cbe6..21fa2df 100644
> --- a/src/PVE/CLIFormatter.pm
> +++ b/src/PVE/CLIFormatter.pm
> @@ -175,9 +175,11 @@ sub print_text_table {
>      if (defined($sort_key) && $sort_key ne 0) {
>  	my $type = $returnprops->{$sort_key}->{type} // 'string';
>  	if ($type eq 'integer' || $type eq 'number') {
> -	    @$data = sort { $a->{$sort_key} <=> $b->{$sort_key} } @$data;
> +	    @$data = sort { $a->{$sort_key} <=> $b->{$sort_key}
> +		if defined $a->{$sort_key} && defined $b->{$sort_key} } @$data;
>  	} else {
> -	    @$data = sort { $a->{$sort_key} cmp $b->{$sort_key} } @$data;
> +	    @$data = sort { $a->{$sort_key} cmp $b->{$sort_key}
> +		if defined $a->{$sort_key} && defined $b->{$sort_key} } @$data;


a post-if in a sort condition feels a bit awkward and does not
clearly tells a reader what the behavior for undefined cases is, IMO

Maybe use a ternary operation here:
sort {
    defined $a->{$sort_key} && defined $b->{$sort_key}
        ? $a->{$sort_key} cmp $b->{$sort_key}
        : 1
}


or as alternative a sorter method:

my $hashsort = sub {
    my ($a, $b, $key) = @_;
    return 1 if !(defined $a->{$key} && defined $b->{$key});
    return $a->{$key} cmp $b->{$key};
}

and use that?

Or even:

return 1 if defined $a->{$key} && !defined $b->{$key});
return -1 if !defined $a->{$key} && defined $b->{$key};
return 0 if defined $a->{$key} && defined $b->{$key};

?? that stuff confuses me after a longer day, sorry ^^




More information about the pve-devel mailing list