-
Notifications
You must be signed in to change notification settings - Fork 2
/
tools.go
84 lines (74 loc) · 2.12 KB
/
tools.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
package main
import (
"crypto/md5"
"encoding/hex"
"fmt"
"regexp"
"strconv"
"strings"
)
const stringWordSeparators = "[ \t\n,.;:\\(\\)\\[\\]{}'\"/\\\\!\\?<>@#|*+-=]"
// IsValidTokenName returns true is argument use only allowed chars for a token
func IsValidTokenName(token string) bool {
match, _ := regexp.MatchString("^[A-Za-z0-9_]+$", token)
return match
}
// IsAllUpper returns true if string is all uppercase
func IsAllUpper(str string) bool {
return str == strings.ToUpper(str)
}
// MD5Hash will hash input text and return MD5 sum
func MD5Hash(text string) string {
hasher := md5.New()
hasher.Write([]byte(text))
return hex.EncodeToString(hasher.Sum(nil))
}
// InterfaceValueToString converts most interface types to string
func InterfaceValueToString(iv interface{}) string {
switch iv.(type) {
case int:
return fmt.Sprintf("%d", iv.(int))
case int32:
return fmt.Sprintf("%d", iv.(int32))
case int64:
return strconv.FormatInt(iv.(int64), 10)
case float32:
return fmt.Sprintf("%f", iv.(float32))
case float64:
return strconv.FormatFloat(iv.(float64), 'f', -1, 64)
case string:
return iv.(string)
case bool:
return strconv.FormatBool(iv.(bool))
}
return "INVALID_TYPE"
}
// StringFindVariables returns a deduplicated slice of all "variables" ($test)
// in the string
func StringFindVariables(str string) []string {
re := regexp.MustCompile("\\$([a-zA-Z0-9_]+)(" + stringWordSeparators + "|$)")
all := re.FindAllStringSubmatch(str, -1)
// deduplicate using a map
varMap := make(map[string]bool)
for _, v := range all {
varMap[v[1]] = true
}
// map to slice
res := []string{}
for name := range varMap {
res = append(res, name)
}
return res
}
// StringExpandVariables expands "variables" ($test, for instance) in str
// and returns a new string
func StringExpandVariables(str string, variables map[string]interface{}) string {
vars := StringFindVariables(str)
for _, v := range vars {
if val, exists := variables[v]; exists == true {
re := regexp.MustCompile("\\$" + v + "(" + stringWordSeparators + "|$)")
str = re.ReplaceAllString(str, InterfaceValueToString(val)+"${1}")
}
}
return str
}