buildr/internal/hcl/context.go
Peter 1261932bdc
All checks were successful
continuous-integration/drone/push Build is passing
refactor: apply golangci-lint findings
2023-06-22 19:16:00 +02:00

94 lines
2.3 KiB
Go

package hcl
import (
"context"
"os"
"strings"
"code.icb4dc0.de/buildr/buildr/internal/vault"
"code.icb4dc0.de/buildr/buildr/modules/helpers/paths"
"code.icb4dc0.de/buildr/buildr/modules/state"
"github.com/hashicorp/hcl/v2"
"github.com/zclconf/go-cty/cty"
"github.com/zclconf/go-cty/cty/function"
"code.icb4dc0.de/buildr/buildr/modules/helpers/env"
"code.icb4dc0.de/buildr/buildr/modules/helpers/github"
"code.icb4dc0.de/buildr/buildr/modules/helpers/hclhelpers"
string_helpers "code.icb4dc0.de/buildr/buildr/modules/helpers/strings"
vaultHelpers "code.icb4dc0.de/buildr/buildr/modules/helpers/vault"
)
func MockContext(ctx context.Context, cache state.Cache) *hcl.EvalContext {
evalctx := &hcl.EvalContext{
Variables: map[string]cty.Value{
"env": envVars(),
},
Functions: make(map[string]function.Function),
}
env.RegisterInContext(evalctx)
string_helpers.RegisterInContext(evalctx)
hclhelpers.RegisterInContext(evalctx)
paths.RegisterInContext(evalctx)
vaultHelpers.RegisterInContext(evalctx, vaultHelpers.MockGetter("<mocked>"))
github.RegisterInContext(ctx, evalctx, cache)
return evalctx
}
func BasicContext(vaultGetter vaultHelpers.VaultGetter) *hcl.EvalContext {
evalctx := &hcl.EvalContext{
Variables: map[string]cty.Value{
"env": envVars(),
},
Functions: make(map[string]function.Function),
}
env.RegisterInContext(evalctx)
string_helpers.RegisterInContext(evalctx)
hclhelpers.RegisterInContext(evalctx)
paths.RegisterInContext(evalctx)
vaultHelpers.RegisterInContext(evalctx, vaultGetter)
return evalctx
}
func FullContext(ctx context.Context, parent *hcl.EvalContext, vaultInst *vault.Vault, cache state.Cache) *hcl.EvalContext {
if parent == nil {
parent = BasicContext(vaultInst)
}
evalctx := parent.NewChild()
if evalctx.Functions == nil {
evalctx.Functions = make(map[string]function.Function)
}
if evalctx.Variables == nil {
evalctx.Variables = make(map[string]cty.Value)
}
github.RegisterInContext(ctx, evalctx, cache)
return evalctx
}
func envVars() cty.Value {
const keyAndValue = 2
vars := os.Environ()
envVars := make(map[string]cty.Value, len(vars))
for i := range vars {
split := strings.Split(vars[i], "=")
if len(split) != keyAndValue {
continue
}
envVars[split[0]] = cty.StringVal(split[1])
}
return cty.MapVal(envVars)
}