-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathgotil.go
319 lines (280 loc) · 7.16 KB
/
gotil.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
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
package gotil
import (
"bufio"
"bytes"
"fmt"
"io"
"math/rand"
"net"
"os"
"os/exec"
"os/user"
"path/filepath"
"regexp"
"strings"
"time"
"github.com/akutz/goof"
"github.com/kardianos/osext"
)
const (
trimPattern = `(?s)^\s*(.*?)\s*$`
networkAdressPattern = `(?i)^((?:(?:tcp|udp|ip)[46]?)|(?:unix(?:gram|packet)?))://(.+)$`
letterBytes = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
letterIndexBits = 6
letterIndexMask = 1<<letterIndexBits - 1
letterIndexMax = 63 / letterIndexBits
)
var (
homeDir string
homeDirSet bool
trimRx *regexp.Regexp
netAddrRx *regexp.Regexp
)
func init() {
trimRx = regexp.MustCompile(trimPattern)
netAddrRx = regexp.MustCompile(networkAdressPattern)
}
// StringInSlice returns a flag indicating whether or not a provided string
// exists in a string slice. The string comparison is case-insensitive.
func StringInSlice(a string, list []string) bool {
for _, b := range list {
if strings.ToLower(a) == strings.ToLower(b) {
return true
}
}
return false
}
// StringInSliceCS returns a flag indicating whether or not a provided string
// exists in a string slice. The string comparison is case-sensitive.
func StringInSliceCS(a string, list []string) bool {
for _, b := range list {
if a == b {
return true
}
}
return false
}
// WriteStringToFile writes the string to the file at the provided path.
func WriteStringToFile(text, path string) error {
f, err := os.OpenFile(path, os.O_CREATE|os.O_WRONLY, 0644)
defer f.Close()
if err != nil {
return err
}
f.WriteString(text)
return nil
}
// ReadFileToString reads the file at the provided path to a string.
func ReadFileToString(path string) (string, error) {
f, err := os.Open(path)
if err != nil {
return "", err
}
defer f.Close()
scanner := bufio.NewScanner(f)
scanner.Scan()
return scanner.Text(), nil
}
// IsDirEmpty returns a flag indicating whether or not a directory has any
// child objects such as files or directories in it.
func IsDirEmpty(name string) (bool, error) {
f, err := os.Open(name)
if err != nil {
return false, err
}
defer f.Close()
_, err = f.Readdir(1)
if err == io.EOF {
return true, nil
}
return false, err
}
func lineReader(f func() (io.Reader, func(), error)) (<-chan string, error) {
r, done, err := f()
if err != nil {
return nil, err
}
c := make(chan string)
go func() {
if r != nil {
s := bufio.NewScanner(r)
for s.Scan() {
c <- s.Text()
}
}
close(c)
if done != nil {
done()
}
}()
return c, nil
}
// LineReader returns a channel that reads the contents of a reader
// line-by-line.
func LineReader(r io.Reader) (<-chan string, error) {
return lineReader(func() (io.Reader, func(), error) { return r, nil, nil })
}
// LineReaderFrom returns a channel that reads the contents of a file
// line-by-line.
func LineReaderFrom(path string) (<-chan string, error) {
return lineReader(func() (io.Reader, func(), error) {
if !FileExists(path) {
return nil, nil, nil
}
f, err := os.Open(path)
if err != nil {
return nil, nil, err
}
return f, func() { f.Close() }, nil
})
}
// FileExists returns a flag indicating whether a provided file path exists.
func FileExists(filePath string) bool {
if _, err := os.Stat(filePath); !os.IsNotExist(err) {
return true
}
return false
}
// FileExistsInPath returns a flag indicating whether the provided file exists
// in the current path.
func FileExistsInPath(fileName string) bool {
_, err := exec.LookPath(fileName)
return err == nil
}
// GetPathParts returns the absolute directory path, the file name, and the
// absolute path of the provided path string.
func GetPathParts(path string) (dirPath, fileName, absPath string) {
lookup, lookupErr := exec.LookPath(path)
if lookupErr == nil {
path = lookup
}
absPath, _ = filepath.Abs(path)
dirPath = filepath.Dir(absPath)
fileName = filepath.Base(absPath)
return
}
// GetThisPathParts returns the same information as GetPathParts for the
// current executable.
func GetThisPathParts() (dirPath, fileName, absPath string) {
exeFile, _ := osext.Executable()
return GetPathParts(exeFile)
}
// RandomString generates a random set of characters with the given lenght.
func RandomString(length int) string {
src := rand.NewSource(time.Now().UnixNano())
b := make([]byte, length)
for i, cache, remain := length-1, src.Int63(), letterIndexMax; i >= 0; {
if remain == 0 {
cache, remain = src.Int63(), letterIndexMax
}
if idx := int(cache & letterIndexMask); idx < len(letterBytes) {
b[i] = letterBytes[idx]
i--
}
cache >>= letterIndexBits
remain--
}
return string(b)
}
// GetLocalIP returns the non loopback local IP of the host
func GetLocalIP() (ip string) {
addrs, _ := net.InterfaceAddrs()
for _, address := range addrs {
// check the address type and if it is not a loopback the display it
if ipnet, ok := address.(*net.IPNet); ok && !ipnet.IP.IsLoopback() {
if ipnet.IP.To4() != nil {
ip = ipnet.IP.String()
break
}
}
}
return
}
// ParseAddress parses a standard golang network address and returns the
// protocol and path.
func ParseAddress(addr string) (proto string, path string, err error) {
m := netAddrRx.FindStringSubmatch(addr)
if m == nil {
return "", "", goof.WithField("address", addr, "invalid address")
}
return m[1], m[2], nil
}
// Trim removes all leading and trailing whitespace, including tab, newline,
// and carriage return characters.
func Trim(text string) string {
return trimRx.FindStringSubmatch(text)[1]
}
// WriteIndentedN indents all lines n spaces.
func WriteIndentedN(w io.Writer, b []byte, n int) error {
s := bufio.NewScanner(bytes.NewReader(b))
if !s.Scan() {
return nil
}
l := s.Text()
for {
for x := 0; x < n; x++ {
if _, err := fmt.Fprint(w, " "); err != nil {
return err
}
}
if _, err := fmt.Fprint(w, l); err != nil {
return err
}
if !s.Scan() {
break
}
l = s.Text()
if _, err := fmt.Fprint(w, "\n"); err != nil {
return err
}
}
return nil
}
// WriteIndented indents all lines four spaces.
func WriteIndented(w io.Writer, b []byte) error {
return WriteIndentedN(w, b, 4)
}
// HomeDir returns the home directory of the user that owns the current process.
func HomeDir() string {
if homeDirSet {
return homeDir
}
if user, err := user.Current(); err == nil {
homeDir = user.HomeDir
}
homeDirSet = true
return homeDir
}
const (
minTCPPort = 0
maxTCPPort = 65535
maxReservedTCPPort = 1024
maxRandTCPPort = maxTCPPort - (maxReservedTCPPort + 1)
)
var (
tcpPortRand = rand.New(rand.NewSource(time.Now().UnixNano()))
)
// IsTCPPortAvailable returns a flag indicating whether or not a TCP port is
// available.
func IsTCPPortAvailable(port int) bool {
if port < minTCPPort || port > maxTCPPort {
return false
}
conn, err := net.Listen("tcp", fmt.Sprintf("127.0.0.1:%d", port))
if err != nil {
return false
}
conn.Close()
return true
}
// RandomTCPPort gets a free, random TCP port between 1025-65535. If no free
// ports are available -1 is returned.
func RandomTCPPort() int {
for i := maxReservedTCPPort; i < maxTCPPort; i++ {
p := tcpPortRand.Intn(maxRandTCPPort) + maxReservedTCPPort + 1
if IsTCPPortAvailable(p) {
return p
}
}
return -1
}