Skip to content

Separate newTemplate from generateFile #63

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 9 additions & 4 deletions template.go
Original file line number Diff line number Diff line change
Expand Up @@ -283,9 +283,8 @@ func trimSuffix(suffix, s string) string {
return strings.TrimSuffix(s, suffix)
}

func generateFile(config Config, containers Context) bool {
templatePath := config.Template
tmpl, err := template.New(filepath.Base(templatePath)).Funcs(template.FuncMap{
func newTemplate(name string) *template.Template {
tmpl := template.New(name).Funcs(template.FuncMap{
"closest": arrayClosest,
"coalesce": coalesce,
"contains": contains,
Expand All @@ -312,7 +311,13 @@ func generateFile(config Config, containers Context) bool {
"whereNotExist": whereNotExist,
"whereAny": whereAny,
"whereAll": whereAll,
}).ParseFiles(templatePath)
})
return tmpl
}

func generateFile(config Config, containers Context) bool {
templatePath := config.Template
tmpl, err := newTemplate(filepath.Base(templatePath)).ParseFiles(templatePath)
if err != nil {
log.Fatalf("unable to parse template: %s", err)
}
Expand Down
19 changes: 8 additions & 11 deletions template_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"encoding/json"
"reflect"
"testing"
"text/template"
)

func TestContains(t *testing.T) {
Expand All @@ -27,20 +28,16 @@ func TestKeys(t *testing.T) {
expected: "demo.local",
}

k, err := keys(env)
if err != nil {
t.Fatalf("Error fetching keys: %v", err)
}
vk := reflect.ValueOf(k)
if vk.Kind() == reflect.Invalid {
t.Fatalf("Got invalid kind for keys: %v", vk)
}
const text = "{{range (keys $)}}{{.}}{{end}}"
tmpl := template.Must(newTemplate("keys-test").Parse(text))

if len(env) != vk.Len() {
t.Fatalf("Incorrect key count; expected %s, got %s", len(env), vk.Len())
var b bytes.Buffer
err := tmpl.ExecuteTemplate(&b, "keys-test", env)
if err != nil {
t.Fatalf("Error executing template: %v", err)
}

got := vk.Index(0).Interface()
got := b.String()
if expected != got {
t.Fatalf("Incorrect key found; expected %s, got %s", expected, got)
}
Expand Down