templatefile/pkg/templater/files.go

72 lines
2.5 KiB
Go
Raw Permalink Normal View History

package templater
import (
"log"
"path/filepath"
"strconv"
"fmt"
"os"
"forge.cadoles.com/pcaseiro/templatefile/pkg/utils"
)
type ConfigFile struct {
Destination string `form:"destination" json:"destination"` // Where do we write the configuration file
Source string `form:"source" json:"source"` // The template file short name
TemplateType string `json:"type"` // The template file type (hcl or gotemplate)
Mode string `form:"mod" json:"mode"` // The configuration file final permissions (mode)
Owner string `json:"owner"` // The configuration file owner
Service string `json:"service"` // Service to restart after configuration generation
Group string `json:"group"` // The configuration file group owner
TemplateDir string
}
// Generate the configuration file from the template (hcl or json)
func (cf *ConfigFile) Generate(root string, templateDir string, values []byte) error {
var template string
cf.TemplateDir = templateDir
dest := filepath.Join(root, cf.Destination)
intMod, err := strconv.ParseInt(cf.Mode, 8, 64)
if err != nil {
return (err)
}
template, err = cf.ProcessTemplate(root, values)
if err != nil {
return fmt.Errorf("Process templates failed with error: %v", err)
}
dirname := filepath.Dir(dest)
err = os.MkdirAll(dirname, os.FileMode(int(0700)))
if err != nil {
return fmt.Errorf("Process templates failed with error: %v", err)
}
err = os.WriteFile(dest, []byte(template), os.FileMode(intMod))
if err != nil {
return fmt.Errorf("Process templates failed with error: %v", err)
}
log.Printf("\tFile %s generated\n", dest)
return nil
}
// Process the template with the provided values
func (cf *ConfigFile) ProcessTemplate(root string, values []byte) (string, error) {
var result string
var err error
if cf.TemplateType == "hcl" {
// The template is an hcl template so we call processHCLTemplate
result, err = utils.ProcessHCLTemplate(filepath.Join(cf.TemplateDir, cf.Source), values)
if err != nil {
return "", fmt.Errorf("Process HCL template failed with error: %v", err)
}
} else if cf.TemplateType == "go" {
// The template is a go template so we call processGoTemplate
result, err = utils.ProcessGoTemplate(filepath.Join(cf.TemplateDir, cf.Source), values)
if err != nil {
return "", fmt.Errorf("Process GO template failed with error: %v", err)
}
}
return result, nil
}