[pve-devel] [PATCH v2 common] print_text_table: handle undefined values in comparision

Oğuz Bektaş o.bektas at proxmox.com
Tue Apr 28 12:00:20 CEST 2020


Tested-by: Oguz Bektas <o.bektas at proxmox.com>


> Fabian Ebner <f.ebner at proxmox.com> hat am 28. April 2020 10:18 geschrieben:
> 
>  
> by introducing a safe_compare helper. Fixes warnings, e.g.
> pvesh get /nodes/<NODE>/network
> would print "use of uninitialized"-warnings if there are inactive
> network interfaces, because for those, 'active' is undef.
> 
> Signed-off-by: Fabian Ebner <f.ebner at proxmox.com>
> ---
> 
> Changes from v1:
>     * don't change sort_key depending on data
>     * instead handle undefined values directly
>       in comparision
> 
>  src/PVE/CLIFormatter.pm | 11 +++++++----
>  src/PVE/Tools.pm        |  9 +++++++++
>  2 files changed, 16 insertions(+), 4 deletions(-)
> 
> diff --git a/src/PVE/CLIFormatter.pm b/src/PVE/CLIFormatter.pm
> index 0e9cbe6..4f18fa9 100644
> --- a/src/PVE/CLIFormatter.pm
> +++ b/src/PVE/CLIFormatter.pm
> @@ -150,8 +150,7 @@ sub data_to_text {
>  # $props_to_print - ordered list of properties to print
>  # $options
>  # - sort_key: can be used to sort after a specific column, if it isn't set we sort
> -#   after the leftmost column (with no undef value in $data) this can be
> -#   turned off by passing 0 as sort_key
> +#   after the leftmost column. This can be turned off by passing 0 as sort_key
>  # - noborder: print without asciiart border
>  # - noheader: print without table header
>  # - columns: limit output width (if > 0)
> @@ -174,11 +173,15 @@ sub print_text_table {
>  
>      if (defined($sort_key) && $sort_key ne 0) {
>  	my $type = $returnprops->{$sort_key}->{type} // 'string';
> +	my $cmpfn;
>  	if ($type eq 'integer' || $type eq 'number') {
> -	    @$data = sort { $a->{$sort_key} <=> $b->{$sort_key} } @$data;
> +	    $cmpfn = sub { $_[0] <=> $_[1] };
>  	} else {
> -	    @$data = sort { $a->{$sort_key} cmp $b->{$sort_key} } @$data;
> +	    $cmpfn = sub { $_[0] cmp $_[1] };
>  	}
> +	@$data = sort {
> +	    PVE::Tools::safe_compare($a->{$sort_key}, $b->{$sort_key}, $cmpfn)
> +	} @$data;
>      }
>  
>      my $colopts = {};
> diff --git a/src/PVE/Tools.pm b/src/PVE/Tools.pm
> index f02c0ae..f6b18f1 100644
> --- a/src/PVE/Tools.pm
> +++ b/src/PVE/Tools.pm
> @@ -1766,4 +1766,13 @@ sub mount($$$$$) {
>      );
>  }
>  
> +sub safe_compare {
> +    my ($left, $right, $cmp) = @_;
> +
> +    return 0 if !defined($left) && !defined($right);
> +    return -1 if !defined($left);
> +    return 1 if !defined($right);
> +    return $cmp->($left, $right);
> +}
> +
>  1;
> -- 
> 2.20.1
> 
> 
> _______________________________________________
> pve-devel mailing list
> pve-devel at pve.proxmox.com
> https://pve.proxmox.com/cgi-bin/mailman/listinfo/pve-devel




More information about the pve-devel mailing list