-
-
Notifications
You must be signed in to change notification settings - Fork 151
/
helpers.go
234 lines (203 loc) · 5.19 KB
/
helpers.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
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
package integram
import (
"bytes"
"crypto/md5"
"encoding/base64"
"encoding/binary"
"fmt"
"github.com/requilence/url"
log "github.com/sirupsen/logrus"
"github.com/vova616/xxhash"
"io/ioutil"
"math/rand"
"regexp"
"runtime"
"strings"
"time"
)
const letterBytes = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-0123456789"
const (
letterIdxBits = 6 // 6 bits to represent a letter index
letterIdxMask = 1<<letterIdxBits - 1 // All 1-bits, as many as letterIdxBits
)
var (
dunno = []byte("???")
centerDot = []byte("·")
dot = []byte(".")
slash = []byte("/")
tzLocations = make(map[string]*time.Location)
)
func tzLocation(name string) *time.Location {
if name == "" {
name = "UTC"
}
if val, ok := tzLocations[name]; ok {
if val == nil {
return tzLocation("UTC")
}
return val
}
l, err := time.LoadLocation(name)
tzLocations[name] = l
if err != nil || l == nil {
log.WithField("tz", name).Error("Can't find TZ")
return tzLocation("UTC")
}
return l
}
// source returns a space-trimmed slice of the n'th line.
func source(lines [][]byte, n int) []byte {
n-- // in stack trace, lines are 1-indexed but our array is 0-indexed
if n < 0 || n >= len(lines) {
return dunno
}
return bytes.TrimSpace(lines[n])
}
// function returns, if possible, the name of the function containing the PC.
func function(pc uintptr) []byte {
fn := runtime.FuncForPC(pc)
if fn == nil {
return dunno
}
name := []byte(fn.Name())
// The name includes the path name to the package, which is unnecessary
// since the file name is already included. Plus, it has center dots.
// That is, we see
// runtime/debug.*T·ptrmethod
// and want
// *T.ptrmethod
// Also the package path might contains dot (e.g. code.google.com/...),
// so first eliminate the path prefix
if lastslash := bytes.LastIndex(name, slash); lastslash >= 0 {
name = name[lastslash+1:]
}
if period := bytes.Index(name, dot); period >= 0 {
name = name[period+1:]
}
name = bytes.Replace(name, centerDot, dot, -1)
return name
}
// stack returns a nicely formated stack frame, skipping skip frames
func stack(skip int) []byte {
buf := new(bytes.Buffer) // the returned data
// As we loop, we open files and read them. These variables record the currently
// loaded file.
var lines [][]byte
var lastFile string
for i := skip; ; i++ { // Skip the expected number of frames
pc, file, line, ok := runtime.Caller(i)
if !ok {
break
}
// Print this much at least. If we can't find the source, it won't show.
fmt.Fprintf(buf, "%s:%d (0x%x)\n", file, line, pc)
if file != lastFile {
data, err := ioutil.ReadFile(file)
if err != nil {
continue
}
lines = bytes.Split(data, []byte{'\n'})
lastFile = file
}
fmt.Fprintf(buf, "\t%s: %s\n", function(pc), source(lines, line))
}
return buf.Bytes()
}
func randomInRange(min, max int) int {
rand.Seed(time.Now().UnixNano())
return rand.Intn(max-min) + min
}
// SliceContainsString returns true if []string contains string
func SliceContainsString(s []string, e string) bool {
for _, a := range s {
if a == e {
return true
}
}
return false
}
func compactHash(s string) string {
a := md5.Sum([]byte(s))
return base64.RawURLEncoding.EncodeToString(a[:])
}
func checksumString(s string) string {
b := make([]byte, 4)
cs := xxhash.Checksum32([]byte(s))
binary.LittleEndian.PutUint32(b, cs)
return base64.RawURLEncoding.EncodeToString(b)
}
type strGenerator interface {
Get(n int) string
}
type rndStrGenerator struct {
}
func (r rndStrGenerator) Get(n int) string {
rand.Seed(time.Now().UTC().UnixNano())
b := make([]byte, n)
for i := 0; i < n; {
if idx := int(rand.Int63() & letterIdxMask); idx < len(letterBytes) {
b[i] = letterBytes[idx]
i++
}
}
return string(b)
}
var rndStr = strGenerator(rndStrGenerator{})
// URLMustParse returns url.URL from static string. Don't use it with a dynamic param
func URLMustParse(s string) *url.URL {
u, err := url.Parse(s)
if err != nil {
log.Errorf("Expected URL to parse: %q, got error: %v", s, err)
}
return u
}
func getBaseURL(s string) (*url.URL, error) {
u, err := url.Parse(s)
if err != nil {
return nil, err
}
return &url.URL{Scheme: u.Scheme, Host: u.Host}, nil
}
func getHostFromURL(s string) string {
h := strings.SplitAfterN(s, "://", 2)
if len(h) > 1 {
m := strings.SplitN(h[1], "/", 2)
return m[0]
}
return ""
}
func Logger() *log.Logger {
return log.StandardLogger()
}
var currentGitHead string
var refRE = regexp.MustCompile(`ref: ([^\n^\s]+)`)
// GetVersion returns the current HEAD git commit if .git exists
func GetVersion() string {
if currentGitHead == "" {
b, err := ioutil.ReadFile(".git/HEAD")
if err != nil {
currentGitHead = "unknown"
return currentGitHead
}
p := refRE.FindStringSubmatch(string(b))
if len(p) < 2 {
currentGitHead = string(b)
return currentGitHead
}
b, err = ioutil.ReadFile(".git/" + p[1])
if err != nil {
currentGitHead = p[1]
return currentGitHead
}
currentGitHead = string(b)
}
return currentGitHead
}
// GetVersion returns the current HEAD git commit(first 7 symbols) if .git exists
func GetShortVersion() string {
v := GetVersion()
if len(v) > 7 {
return v[0:7]
}
return v
}