fix(template): fix go txt/template support

We can parse go text/template again.
This commit is contained in:
Philippe Caseiro 2022-03-11 10:39:07 +01:00
parent 66d290c298
commit 54ef86c46e
1 changed files with 35 additions and 19 deletions

40
main.go
View File

@ -1,15 +1,14 @@
package main
import (
encjson "encoding/json"
"fmt"
"os"
"encoding/json"
"text/template"
//"github.com/hashicorp/hcl2/gohcl"
"github.com/hashicorp/hcl/v2"
"github.com/hashicorp/hcl/v2/hclsyntax"
//"github.com/zclconf/go-cty/cty"
//"github.com/zclconf/go-cty/cty/gocty"
"github.com/zclconf/go-cty/cty"
ctyjson "github.com/zclconf/go-cty/cty/json"
)
@ -19,22 +18,27 @@ func checkErr(e error) {
}
}
func checkDiags(diag hcl.Diagnostics) {
if diag.HasErrors() {
panic(diag.Error())
}
}
func processGoTemplate(file string, config []byte) {
// The JSON configuration
var confData map[string]interface{}
err := json.Unmarshal(config, &confData)
err := encjson.Unmarshal(config, &confData)
checkErr(err)
// Read the template
data, err := os.ReadFile(file)
checkErr(err)
tpl, err := template.New("conf").Parse(string(data))
checkErr(err)
checkErr(tpl.Execute(os.Stdout,config))
checkErr(tpl.Execute(os.Stdout, confData))
}
@ -44,15 +48,28 @@ func processHCLTemplate(file string, config []byte) {
checkErr(err)
expr, diags := hclsyntax.ParseTemplate(fct, file, hcl.Pos{Line: 1, Column: 1})
checkDiags(diags)
// Retrieve values from JSON
var varsVal cty.Value
ctyType, err := ctyjson.ImpliedType(config)
if err != nil {
panic(err)
/* Maybe one day
cexpr, diags := hclsyntax.ParseExpression(config, "", hcl.Pos{Line: 1, Column: 1})
if diags.HasErrors() {
panic(diags.Error())
}
ctyType, err := ctyjson.ImpliedType(config)
checkErr(err)
varsVal, err := ctyjson.Unmarshal(config,ctyType)
varsVal, diags = cexpr.Value(&hcl.EvalContext{})
fmt.Println(cexpr.Variables())
checkDiags(diags)
*/
} else {
varsVal, err = ctyjson.Unmarshal(config, ctyType)
checkErr(err)
}
fmt.Println(varsVal.AsValueMap())
ctx := &hcl.EvalContext{
Variables: varsVal.AsValueMap(),
}
@ -84,7 +101,6 @@ func main() {
templateFile := os.Args[2]
config := []byte(os.Args[3])
if templateType == "go" {
processGoTemplate(templateFile, config)
} else if templateType == "hcl" {