forked from wallix/awless
-
Notifications
You must be signed in to change notification settings - Fork 2
/
humanize.go
87 lines (77 loc) · 2.18 KB
/
humanize.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
/*
Copyright 2017 WALLIX
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package console
import (
"fmt"
"time"
)
func HumanizeTime(t time.Time) string {
d := time.Now().UTC().Sub(t)
switch {
case d.Seconds() <= time.Second.Seconds():
return "now"
case d.Seconds() <= 2*60*time.Second.Seconds():
return fmt.Sprintf("%d secs", int(d.Seconds()))
case d.Seconds() <= 2*60*time.Minute.Seconds():
return fmt.Sprintf("%d mins", int(d.Minutes()))
case d.Seconds() <= 2*24*time.Hour.Seconds():
return fmt.Sprintf("%d hours", int(d.Hours()))
case d.Seconds() <= 2*7*24*time.Hour.Seconds():
return fmt.Sprintf("%d days", int(d.Hours()/24))
case d.Seconds() <= 2*30*24*time.Hour.Seconds():
return fmt.Sprintf("%d weeks", int(d.Hours()/(24*7)))
case d.Seconds() <= 2*365*24*time.Hour.Seconds():
return fmt.Sprintf("%d months", int(d.Hours()/(24*30)))
default:
return fmt.Sprintf("%d years", int(d.Hours()/(24*365)))
}
}
type storageUnit uint
const (
b storageUnit = iota
kb
mb
gb
)
func HumanizeStorage(nb uint64, unit storageUnit) string {
var nbBytes uint64
switch unit {
case b:
nbBytes = nb
case kb:
nbBytes = nb * 1024
case mb:
nbBytes = nb * 1024 * 1024
case gb:
nbBytes = nb * 1024 * 1024 * 1024
default:
return "invalid storage unit"
}
switch {
case nbBytes < 1024:
return fmt.Sprintf("%dB", nbBytes)
case nbBytes < 1024*1024:
return fmt.Sprintf("%sK", divideValue(nbBytes, 1024))
case nbBytes < 1024*1024*1024:
return fmt.Sprintf("%sM", divideValue(nbBytes, 1024*1024))
default:
return fmt.Sprintf("%sG", divideValue(nbBytes, 1024*1024*1024))
}
}
func divideValue(from, by uint64) string {
res := from / by
if from%by != 0 {
return fmt.Sprintf("~%d", res)
}
return fmt.Sprint(res)
}