-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathtemplate.go
65 lines (56 loc) · 1.14 KB
/
template.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 goss
import (
"bytes"
"fmt"
"io/ioutil"
"log"
"os"
"strings"
"text/template"
)
func mkSlice(args ...interface{}) []interface{} {
return args
}
func readFile(f string) (string, error) {
b, err := ioutil.ReadFile(f)
if err != nil {
return "", err
}
return strings.TrimSpace(string(b)), nil
}
func getEnv(key string, def ...string) string {
val := os.Getenv(key)
if val == "" && len(def) > 0 {
return def[0]
}
return os.Getenv(key)
}
var funcMap = map[string]interface{}{
"mkSlice": mkSlice,
"readFile": readFile,
"getEnv": getEnv,
}
func NewTemplateFilter(varsFile string) func([]byte) []byte {
vars, err := varsFromFile(varsFile)
if err != nil {
fmt.Printf("Error: loading vars file '%s'\n%v\n", varsFile, err)
os.Exit(1)
}
tVars := &TmplVars{Vars: vars}
f := func(data []byte) []byte {
funcMap := funcMap
t := template.New("test").Funcs(template.FuncMap(funcMap))
tmpl, err := t.Parse(string(data))
if err != nil {
log.Fatal(err)
}
tmpl.Option("missingkey=error")
var doc bytes.Buffer
err = tmpl.Execute(&doc, tVars)
if err != nil {
log.Fatal(err)
}
return doc.Bytes()
}
return f
}