feat templater: Fail if values are missing
Golang's template package now has an option for failing if template variables are missing: https://golang.org/pkg/text/template/#Template.Option This updates the templater code to make use of that option and return the errors encountered during templating. This fixes #1
This commit is contained in:
parent
45aee8257f
commit
3b0f41e71d
3 changed files with 21 additions and 1 deletions
|
@ -16,6 +16,8 @@ import (
|
||||||
"github.com/tazjin/kontemplate/util"
|
"github.com/tazjin/kontemplate/util"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
const failOnMissingKeys string = "missingkey=error"
|
||||||
|
|
||||||
// Error that is caused by non-existent template files being specified
|
// Error that is caused by non-existent template files being specified
|
||||||
type TemplateNotFoundError struct {
|
type TemplateNotFoundError struct {
|
||||||
meep.AllTraits
|
meep.AllTraits
|
||||||
|
@ -78,7 +80,7 @@ func processFiles(c *context.Context, rs *context.ResourceSet, rp string, files
|
||||||
}
|
}
|
||||||
|
|
||||||
func templateFile(c *context.Context, rs *context.ResourceSet, filename string) (string, error) {
|
func templateFile(c *context.Context, rs *context.ResourceSet, filename string) (string, error) {
|
||||||
tpl, err := template.New(path.Base(filename)).Funcs(templateFuncs()).ParseFiles(filename)
|
tpl, err := template.New(path.Base(filename)).Funcs(templateFuncs()).Option(failOnMissingKeys).ParseFiles(filename)
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return "", meep.New(
|
return "", meep.New(
|
||||||
|
|
|
@ -3,6 +3,7 @@ package templater
|
||||||
import (
|
import (
|
||||||
"github.com/tazjin/kontemplate/context"
|
"github.com/tazjin/kontemplate/context"
|
||||||
"reflect"
|
"reflect"
|
||||||
|
"strings"
|
||||||
"testing"
|
"testing"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
@ -136,3 +137,19 @@ func TestApplyLimitsExcludeIncludePrecedence(t *testing.T) {
|
||||||
t.Fail()
|
t.Fail()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestFailOnMissingKeys(t *testing.T) {
|
||||||
|
ctx := context.Context{}
|
||||||
|
resourceSet := context.ResourceSet{}
|
||||||
|
|
||||||
|
_, err := templateFile(&ctx, &resourceSet, "testdata/test-template.txt")
|
||||||
|
|
||||||
|
if err == nil {
|
||||||
|
t.Errorf("Template with missing keys should have failed.\n")
|
||||||
|
t.Fail()
|
||||||
|
}
|
||||||
|
|
||||||
|
if !strings.Contains(err.Error(), "map has no entry for key \"testName\"") {
|
||||||
|
t.Errorf("Templating failed with unexpected error: %v\n", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
1
templater/testdata/test-template.txt
vendored
Normal file
1
templater/testdata/test-template.txt
vendored
Normal file
|
@ -0,0 +1 @@
|
||||||
|
Template for test {{ .testName }}
|
Loading…
Reference in a new issue