]> git.proxmox.com Git - pve-common.git/blobdiff - src/PVE/CLIFormatter.pm
cli: data_to_text: never render undefined values
[pve-common.git] / src / PVE / CLIFormatter.pm
index 77f528bafd4c1cb3c2e7bacb7f6e9f57dd907bb2..a6c47952fecf16b8d852c2ac1a6b579c836ec262 100644 (file)
@@ -2,11 +2,30 @@ package PVE::CLIFormatter;
 
 use strict;
 use warnings;
+use I18N::Langinfo;
+
 use PVE::JSONSchema;
+use PVE::PTY;
 use JSON;
 use utf8;
 use Encode;
 
+sub query_terminal_options {
+    my ($options) = @_;
+
+    $options //= {};
+
+    if (-t STDOUT) {
+       ($options->{columns}) = PVE::PTY::tcgetsize(*STDOUT);
+    }
+
+    $options->{encoding} = I18N::Langinfo::langinfo(I18N::Langinfo::CODESET());
+
+    $options->{utf8} = 1 if $options->{encoding} eq 'UTF-8';
+
+    return $options;
+}
+
 sub println_max {
     my ($text, $encoding, $max) = @_;
 
@@ -23,6 +42,8 @@ sub println_max {
 sub data_to_text {
     my ($data, $propdef) = @_;
 
+    return '' if !defined($data);
+
     if (defined($propdef)) {
        if (my $type = $propdef->{type}) {
            if ($type eq 'boolean') {
@@ -38,7 +59,6 @@ sub data_to_text {
            return $code->($data);
        }
     }
-    return '' if !defined($data);
 
     if (my $class = ref($data)) {
        return to_json($data, { canonical => 1 });
@@ -217,8 +237,11 @@ sub print_api_list {
 sub print_api_result {
     my ($format, $data, $result_schema, $props_to_print, $options) = @_;
 
-    $options //= {};
-    $options = { %$options }; # copy
+    if (!defined($options)) {
+       $options = query_terminal_options({});
+    } else {
+       $options = { %$options }; # copy
+    }
 
     return if $result_schema->{type} eq 'null';