]> git.proxmox.com Git - pve-common.git/blame - src/PVE/Format.pm
format: drop unused JSONSchema module use
[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 {
32 my ($duration_in_seconds) = @_;
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
42 if ((my $v = int($rest/$unitlength)) > 0) {
43 $text .= " " if length($text);
44 $text .= "${v}${unit}";
45 $rest -= $v * $unitlength;
46 }
47 };
48
49 $step->('w', 7*24*3600);
50 $step->('d', 24*3600);
51 $step->('h', 3600);
52 $step->('m', 60);
53 $step->('s', 1);
54
55 return $text;
56}
57
58sub render_fraction_as_percentage {
59 my ($fraction) = @_;
60
61 return sprintf("%.2f%%", $fraction*100);
62}
63
64sub render_bytes {
65 my ($value, $precision) = @_;
66
67 my @units = qw(B KiB MiB GiB TiB PiB);
68
69 my $max_unit = 0;
70 if ($value > 1023) {
71 $max_unit = int(log($value)/log(1024));
72 $value /= 1024**($max_unit);
73 }
74 my $unit = $units[$max_unit];
75 return sprintf "%." . ($precision || 2) . "f $unit", $value;
76}
77
781;