-
Notifications
You must be signed in to change notification settings - Fork 7
/
template.go
219 lines (187 loc) · 4.53 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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
package main
import (
"bytes"
"fmt"
"log"
"net/url"
"os"
"path/filepath"
"strconv"
"strings"
"syscall"
"text/template"
)
type TemplateContext struct {
env, secrets map[string]string
}
func GetEnvMap() map[string]string {
env := make(map[string]string)
for _, i := range os.Environ() {
sep := strings.Index(i, "=")
env[i[0:sep]] = i[sep+1:]
}
return env
}
//
// getenv template function
//
// '{{concat "P" "WD" | getenv}}' will print $PWD
//
func GetEnv(v string) string {
return GetEnvMap()[v]
}
//
// .Env.VAR lookup from template context
//
func (c *TemplateContext) Env() map[string]string {
if c.env != nil {
return c.env
}
c.env = GetEnvMap()
return c.env
}
//
// Make secrets available under .Secret.VARNAME in the TemplateContext
//
func (c *TemplateContext) Secret() map[string]string {
if c.secrets != nil {
return c.secrets
}
c.secrets = getSecrets()
return c.secrets
}
func exists(path string) (bool, error) {
_, err := os.Stat(path)
if err == nil {
return true, nil
}
if os.IsNotExist(err) {
return false, nil
}
return false, err
}
func contains(item map[string]string, key string) bool {
if _, ok := item[key]; ok {
return true
}
return false
}
func defaultValue(args ...interface{}) (string, error) {
if len(args) == 0 {
return "", fmt.Errorf("default called with no values!")
}
if len(args) > 0 {
if args[0] != nil {
return args[0].(string), nil
}
}
if len(args) > 1 {
if args[1] == nil {
return "", fmt.Errorf("default called with nil default value!")
}
if _, ok := args[1].(string); !ok {
return "", fmt.Errorf("default is not a string value. hint: surround it w/ double quotes.")
}
return args[1].(string), nil
}
return "", fmt.Errorf("default called with no default value")
}
func parseUrl(rawurl string) *url.URL {
u, err := url.Parse(rawurl)
if err != nil {
log.Fatalf("unable to parse url %s: %s", rawurl, err)
}
return u
}
func add(arg1, arg2 int) int {
return arg1 + arg2
}
func concat(args ...string) (s string) {
s = ""
for _, v := range args {
s = s + v
}
return
}
func sequence(firstS, lastS string) []string {
// return a sequence of strings from first to last (inclusive)
// `sequence 3 5` returns ["3", "4", "5"]
first, _ := strconv.Atoi(firstS)
last, _ := strconv.Atoi(lastS)
if last < first {
last, first = 0, 0
}
sequence := make([]string, (last - first + 1))
for i := 0; i + first <= last; i++ {
sequence[i] = strconv.Itoa(i + first)
}
return sequence
}
var funcMap = template.FuncMap{
"contains": contains,
"exists": exists,
"split": strings.Split,
"replace": strings.Replace,
"default": defaultValue,
"parseUrl": parseUrl,
"atoi": strconv.Atoi,
"add": add,
"concat": concat,
"sequence": sequence,
"N": sequence,
"getenv": GetEnv,
}
//
// Execute the string_template under the TemplateContext, and
// return the result as a string
//
func string_template_eval(string_template string) string {
var result bytes.Buffer
t := template.New("String Template").Funcs(funcMap)
t, err := t.Parse(string_template)
if err != nil {
log.Fatalf("unable to parse template: %s", err)
}
err = t.Execute(&result, &TemplateContext{})
if err != nil {
log.Fatalf("template error: %s\n", err)
}
return result.String()
}
//
// Execute the template at templatePath under the TemplateContext and write it to destPath
//
func generateFile(templatePath, destPath string) bool {
tmpl := template.New(filepath.Base(templatePath)).Funcs(funcMap)
if len(delims) > 0 {
tmpl = tmpl.Delims(delims[0], delims[1])
}
tmpl, err := tmpl.ParseFiles(templatePath)
if err != nil {
log.Fatalf("unable to parse template: %s", err)
}
dest := os.Stdout
if destPath != "" {
dest, err = os.Create(destPath)
if err != nil {
log.Fatalf("unable to create %s", err)
}
defer dest.Close()
if verboseFlag {
log.Printf("Template %s --> %s\n", templatePath, destPath)
}
}
err = tmpl.ExecuteTemplate(dest, filepath.Base(templatePath), &TemplateContext{})
if err != nil {
log.Fatalf("template error: %s\n", err)
}
if fi, err := os.Stat(destPath); err == nil {
if err := dest.Chmod(fi.Mode()); err != nil {
log.Fatalf("unable to chmod temp file: %s\n", err)
}
if err := dest.Chown(int(fi.Sys().(*syscall.Stat_t).Uid), int(fi.Sys().(*syscall.Stat_t).Gid)); err != nil {
log.Fatalf("unable to chown temp file: %s\n", err)
}
}
return true
}