/
templating.go
90 lines (76 loc) · 1.9 KB
/
templating.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
// Copyright (c) 2016 Niklas Wolber
// This file is licensed under the MIT license.
// See the LICENSE file for more information.
package job
import (
"bytes"
"fmt"
"os"
"strings"
"text/template"
"time"
errs "github.com/pkg/errors"
)
// A TemplatingEngine can treat templating strings as defined by the Go
// text/template package. It uses information from the Config, Host, environment
// variables and the current time to replace place holders in the string.
type TemplatingEngine struct {
Config *Config
Host *Host
Env map[string]string
now func() time.Time
}
func getEnv() map[string]string {
env := make(map[string]string)
for _, e := range os.Environ() {
index := strings.Index(e, "=")
key, value := e[:index], e[index+1:]
env[key] = value
}
return env
}
func newTemplatingEngine(c *Config, h *Host) *TemplatingEngine {
return &TemplatingEngine{
Config: c,
Host: h,
Env: getEnv(),
now: time.Now,
}
}
// Interpolate tries to replace all place holders present in templ with
// information stored in the TemplatingEngine.
func (t *TemplatingEngine) Interpolate(templ string) (string, error) {
var buf bytes.Buffer
funcMap := template.FuncMap{
"date": func(t time.Time) string {
return fmt.Sprintf("%04d-%02d-%02d", t.Year(), t.Month(), t.Day())
},
"time": func(t time.Time) string {
return fmt.Sprintf("%02d:%02d:%02d", t.Hour(), t.Minute(), t.Second())
},
"now": func() time.Time {
return t.now()
},
}
tt := template.New("").Funcs(funcMap)
tt, err := tt.Parse(templ)
if err != nil {
return "", errs.Wrap(err, "failed to parse template")
}
data := struct {
Config *Config
Host *Host
Env map[string]string
Now time.Time
}{
Config: t.Config,
Host: t.Host,
Env: t.Env,
Now: time.Now(),
}
err = tt.Execute(&buf, data)
if err != nil {
return "", errs.Wrap(err, "failed to execute template")
}
return buf.String(), nil
}