policy-generator/cmd/policygen/templates.go
2025-01-02 11:37:20 +01:00

95 lines
1.9 KiB
Go

package main
import (
"fmt"
"html/template"
"io/fs"
"os"
"strings"
)
import "embed"
import sprig "github.com/Masterminds/sprig/v3" // This provides most Helm functions
import "github.com/goccy/go-yaml"
// This provides most Helm functions
//go:embed templates/*
var templateFS embed.FS
func NewTemplate() *template.Template {
tmpl := template.New("")
// Combine sprig functions with custom functions
funcMap := template.FuncMap{}
// Add all sprig functions
for name, fn := range sprig.FuncMap() {
funcMap[name] = fn
}
// Add any custom functions you want
customFuncs := template.FuncMap{
"toYaml": func(v interface{}) string {
data, err := yaml.Marshal(v)
if err != nil {
return ""
}
return string(data)
},
}
// Merge custom functions
for name, fn := range customFuncs {
funcMap[name] = fn
}
// Add the function map to the template
tmpl = tmpl.Funcs(funcMap)
return tmpl
}
func showContents(files fs.FS) {
entries, err := fs.ReadDir(files, ".")
if err != nil {
panic(err)
}
for _, entry := range entries {
fmt.Printf("entry %s %s\n", entry.Name(), entry.Type())
if entry.Type().IsDir() {
subdir, err := fs.Sub(files, entry.Name())
if err != nil {
panic(err)
}
showContents(subdir)
}
}
}
func loadTemplates() (*template.Template, error) {
showContents(templateFS)
// Parse all templates at once from the embedded FS
tmpl := NewTemplate()
err := loadTemplatesGlob(tmpl)
if err != nil {
return nil, err
}
return tmpl, err
}
func loadTemplatesGlob(tmpl *template.Template) error {
return fs.WalkDir(templateFS, ".", func(path string, d os.DirEntry, err error) error {
if strings.HasSuffix(path, ".yaml") {
data, err := fs.ReadFile(templateFS, path)
if err != nil {
return err
}
fmt.Fprintf(os.Stderr, "Loading template %s\n", path)
tmpl.New(path).Parse(string(data))
}
return nil
})
}