Skip to content

Commit

Permalink
fix: fail templating gracefully
Browse files Browse the repository at this point in the history
Signed-off-by: Humair Khan <HumairAK@users.noreply.github.com>
  • Loading branch information
HumairAK committed Mar 18, 2024
1 parent ad47dda commit 7377bb5
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 9 deletions.
7 changes: 6 additions & 1 deletion controllers/config/manifest.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,12 @@ import (
)

func Manifest(cl client.Client, templatePath string, context interface{}) (mf.Manifest, error) {
m, err := mf.ManifestFrom(PathTemplateSource(templatePath, context))
pathTmplSrc, err := PathTemplateSource(templatePath, context)
if err != nil {
return mf.Manifest{}, err
}

m, err := mf.ManifestFrom(pathTmplSrc)
if err != nil {
return mf.Manifest{}, err
}
Expand Down
23 changes: 15 additions & 8 deletions controllers/config/templating.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ package config
import (
"bytes"
"io"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"os"
"text/template"

Expand All @@ -30,12 +31,18 @@ import (
var PathPrefix string

// PathTemplateSource A templating source read from a file
func PathTemplateSource(path string, context interface{}) mf.Source {
func PathTemplateSource(path string, context interface{}) (mf.Source, error) {
f, err := os.Open(prefixedPath(path))
if err != nil {
panic(err)
return mf.Slice([]unstructured.Unstructured{}), err
}
return templateSource(f, context)

tmplSrc, err := templateSource(f, context)
if err != nil {
return mf.Slice([]unstructured.Unstructured{}), err
}

return tmplSrc, nil
}

func prefixedPath(p string) string {
Expand All @@ -46,19 +53,19 @@ func prefixedPath(p string) string {
}

// A templating manifest source
func templateSource(r io.Reader, context interface{}) mf.Source {
func templateSource(r io.Reader, context interface{}) (mf.Source, error) {
b, err := io.ReadAll(r)
if err != nil {
panic(err)
return mf.Slice([]unstructured.Unstructured{}), err
}
t, err := template.New("manifestTemplateDSP").Parse(string(b))
if err != nil {
panic(err)
return mf.Slice([]unstructured.Unstructured{}), err
}
var b2 bytes.Buffer
err = t.Execute(&b2, context)
if err != nil {
panic(err)
return mf.Slice([]unstructured.Unstructured{}), err
}
return mf.Reader(&b2)
return mf.Reader(&b2), nil
}

0 comments on commit 7377bb5

Please sign in to comment.