]> git.proxmox.com Git - pve-common.git/blame - src/PVE/Format.pm
formatter: render duration: support autolimiting accurarcy
[pve-common.git] / src / PVE / Format.pm
CommitLineData
57b33852
SR
1package PVE::Format;
2
3use strict;
4use warnings;
5
4997835b 6use POSIX qw(strftime round);
57b33852
SR
7
8use base 'Exporter';
9our @EXPORT_OK = qw(
10render_timestamp
11render_timestamp_gmt
12render_duration
13render_fraction_as_percentage
14render_bytes
15);
16
17sub render_timestamp {
18 my ($epoch) = @_;
19
20 # ISO 8601 date format
21 return strftime("%F %H:%M:%S", localtime($epoch));
22}
23
24sub render_timestamp_gmt {
25 my ($epoch) = @_;
26
27 # ISO 8601 date format, standard Greenwich time zone
28 return strftime("%F %H:%M:%S", gmtime($epoch));
29}
30
31sub render_duration {
969c4ffd 32 my ($duration_in_seconds, $auto_limit_accuracy) = @_;
57b33852
SR
33
34 my $text = '';
4997835b
SR
35 my $rest = round($duration_in_seconds // 0);
36
37 return "0s" if !$rest;
57b33852
SR
38
39 my $step = sub {
40 my ($unit, $unitlength) = @_;
41
969c4ffd 42 if ((my $v = int($rest / $unitlength)) > 0) {
57b33852
SR
43 $text .= " " if length($text);
44 $text .= "${v}${unit}";
45 $rest -= $v * $unitlength;
969c4ffd 46 return 1;
57b33852 47 }
969c4ffd 48 return undef;
57b33852
SR
49 };
50
969c4ffd
TL
51 my $weeks = $step->('w', 7 * 24 * 3600);
52 my $days = $step->('d', 24 * 3600) || $weeks;
57b33852 53 $step->('h', 3600);
969c4ffd
TL
54 $step->('m', 60) if !$auto_limit_accuracy || !$weeks;
55 $step->('s', 1) if !$auto_limit_accuracy || !$days;
57b33852
SR
56
57 return $text;
58}
59
60sub render_fraction_as_percentage {
61 my ($fraction) = @_;
62
63 return sprintf("%.2f%%", $fraction*100);
64}
65
66sub render_bytes {
67 my ($value, $precision) = @_;
68
3bb8802a
SR
69 $precision = $precision->{precision} if ref($precision) eq 'HASH';
70
57b33852
SR
71 my @units = qw(B KiB MiB GiB TiB PiB);
72
73 my $max_unit = 0;
74 if ($value > 1023) {
75 $max_unit = int(log($value)/log(1024));
76 $value /= 1024**($max_unit);
77 }
78 my $unit = $units[$max_unit];
79 return sprintf "%." . ($precision || 2) . "f $unit", $value;
80}
81
821;