Skip to content

Commit

Permalink
Use template engine only for .tmpl files
Browse files Browse the repository at this point in the history
  • Loading branch information
Ilkka Poutanen committed Aug 28, 2023
1 parent ca37f5e commit f801350
Showing 1 changed file with 33 additions and 22 deletions.
55 changes: 33 additions & 22 deletions pkg/engine/engine.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,43 +3,54 @@ package engine
import (
"errors"
"fmt"
"path/filepath"
"strings"
"text/template"
)

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())

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 "<no value>"
if strings.Contains(output, "<no value>") {
// 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 "<no value>"
if strings.Contains(output, "<no value>") {
// 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
Expand Down

0 comments on commit f801350

Please sign in to comment.