-
Notifications
You must be signed in to change notification settings - Fork 101
/
utils.go
131 lines (110 loc) · 2.44 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
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
package main
import (
"fmt"
"os"
"strings"
)
// logging
func logRaw(format string, args ...interface{}) {
fmt.Printf(format+"\n", args...)
}
func logTitle(format string, args ...interface{}) {
logInfo(format, args...)
title := strings.Repeat("-", len(fmt.Sprintf(format, args...)))
if len(title) > 0 {
logInfo(title)
}
}
func logInfo(format string, args ...interface{}) {
if StartParams.Raw {
logRaw(format, args...)
} else {
logger.Printf(format, args...)
}
}
func logWarn(format string, args ...interface{}) {
format = "[WARN] " + format
if StartParams.Raw {
logRaw(format, args...)
} else {
logger.Printf(format, args...)
}
}
func logError(format string, args ...interface{}) {
format = "[ERROR] " + format
if StartParams.Raw {
logRaw(format, args...)
} else {
logger.Printf(format, args...)
}
}
func logFatal(format string, args ...interface{}) {
format = "[FATAL] " + format
if StartParams.Raw {
logRaw(format, args...)
} else {
logger.Printf(format, args...)
}
os.Exit(1)
}
func logFatalError(err error) {
if err != nil {
logFatal(err.Error())
}
}
// strings
type caseSensitivity int
const (
caseSensitive caseSensitivity = 0
caseInsensitive caseSensitivity = 1
)
func startsWith(str, prefix string, cs caseSensitivity) bool {
if cs == caseSensitive {
return strings.HasPrefix(str, prefix)
}
return strings.HasPrefix(strings.ToLower(str), strings.ToLower(prefix))
}
func startsWithAny(str string, prefixes []string, cs caseSensitivity) bool {
for _, prefix := range prefixes {
if startsWith(str, prefix, cs) {
return true
}
}
return false
}
func endsWith(str, postfix string, cs caseSensitivity) bool {
if cs == caseSensitive {
return strings.HasSuffix(str, postfix)
}
return strings.HasSuffix(strings.ToLower(str), strings.ToLower(postfix))
}
func endsWithAny(str string, postfixes []string, cs caseSensitivity) bool {
for _, postfix := range postfixes {
if endsWith(str, postfix, cs) {
return true
}
}
return false
}
// file
// Returns if file/dir in path exists.
func fileExists(path string) bool {
if len(path) == 0 {
return false
}
if _, err := os.Stat(path); os.IsNotExist(err) {
return false
}
return true
}
// data
func stringProperty(data map[string]interface{}, key string) (string, error) {
if value, ok := data[key]; ok {
if vStr, ok := value.(string); ok {
return vStr, nil
} else {
return "", fmt.Errorf("%s is not a string", key)
}
}
return "", nil
}