From 54ef86c46effd3a9b9ea7291c407d6b2383c9d24 Mon Sep 17 00:00:00 2001 From: Philippe Caseiro Date: Fri, 11 Mar 2022 10:39:07 +0100 Subject: [PATCH] fix(template): fix go txt/template support We can parse go text/template again. --- main.go | 54 +++++++++++++++++++++++++++++++++++------------------- 1 file changed, 35 insertions(+), 19 deletions(-) diff --git a/main.go b/main.go index 8e16cbd..b32edde 100644 --- a/main.go +++ b/main.go @@ -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,40 +18,58 @@ 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)) } func processHCLTemplate(file string, config []byte) { - fct, err:= os.ReadFile(file) + fct, err := os.ReadFile(file) checkErr(err) - expr, diags := hclsyntax.ParseTemplate(fct, file, hcl.Pos{Line:1, Column: 1}) - if diags.HasErrors() { - panic(diags.Error()) + 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()) + } + varsVal, diags = cexpr.Value(&hcl.EvalContext{}) + fmt.Println(cexpr.Variables()) + checkDiags(diags) + */ + } else { + varsVal, err = ctyjson.Unmarshal(config, ctyType) + checkErr(err) } - ctyType, err := ctyjson.ImpliedType(config) - checkErr(err) - varsVal, err := ctyjson.Unmarshal(config,ctyType) - checkErr(err) - + fmt.Println(varsVal.AsValueMap()) ctx := &hcl.EvalContext{ Variables: varsVal.AsValueMap(), } @@ -75,7 +92,7 @@ func processHCLTemplate(file string, config []byte) { panic(diags.Error()) } - fmt.Printf("%s",val.AsString()) + fmt.Printf("%s", val.AsString()) } func main() { @@ -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" { @@ -92,4 +108,4 @@ func main() { } else { panic(fmt.Errorf("Unsupported template type")) } -} \ No newline at end of file +}