templatefile/pkg/templater/files.go

146 lines
3.7 KiB
Go
Raw Normal View History

package templater
import (
"path/filepath"
"strconv"
"bytes"
encjson "encoding/json"
"fmt"
"os"
"text/template"
"github.com/hashicorp/hcl/v2"
"github.com/hashicorp/hcl/v2/hclsyntax"
"github.com/zclconf/go-cty/cty"
ctyjson "github.com/zclconf/go-cty/cty/json"
"forge.cadoles.com/pcaseiro/templatefile/pkg/utils"
)
type ConfigFile struct {
Destination string `form:"destination" json:"destination"`
Source string `form:"source" json:"source"`
TemplateType string `json:"type"`
Mode string `form:"mod" json:"mode"`
Owner string `json:"owner"`
Group string `json:"group"`
}
func (cf *ConfigFile) Generate(root string, templateDir string, values []byte) error {
var template string
dest := filepath.Join(root, cf.Destination)
source := filepath.Join(templateDir, cf.Source)
intMod, err := strconv.ParseInt(cf.Mode, 8, 64)
if err != nil {
return (err)
}
template, err = cf.ProcessTemplate(source, 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)
}
return nil
}
func (cf *ConfigFile) ProcessTemplate(source string, values []byte) (string, error) {
var result string
var err error
fmt.Printf("Processing %s\n", source)
if cf.TemplateType == "hcl" {
result, err = cf.processHCLTemplate(source, values)
if err != nil {
return "", fmt.Errorf("Process HCL template failed with error: %v", err)
}
} else if cf.TemplateType == "go" {
result, err = cf.processGoTemplate(source, values)
if err != nil {
return "", fmt.Errorf("Process GO template failed with error: %v", err)
}
}
return result, nil
}
func (cf *ConfigFile) processGoTemplate(file string, configValues []byte) (string, error) {
// The JSON configuration
var confData map[string]interface{}
var res bytes.Buffer
err := encjson.Unmarshal(configValues, &confData)
utils.CheckErr(err)
// Read the template
data, err := os.ReadFile(file)
utils.CheckErr(err)
tpl, err := template.New("conf").Parse(string(data))
utils.CheckErr(err)
utils.CheckErr(tpl.Execute(&res, confData["Config"]))
return res.String(), nil
}
func (cf *ConfigFile) processHCLTemplate(file string, config []byte) (string, error) {
fct, err := os.ReadFile(file)
utils.CheckErr(err)
expr, diags := hclsyntax.ParseTemplate(fct, file, hcl.Pos{Line: 0, Column: 1})
utils.CheckDiags(diags)
// Retrieve values from JSON
var varsVal cty.Value
ctyType, err := ctyjson.ImpliedType(config)
if err != nil {
return "", err
/* Maybe one day
cexpr, diags := hclsyntax.ParseExpression(config, "", hcl.Pos{Line: 0, Column: 1})
if diags.HasErrors() {
panic(diags.Error())
}
varsVal, diags = cexpr.Value(&hcl.EvalContext{})
fmt.Println(cexpr.Variables())
checkDiags(diags)
*/
} else {
varsVal, err = ctyjson.Unmarshal(config, ctyType)
utils.CheckErr(err)
}
ctx := &hcl.EvalContext{
Variables: varsVal.AsValueMap(),
}
for n := range ctx.Variables {
if !hclsyntax.ValidIdentifier(n) {
panic(fmt.Errorf("invalid template variable name %q: must start with a letter, followed by zero or more letters, digits, and underscores", n))
}
}
for _, traversal := range expr.Variables() {
root := traversal.RootName()
if _, ok := ctx.Variables[root]; !ok {
panic(fmt.Errorf("vars map does not contain key %q, referenced at %s", root, traversal[0].SourceRange()))
}
}
val, diags := expr.Value(ctx)
if diags.HasErrors() {
panic(diags.Error())
}
return val.AsString(), nil
}