-
Notifications
You must be signed in to change notification settings - Fork 5
/
template.go
214 lines (191 loc) · 4.99 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
// Copyright © 2015 Victor Antonovich <[email protected]>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package main
import (
"bytes"
"fmt"
"io/ioutil"
"os"
"path/filepath"
gotemplate "text/template"
"strings"
"github.com/Masterminds/sprig/v3"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)
const (
DefaultNamespace = metav1.NamespaceDefault
DefaultSelector = ""
)
type Template struct {
// Template descriptor from configuration
desc *TemplateDescriptor
// Template name (base file name)
name string
// Go template to render
template *gotemplate.Template
// Template last output (in case of successfully rendered template)
lastOutput string
}
func newTemplate(cfg *Config, dm *DependencyManager, d *TemplateDescriptor) (*Template, error) {
// Template name
name := filepath.Base(d.Path)
// Get last template output, if present
o, err := ioutil.ReadFile(d.Output)
if err != nil {
o = nil
}
// Read template data
data, err := ioutil.ReadFile(d.Path)
if err != nil {
return nil, err
}
s := string(data)
// Create Go template from read data
template, err := gotemplate.New(name).Delims(cfg.LeftDelimiter, cfg.RightDelimiter).Funcs(funcMap(dm)).Parse(s)
if err != nil {
return nil, err
}
// Create template
return &Template{
desc: d,
name: name,
template: template,
lastOutput: string(o),
}, nil
}
func newTemplatesFromConfig(cfg *Config, dm *DependencyManager) ([]*Template, error) {
templates := make([]*Template, 0, len(cfg.TemplateDescriptors))
for _, d := range cfg.TemplateDescriptors {
t, err := newTemplate(cfg, dm, d)
if err != nil {
return nil, err
}
templates = append(templates, t)
}
return templates, nil
}
func (t *Template) Process(dryRun bool) (bool, error) {
if r, err := t.Render(); err == nil {
if changed := !(r == t.lastOutput); changed {
// Template output changed
if !dryRun {
if err := t.Write([]byte(r)); err != nil {
// Can't write template output
return false, err
}
}
t.lastOutput = r
return true, nil
}
// Template output not changed
return false, nil
} else {
// Can't render template
return false, err
}
}
func (t *Template) Write(content []byte) error {
dir := filepath.Dir(t.desc.Output)
if _, err := os.Stat(t.desc.Output); os.IsNotExist(err) {
// Output file does not exist, create intermediate dirs and write directly
if err := os.MkdirAll(dir, 0755); err != nil {
return err
}
// TODO file mode from config
if err := ioutil.WriteFile(t.desc.Output, content, 0644); err != nil {
return err
}
} else {
// Output file exist, update atomically using temp file
var f *os.File
if f, err = ioutil.TempFile(dir, t.name); err != nil {
return err
}
defer UnlinkQuietly(f.Name())
// Write template output to temp file
if _, err := f.Write(content); err != nil {
return err
}
if err := f.Sync(); err != nil {
return err
}
if err := f.Close(); err != nil {
return err
}
// TODO file mode from config
if err := os.Chmod(f.Name(), 0644); err != nil {
return err
}
// Rename temp file to output file
if err := os.Rename(f.Name(), t.desc.Output); err != nil {
return err
}
}
return nil
}
func (t *Template) Render() (string, error) {
// Render template to buffer
buf := new(bytes.Buffer)
if err := t.template.Execute(buf, nil); err != nil {
return "", err
}
return buf.String(), nil
}
func funcMap(dm *DependencyManager) gotemplate.FuncMap {
f := gotemplate.FuncMap{
// Legacy helper functions
"toLower": strings.ToLower,
"toUpper": strings.ToUpper,
"toTitle": strings.Title,
"trimSpace": strings.TrimSpace,
}
// Kubernetes objects functions
for k, v := range kubeObjectsFuncMap(dm) {
f[k] = v
}
// Sprig helper functions
for k, v := range sprig.FuncMap() {
f[k] = v
}
return f
}
// Parse template tag with max 1 argument - selector
func parseSelector(s ...string) (string, error) {
selector := DefaultSelector
switch len(s) {
case 0:
break
case 1:
selector = s[0]
default:
return "", fmt.Errorf("expected max 1 argument, got %d", len(s))
}
return selector, nil
}
// Parse template tag with max 2 arguments - selector and namespace (in given order)
func parseNamespaceSelector(s ...string) (string, string, error) {
namespace, selector := DefaultNamespace, DefaultSelector
switch len(s) {
case 0:
break
case 1:
selector = s[0]
case 2:
selector = s[0]
namespace = s[1]
default:
return "", "", fmt.Errorf("expected max 2 arguments, got %d", len(s))
}
return namespace, selector, nil
}