diff --git a/pkg/engine/engine.go b/pkg/engine/engine.go index eb022847..6b46b0ee 100644 --- a/pkg/engine/engine.go +++ b/pkg/engine/engine.go @@ -3,6 +3,7 @@ package engine import ( "errors" "fmt" + "path/filepath" "strings" "text/template" ) @@ -10,6 +11,8 @@ import ( type Engine struct { } +const TEMPLATE_EXT = ".tmpl" + func (e Engine) Render(templates map[string][]byte, values map[string]interface{}) (map[string][]byte, error) { t := template.New("gotpl") t.Funcs(funcMap()) @@ -17,29 +20,37 @@ func (e Engine) Render(templates map[string][]byte, values map[string]interface{ rendered := make(map[string][]byte) for name, data := range templates { - _, err := t.New(name).Parse(string(data)) - if err != nil { - // TODO: Inner error message includes prefix "template: ", which does not good when printing this error - return nil, fmt.Errorf("failed to parse template: %w", err) - } - - var buf strings.Builder - if err := t.ExecuteTemplate(&buf, name, values); err != nil { - // TODO: Inner error message includes prefix "template: ", which does not good when printing this error - return nil, fmt.Errorf("failed to execute template: %w", err) - } - - output := buf.String() - - // If template uses variables which were undefined, gotpl will insert "" - if strings.Contains(output, "") { - // TODO: Find out which variable was not defined - return nil, errors.New("some of the variables used in the template were undefined") + if filepath.Ext(name) == TEMPLATE_EXT { + _, err := t.New(name).Parse(string(data)) + if err != nil { + // TODO: Inner error message includes prefix "template: ", which does not good when printing this error + return nil, fmt.Errorf("failed to parse template: %w", err) + } + + var buf strings.Builder + if err := t.ExecuteTemplate(&buf, name, values); err != nil { + // TODO: Inner error message includes prefix "template: ", which does not good when printing this error + return nil, fmt.Errorf("failed to execute template: %w", err) + } + + output := buf.String() + + // If template uses variables which were undefined, gotpl will insert "" + if strings.Contains(output, "") { + // TODO: Find out which variable was not defined + return nil, errors.New("some of the variables used in the template were undefined") + } + + // TODO: Could we detect unused variables, and give warning about those? + + // Remove template filename extension from destination path + destPathRunes := []rune(name) + destination := string(destPathRunes[0 : len(destPathRunes)-len(TEMPLATE_EXT)]) + rendered[destination] = []byte(output) + } else { + // non-template file, render as is + rendered[name] = data } - - // TODO: Could we detect unused variables, and give warning about those? - - rendered[name] = []byte(output) } return rendered, nil