This repository has been archived on 2023-05-06. You can view files and clone it, but cannot push or open issues or pull requests.
helix/internal/stacks/templates.go

61 lines
1.5 KiB
Go
Raw Normal View History

package stacks
import (
"fmt"
"os"
2021-09-01 22:04:40 +01:00
"path/filepath"
"strings"
"text/template"
)
2021-09-01 22:04:40 +01:00
// renderTemplates renders all template files (.tmpl) within a given directory in the
// embedded 'templates' filesystem.
func renderTemplates(data interface{}, service, projectCacheRoot string) error {
// create the context directory
contextDir := filepath.Join(projectCacheRoot, service)
if err := os.MkdirAll(contextDir, 0700); err != nil {
return fmt.Errorf("unable to make the cache directory for %s...\n%w", service, err)
}
// read the service's template directory to get the list of the template files.
templateDir := "templates/" + service
fsDir, err := templates.ReadDir(templateDir)
if err != nil {
2021-09-01 22:04:40 +01:00
return err
}
2021-09-01 22:04:40 +01:00
// render each template file (.tmpl) to the context directory.
for _, f := range fsDir {
filename := f.Name()
content, err := templates.ReadFile(fmt.Sprintf("%s/%s", templateDir, filename))
if err != nil {
return err
}
outputFilename := strings.TrimSuffix(filename, ".tmpl")
outputPath := filepath.Join(contextDir, outputFilename)
file, err := os.Create(outputPath)
if err != nil {
return fmt.Errorf("unable to create the file '%s'...\n%v", outputPath, err)
}
defer file.Close()
if !strings.HasSuffix(filename, ".tmpl") {
fmt.Fprint(file, string(content))
return nil
}
tmpl := template.Must(template.New(filename).Parse(string(content)))
2021-09-01 22:04:40 +01:00
if err = tmpl.Execute(file, data); err != nil {
return fmt.Errorf("unable to execute the template at '%s'...\n%v", outputFilename, err)
}
}
return nil
}