/
template.go
91 lines (82 loc) · 2.01 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
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
91
package main
import (
"fmt"
"gopkg.in/BlueDragonX/go-hash.v1"
"io/ioutil"
"os"
"path/filepath"
"strings"
"text/template"
)
// Describes a template as part of a watcher.
type Template struct {
Src string
Dest string
}
// Return true if one file differs from another.
func (t *Template) differs(fileA, fileB string) bool {
var err error
var hashA, hashB string
if hashA, err = hash.File(fileA); err != nil {
logger.Debugf("unable to hash file %s", fileA)
return true
}
if hashB, err = hash.File(fileB); err != nil {
logger.Debugf("unable to hash file %s", fileB)
return true
}
return hashA != hashB
}
// Render the template to a temporary and return true if the original was changed.
func (t *Template) Render(context interface{}) (changed bool, err error) {
// create the destination directory
dir := filepath.Dir(t.Dest)
if err = os.MkdirAll(dir, 0777); err != nil {
return
}
// create a temp file to write
var tmp *os.File
prefix := fmt.Sprintf(".%s-", filepath.Base(t.Dest))
if tmp, err = ioutil.TempFile(dir, prefix); err != nil {
return
}
defer func() {
tmp.Close()
if !changed || err != nil {
os.Remove(tmp.Name())
}
}()
// add functions to the templates
funcs := template.FuncMap{
"replace": strings.Replace,
"addrHost": AddrHost,
"addrPort": AddrPort,
"urlScheme": URLScheme,
"urlUsername": URLUsername,
"urlPassword": URLPassword,
"urlHost": URLHost,
"urlPath": URLPath,
"urlRawQuery": URLRawQuery,
"urlQuery": URLQuery,
"urlFragment": URLFragment,
"json": JSON,
}
// render the template to the temp file
var tpl *template.Template
name := filepath.Base(t.Src)
if tpl, err = template.New(name).Funcs(funcs).ParseFiles(t.Src); err != nil {
return
}
if err = tpl.Execute(tmp, context); err != nil {
return
}
tmp.Close()
// return if the old and new files are the same
changed = t.differs(t.Dest, tmp.Name())
if !changed {
return
}
// replace the old file with the new one
err = os.Rename(tmp.Name(), t.Dest)
return
}