gouick/helpers/template.go

51 lines
1.1 KiB
Go
Raw Normal View History

2022-08-09 21:37:57 +00:00
package helpers
import (
"os"
"path/filepath"
"text/template"
"github.com/juju/errors"
log "github.com/sirupsen/logrus"
)
// WriteTemplate will parse the given template filepath, and write the result to the savePath.
func WriteTemplate(templatePath string, savePath string, data interface{}) error {
execDirectory, err := GetExecutableDirectory()
if err != nil {
log.Error("Fail to get Gouick directory")
return errors.Trace(err)
}
templatePath = filepath.Join(execDirectory, templatePath)
template, err := template.ParseFiles(templatePath)
if err != nil {
log.Errorf("Fail to parse the template %s", templatePath)
return errors.Trace(err)
}
//nolint: gosec // We compute the savePath
fh, err := os.Create(savePath)
if err != nil {
log.Errorf("Fail to create saving path %s", savePath)
return errors.Trace(err)
}
defer func() {
if err := fh.Close(); err != nil {
log.Errorf("Error closing file: %s", err)
}
}()
err = template.Execute(fh, data)
if err != nil {
log.Errorf("Fail to write compute the template content for %s", savePath)
return errors.Trace(err)
}
return nil
}