Provide sprig functions in overlay templates

This commit is contained in:
John Hanks
2024-02-26 10:45:51 -07:00
committed by Christian Goll
parent 6a8f0022db
commit cbf9178f10
5 changed files with 56 additions and 19 deletions

View File

@@ -13,6 +13,8 @@ import (
"syscall"
"text/template"
"github.com/Masterminds/sprig/v3"
"github.com/pkg/errors"
"github.com/warewulf/warewulf/internal/pkg/node"
"github.com/warewulf/warewulf/internal/pkg/util"
@@ -350,8 +352,12 @@ func RenderTemplateFile(fileName string, data TemplateStruct) (
err error) {
backupFile = true
writeFile = true
tmpl, err := template.New(path.Base(fileName)).Option("missingkey=default").Funcs(template.FuncMap{
// TODO: Fix for missingkey=zero
// Build our FuncMap
funcMap := template.FuncMap{
"tr": func(source, old, new string) string {
return strings.Replace(source, old, new, -1)
},
"Include": templateFileInclude,
"IncludeFrom": templateContainerFileInclude,
"IncludeBlock": templateFileBlock,
@@ -377,21 +383,20 @@ func RenderTemplateFile(fileName string, data TemplateStruct) (
backupFile = false
return ""
},
"split": func(s string, d string) []string {
return strings.Split(s, d)
},
"tr": func(source, old, new string) string {
return strings.Replace(source, old, new, -1)
},
"replace": func(source, old, new string) string {
return strings.Replace(source, old, new, -1)
},
// }).ParseGlob(path.Join(OverlayDir, destFile+".ww*"))
}).ParseGlob(fileName)
}
// Merge sprig.FuncMap with our FuncMap
for key, value := range sprig.TxtFuncMap() {
funcMap[key] = value
}
// Create the template with the merged FuncMap
tmpl, err := template.New(path.Base(fileName)).Option("missingkey=default").Funcs(funcMap).ParseGlob(fileName)
if err != nil {
err = errors.Wrap(err, "could not parse template "+fileName)
return
}
err = tmpl.Execute(&buffer, data)
if err != nil {
err = errors.Wrap(err, "could not execute template")

View File

@@ -6,10 +6,12 @@ import (
"fmt"
"net/http"
"path"
"path/filepath"
"strconv"
"strings"
"text/template"
"github.com/Masterminds/sprig/v3"
warewulfconf "github.com/warewulf/warewulf/internal/pkg/config"
"github.com/warewulf/warewulf/internal/pkg/container"
"github.com/warewulf/warewulf/internal/pkg/kernel"
@@ -226,7 +228,11 @@ func ProvisionSend(w http.ResponseWriter, req *http.Request) {
return
}
tmpl, err := template.ParseFiles(stage_file)
// Create a template with the Sprig functions.
tmpl := template.New(filepath.Base(stage_file)).Funcs(sprig.TxtFuncMap())
// Parse the template.
parsedTmpl, err := tmpl.ParseFiles(stage_file)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
wwlog.ErrorExc(err, "")
@@ -236,7 +242,7 @@ func ProvisionSend(w http.ResponseWriter, req *http.Request) {
// template engine writes file to buffer in case rendering fails
var buf bytes.Buffer
err = tmpl.Execute(&buf, tmpl_data)
err = parsedTmpl.Execute(&buf, tmpl_data)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
wwlog.ErrorExc(err, "")