Refactor renderAsset()
This makes it easier to reuse parts of the function.
@@ -33,12 +33,29 @@ type renderConfig struct {
Constants map[string]string
}
-func renderAsset(config *renderConfig, path string) ([]byte, error) {
- objBytes, err := manifests.ReadFile(path)
+type assetRenderer struct {
+ Path string
+ tmpl *template.Template
+ templateData string
+}
+
+func newAssetRenderer(path string) *assetRenderer {
+ return &assetRenderer{
+ Path: path,
+ tmpl: template.New(path),
+ }
+}
+
+func (a *assetRenderer) read() error {
+ objBytes, err := manifests.ReadFile(a.Path)
if err != nil {
- return nil, fmt.Errorf("error getting asset %s: %v", path, err)
+ return fmt.Errorf("error getting asset %s: %v", a.Path, err)
+ }
+ a.templateData = string(objBytes)
+ return nil
}
+func (a *assetRenderer) addTemplateFuncs() {
funcs := sprig.TxtFuncMap()
funcs["toYAML"] = toYAML
funcs["onPremPlatformAPIServerInternalIP"] = onPremPlatformAPIServerInternalIP
@@ -46,13 +63,13 @@ func renderAsset(config *renderConfig, path string) ([]byte, error) {
funcs["onPremPlatformShortName"] = onPremPlatformShortName
funcs["onPremPlatformKeepalivedEnableUnicast"] = onPremPlatformKeepalivedEnableUnicast
- if config.Constants == nil {
- config.Constants = constants.ConstantsByName
+ a.tmpl = a.tmpl.Funcs(funcs)
}
- tmpl, err := template.New(path).Funcs(funcs).Parse(string(objBytes))
+func (a *assetRenderer) render(config interface{}) ([]byte, error) {
+ tmpl, err := a.tmpl.Parse(a.templateData)
if err != nil {
- return nil, fmt.Errorf("failed to parse asset %s: %v", path, err)
+ return nil, fmt.Errorf("failed to parse asset %s: %v", a.Path, err)
}
buf := new(bytes.Buffer)
@@ -63,6 +80,21 @@ func renderAsset(config *renderConfig, path string) ([]byte, error) {
return buf.Bytes(), nil
}
+func renderAsset(config *renderConfig, path string) ([]byte, error) {
+ asset := newAssetRenderer(path)
+ if err := asset.read(); err != nil {
+ return nil, err
+ }
+
+ if config.Constants == nil {
+ config.Constants = constants.ConstantsByName
+ }
+
+ asset.addTemplateFuncs()
+
+ return asset.render(config)
+}
+
func toYAML(i interface{}) []byte {
out, err := yaml.Marshal(i)
if err != nil {
