94 lines
2.2 KiB
Go
94 lines
2.2 KiB
Go
package hcl
|
|
|
|
import (
|
|
"fmt"
|
|
"path/filepath"
|
|
|
|
"github.com/google/uuid"
|
|
"github.com/hashicorp/hcl/v2"
|
|
"github.com/hashicorp/hcl/v2/hclsyntax"
|
|
"github.com/zclconf/go-cty/cty"
|
|
|
|
"code.icb4dc0.de/buildr/buildr/modules"
|
|
)
|
|
|
|
func (s ModulesSpec) parseLocals(blocks []LocalsBlock, evalCtx *hcl.EvalContext) error {
|
|
localValues := make(map[string]cty.Value)
|
|
|
|
for _, block := range blocks {
|
|
if sBody, ok := block.Body.(*hclsyntax.Body); ok {
|
|
if val, err := s.parseSyntaxBodyToObject(sBody, evalCtx, false); err != nil {
|
|
return err
|
|
} else {
|
|
for k, v := range val {
|
|
if _, ok := localValues[k]; ok {
|
|
return fmt.Errorf("duplicate key %s detected in local values", k)
|
|
} else {
|
|
localValues[k] = v
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
evalCtx.Variables["local"] = cty.ObjectVal(localValues)
|
|
|
|
return nil
|
|
}
|
|
|
|
func (s ModulesSpec) parseSyntaxBodyToObject(
|
|
body *hclsyntax.Body,
|
|
evalCtx *hcl.EvalContext,
|
|
continueOnError bool,
|
|
) (map[string]cty.Value, error) {
|
|
attrs := make(map[string]cty.Value, len(body.Attributes))
|
|
|
|
for i := range body.Attributes {
|
|
attr := body.Attributes[i]
|
|
if val, diags := attr.Expr.Value(evalCtx); diags.HasErrors() && !continueOnError {
|
|
_ = s.diagsWriter.WriteDiagnostics(diags)
|
|
return nil, diags
|
|
} else {
|
|
attrs[attr.Name] = val
|
|
}
|
|
}
|
|
|
|
for i := range body.Blocks {
|
|
block := body.Blocks[i]
|
|
if mapped, err := s.parseSyntaxBodyToObject(block.Body, evalCtx, continueOnError); err != nil {
|
|
return nil, err
|
|
} else {
|
|
attrs[block.Type] = cty.ObjectVal(mapped)
|
|
}
|
|
}
|
|
|
|
return attrs, nil
|
|
}
|
|
|
|
func initBlock(body *hclsyntax.Body, moduleType modules.Category, moduleName, outDir string) *hclsyntax.Body {
|
|
body.Attributes["id"] = &hclsyntax.Attribute{
|
|
Name: "id",
|
|
Expr: &hclsyntax.LiteralValueExpr{
|
|
Val: cty.StringVal(uuid.NewString()),
|
|
},
|
|
}
|
|
|
|
body.Attributes["name"] = &hclsyntax.Attribute{
|
|
Name: "name",
|
|
Expr: &hclsyntax.LiteralValueExpr{
|
|
Val: cty.StringVal(moduleName),
|
|
},
|
|
}
|
|
|
|
if _, ok := body.Attributes["out_dir"]; !ok {
|
|
body.Attributes["out_dir"] = &hclsyntax.Attribute{
|
|
Name: "out_dir",
|
|
Expr: &hclsyntax.LiteralValueExpr{
|
|
Val: cty.StringVal(filepath.Join(outDir, modules.CategoryName(moduleType), moduleName)),
|
|
},
|
|
}
|
|
}
|
|
|
|
return body
|
|
}
|