60 lines
1.5 KiB
Go
60 lines
1.5 KiB
Go
package stacks
|
|
|
|
import (
|
|
"fmt"
|
|
"os"
|
|
"path/filepath"
|
|
"strings"
|
|
"text/template"
|
|
)
|
|
|
|
// 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 {
|
|
return err
|
|
}
|
|
|
|
// 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)))
|
|
|
|
if err = tmpl.Execute(file, data); err != nil {
|
|
return fmt.Errorf("unable to execute the template at '%s'...\n%v", outputFilename, err)
|
|
}
|
|
}
|
|
|
|
return nil
|
|
}
|