/
common.go
100 lines (80 loc) · 1.64 KB
/
common.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
package common
import (
"crypto/rand"
"fmt"
"github.com/google/uuid"
"math/big"
"os"
"runtime"
"strings"
"time"
)
// IsWindowsOS reports true if underlying OS is MS Windows
func IsWindows() bool {
return runtime.GOOS == "windows"
}
// IsLinuxOS reports true if underlying OS is Linux
func IsLinux() bool {
return runtime.GOOS == "linux"
}
// IsMacOS reports true if underlying OS is MacOS
func IsMac() bool {
return runtime.GOOS == "darwin"
}
// ToBool reports if value indicates "true"
func ToBool(s string) bool {
if len(s) == 0 {
return false
}
s = strings.ToLower(s)
return s == "true" || s == "1" || strings.HasPrefix(s, "t") || strings.HasPrefix(s, "y") || strings.HasPrefix(s, "j")
}
func Eval(b bool, trueFunc interface{}, falseFunc interface{}) interface{} {
if b {
if f, ok := trueFunc.(func() interface{}); ok {
return f()
} else {
return trueFunc
}
} else {
if f, ok := falseFunc.(func() interface{}); ok {
return f()
} else {
return falseFunc
}
}
}
func Sleep(d time.Duration) {
if !*FlagLogVerbose {
time.Sleep(d)
return
}
id := uuid.New().String()
DebugIndex(1, "Sleep [%s] %v... ", id, d)
time.Sleep(d)
DebugIndex(1, "Sleep [%s] %v continue", id, d)
}
func Catch(fn func() error) (err error) {
defer func() {
if r := recover(); r != nil {
switch x := r.(type) {
case string:
err = fmt.Errorf(x)
case error:
err = x
default:
err = fmt.Errorf("unknown panic: %+v", r)
}
}
}()
return fn()
}
func Exit(code int) {
done()
os.Exit(code)
}
func Rnd(max int) int {
nBig, err := rand.Int(rand.Reader, big.NewInt(int64(max)))
Panic(err)
return int(nBig.Int64())
}