/
functions.go
48 lines (41 loc) · 1010 Bytes
/
functions.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
package semo
import (
"crypto/sha256"
"fmt"
"math/rand"
"regexp"
"strings"
"text/template"
"time"
)
var defaultFuncMap = template.FuncMap{
"toUpper": strings.ToUpper,
"toLower": strings.ToLower,
"noWhitespace": removeWhitespace,
"runID": runID,
}
// A random string that is constant per semo
// invocation
var runIdentifier *string
// Remove whitespace and replace it with
// an underscore
func removeWhitespace(str string) string {
re := regexp.MustCompile(`\s`)
return re.ReplaceAllString(str, "_")
}
// Returns the id of this run with a maximum
// length of maxLen characters.
// If no id has been set, generate a new one
func runID(maxLen int) string {
if runIdentifier == nil {
baseString := fmt.Sprintf("%d%d",
time.Now().UnixNano(), rand.Uint32())
sum := sha256.Sum256([]byte(baseString))
idHash := fmt.Sprintf("%x", sum)
runIdentifier = &idHash
}
if maxLen > len(*runIdentifier) {
maxLen = len(*runIdentifier)
}
return (*runIdentifier)[:maxLen]
}