forked from astaxie/bat
-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils.go
80 lines (73 loc) · 1.64 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
package main
import (
"fmt"
"strconv"
"strings"
)
func inSlice(str string, l []string) bool {
for i := range l {
if l[i] == str {
return true
}
}
return false
}
func toRealType(str string) interface{} {
if i, err := isint(str); err == nil {
return i
}
if b, err := isbool(str); err == nil {
return b
}
if f, err := isfloat(str); err == nil {
return f
}
if strings.HasPrefix(str, "[") && strings.HasSuffix(str, "]") {
bstr := []byte(str)
strs := strings.Split(string(bstr[1:len(bstr)-1]), ",")
var r []interface{}
for _, s := range strs {
if i, err := isint(s); err == nil {
r = append(r, i)
continue
}
if i, err := isbool(s); err == nil {
r = append(r, i)
continue
}
if i, err := isfloat(s); err == nil {
r = append(r, i)
continue
}
r = append(r, strings.Trim(s, "\"' "))
}
return r
}
return str
}
func isint(v string) (i int, err error) {
return strconv.Atoi(v)
}
func isbool(v string) (bool, error) {
return strconv.ParseBool(v)
}
func isfloat(v string) (float64, error) {
return strconv.ParseFloat(v, 64)
}
// Convert bytes to human readable string. Like a 2 MB, 64.2 KB, 52 B
func FormatBytes(i int64) (result string) {
switch {
case i > (1024 * 1024 * 1024 * 1024):
result = fmt.Sprintf("%#.02f TB", float64(i)/1024/1024/1024/1024)
case i > (1024 * 1024 * 1024):
result = fmt.Sprintf("%#.02f GB", float64(i)/1024/1024/1024)
case i > (1024 * 1024):
result = fmt.Sprintf("%#.02f MB", float64(i)/1024/1024)
case i > 1024:
result = fmt.Sprintf("%#.02f KB", float64(i)/1024)
default:
result = fmt.Sprintf("%d B", i)
}
result = strings.Trim(result, " ")
return
}