/
funcs.go
65 lines (53 loc) · 1.42 KB
/
funcs.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
package main
import (
"os"
"strconv"
"text/template"
"time"
log "github.com/Sirupsen/logrus"
)
// Funcs are the interpolation funcs that are available within interpolations.
var FuncGens = map[string]FuncGenerator{
"env": funcGenEnv,
"timestamp": funcGenTimestamp,
"var": funcGenVar,
}
// InitTime is the UTC time when this package was initialized. It is
// used as the timestamp for all configuration templates so that they
// match for a single build.
var InitTime time.Time
func init() {
InitTime = time.Now().UTC()
}
// FuncGenerator is a function that given a context generates a template
// function for the template.
type FuncGenerator func(*Context) interface{}
// Funcs returns the functions that can be used for interpolation given
// a context.
func Funcs(ctx *Context) template.FuncMap {
result := make(map[string]interface{})
for k, v := range FuncGens {
log.Debugf("adding %v handler func", k)
result[k] = v(ctx)
}
return template.FuncMap(result)
}
func funcGenEnv(ctx *Context) interface{} {
return func(k string) (string, error) {
log.Debugf("rendering env var for '%v'", k)
return os.Getenv(k), nil
}
}
func funcGenTimestamp(ctx *Context) interface{} {
return func() string {
return strconv.FormatInt(InitTime.Unix(), 10)
}
}
func funcGenVar(ctx *Context) interface{} {
return func(k string) string {
if ctx == nil || ctx.Vars == nil {
return ""
}
return ctx.Vars[k]
}
}