]>
Commit | Line | Data |
---|---|---|
57b33852 SR |
1 | package PVE::Format; |
2 | ||
3 | use strict; | |
4 | use warnings; | |
5 | ||
4997835b | 6 | use POSIX qw(strftime round); |
57b33852 SR |
7 | |
8 | use base 'Exporter'; | |
9 | our @EXPORT_OK = qw( | |
10 | render_timestamp | |
11 | render_timestamp_gmt | |
12 | render_duration | |
13 | render_fraction_as_percentage | |
14 | render_bytes | |
15 | ); | |
16 | ||
17 | sub render_timestamp { | |
18 | my ($epoch) = @_; | |
19 | ||
20 | # ISO 8601 date format | |
21 | return strftime("%F %H:%M:%S", localtime($epoch)); | |
22 | } | |
23 | ||
24 | sub 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 | ||
31 | sub 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 | ||
60 | sub render_fraction_as_percentage { | |
61 | my ($fraction) = @_; | |
62 | ||
63 | return sprintf("%.2f%%", $fraction*100); | |
64 | } | |
65 | ||
66 | sub 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 | ||
82 | 1; |