templatefile/pkg/templater/main.go

90 lines
2.1 KiB
Go
Raw Normal View History

package templater
import (
"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"
)
2022-06-23 18:03:09 +02:00
func ProcessGoTemplate(file string, config []byte) (string, error) {
// The JSON configuration
var confData map[string]interface{}
var res bytes.Buffer
err := encjson.Unmarshal(config, &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)
2022-06-15 17:29:45 +02:00
utils.CheckErr(tpl.Execute(&res, confData["Config"]))
2022-06-23 18:03:09 +02:00
return res.String(), nil
}
2022-06-23 18:03:09 +02:00
func 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 {
2022-06-23 18:03:09 +02:00
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{
2022-06-23 18:03:09 +02:00
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())
}
2022-06-23 18:03:09 +02:00
return val.AsString(), nil
}