[pve-devel] [pve-common 2/4] CLIFormatter: define some commonly useful rendering functions

Dietmar Maurer dietmar at proxmox.com
Mon Jul 2 13:34:14 CEST 2018


Signed-off-by: Dietmar Maurer <dietmar at proxmox.com>
---
 src/PVE/CLIFormatter.pm | 54 +++++++++++++++++++++++++++++++++++++++++++++++++
 1 file changed, 54 insertions(+)

diff --git a/src/PVE/CLIFormatter.pm b/src/PVE/CLIFormatter.pm
index b50464d..14ca9d4 100644
--- a/src/PVE/CLIFormatter.pm
+++ b/src/PVE/CLIFormatter.pm
@@ -10,6 +10,60 @@ use JSON;
 use utf8;
 use Encode;
 
+sub render_duration {
+    my ($duration_in_seconds) = @_;
+
+    my $text = '';
+    my $rest = $duration_in_seconds;
+    if ((my $days = int($rest/(24*3600))) > 0) {
+	$text .= " " if length($text);
+	$text .= "${days}d";
+	$rest -= $days*24*3600;
+    }
+    if ((my $hours = int($rest/3600)) > 0) {
+	$text .= " " if length($text);
+	$text .= "${hours}h";
+	$rest -= $hours*3600;
+    }
+    if ((my $minutes = int($rest/60)) > 0) {
+	$text .= " " if length($text);
+	$text .= "${minutes}m";
+	$rest -= $minutes*60;
+    }
+    if ($rest > 0) {
+	$text .= " " if length($text);
+	$text .= "${rest}s";
+    }
+    return $text;
+}
+
+PVE::JSONSchema::register_renderer('duration', \&render_duration);
+
+sub render_fraction_as_percentage {
+    my ($fraction) = @_;
+
+    return sprintf("%.2f%%", $fraction*100);
+}
+
+PVE::JSONSchema::register_renderer(
+    'fraction_as_percentage', \&render_fraction_as_percentage);
+
+sub render_bytes {
+    my ($bytes) = @_;
+
+    if ((my $gib = $bytes/(1024*1024*1024)) >= 1) {
+	return sprintf("%.2fGiB", $gib);
+    } elsif ((my $mib = $bytes/1024*1024) >= 1) {
+	return sprintf("%.2fMiB", $mib);
+    } elsif ((my $kib = $bytes/1024) >= 1) {
+	return sprintf("%.2fKiB", $kib);
+    } else {
+	return "${bytes}";
+    }
+}
+
+PVE::JSONSchema::register_renderer('bytes', \&render_bytes);
+
 sub query_terminal_options {
     my ($options) = @_;
 
-- 
2.11.0




More information about the pve-devel mailing list