forked from AliyunContainerService/pouch
/
utils.go
110 lines (99 loc) · 2.36 KB
/
utils.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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
package utils
import (
"errors"
"fmt"
"strconv"
"time"
)
// Common durations that is .
// There are some definitions for units of Day and larger .
const (
Second = time.Second
Minute = Second * 60
Hour = Minute * 60
Day = Hour * 24
Week = Day * 7
Month = Day * 30
Year = Day * 365
TimeLayout = "2006-01-02 15:04:05"
)
var errInvalid = errors.New("invalid time")
// If implements ternary operator. if cond is true return v1, or return v2 instead.
func If(cond bool, v1, v2 interface{}) interface{} {
if cond {
return v1
}
return v2
}
// FormatSize format image size to B/KB/MB/GB
func FormatSize(size int64) string {
if size <= 0 {
return "0.00 B"
}
// we consider image size less than 1024 GB
suffixes := []string{"B", "KB", "MB", "GB"}
var count int
formattedSize := float64(size)
for count = 0; count < 3; count++ {
if formattedSize < 1024 {
break
}
formattedSize /= 1024
}
return fmt.Sprintf("%.2f %s", formattedSize, suffixes[count])
}
// FormatTimeInterval is used to show the time interval from input time to now.
func FormatTimeInterval(input int64) (formattedTime string, err error) {
start := time.Unix(0, input)
diff := time.Now().Sub(start)
// That should not happen.
if diff < 0 {
return "", errInvalid
}
if diff >= Year {
year := int(diff / Year)
formattedTime += strconv.Itoa(year) + " year"
if year > 1 {
formattedTime += "s"
}
} else if diff >= Month {
month := int(diff / Month)
formattedTime += strconv.Itoa(month) + " month"
if month > 1 {
formattedTime += "s"
}
} else if diff >= Week {
week := int(diff / Week)
formattedTime += strconv.Itoa(week) + " week"
if week > 1 {
formattedTime += "s"
}
} else if diff >= Day {
day := int(diff / Day)
formattedTime += strconv.Itoa(day) + " day"
if day > 1 {
formattedTime += "s"
}
} else if diff >= Hour {
hour := int(diff / Hour)
formattedTime += strconv.Itoa(hour) + " hour"
if hour > 1 {
formattedTime += "s"
}
} else if diff >= Minute {
minute := int(diff / Minute)
formattedTime += strconv.Itoa(minute) + " minute"
if minute > 1 {
formattedTime += "s"
}
} else if diff >= Second {
second := int(diff / Second)
formattedTime += strconv.Itoa(second) + " second"
if second > 1 {
formattedTime += "s"
}
} else {
formattedTime += "0 second"
}
return formattedTime, nil
}