/
utils.go
81 lines (73 loc) · 1.67 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
package utils
import (
"crypto/sha1"
"encoding/hex"
"io"
"os"
"github.com/pkg/errors"
"github.com/sirupsen/logrus"
)
// StringInSlice checks for string in slice
func StringInSlice(str string, list []string) bool {
for _, v := range list {
if v == str {
return true
}
}
return false
}
// StringSlice makes a slice str to str pointers
func StringSlice(strs []string) []*string {
res := make([]*string, len(strs))
for i := 0; i < len(strs); i++ {
res[i] = &(strs[i])
}
return res
}
// IsLetter checks if string is letter
func IsLetter(s string) bool {
for _, r := range s {
if (r < 'a' || r > 'z') && (r < 'A' || r > 'Z') {
return false
}
}
return true
}
// GetFileSHA1 returns a files SHA1
func GetFileSHA1(filePath string) (string, error) {
var resSha1 string
file, err := os.Open(filePath)
if err != nil {
return "", errors.Wrap(err, "Failed to open file")
}
defer file.Close()
hash := sha1.New()
if _, err := io.Copy(hash, file); err != nil {
return "", err
}
hashInBytes := hash.Sum(nil)[:20]
resSha1 = hex.EncodeToString(hashInBytes)
return resSha1, nil
}
// VerifyArgsOrRun will check args length then call first defined function or 2nd to handle error
func VerifyArgsOrRun(args []string, equalTo int, call ...func()) {
if len(args) > 0 || equalTo > 0 && len(args) == equalTo {
call[0]()
} else {
if call[1] != nil {
call[1]()
} else {
logrus.Fatalln("args count not valid")
}
}
}
// FilterMap items from array based on test functions
func FilterMap(ms map[string][]string, test func(string) bool) (ret map[string][]string) {
ret = make(map[string][]string)
for s, ss := range ms {
if test(s) {
ret[s] = ss
}
}
return
}