feat(env): convenience get_env function with fallback support

This commit is contained in:
Peter 2023-03-19 11:36:39 +01:00
parent 049d316d4d
commit d1bdc8449f
Signed by: prskr
GPG key ID: C1DB5D2E8DB512F9
10 changed files with 80 additions and 16 deletions

View file

@ -4,6 +4,6 @@ buildr {
logs_dir = ".buildr/logs"
github {
api_token = env["BUILDR_GITHUB_TOKEN"]
api_token = get_env("BUILDR_GITHUB_TOKEN")
}
}

View file

@ -11,10 +11,11 @@ import (
)
var buildCmd = &cobra.Command{
Use: "build",
RunE: runBuild,
Args: cobra.ExactArgs(1),
SilenceUsage: true,
Use: "build",
RunE: runBuild,
Args: cobra.ExactArgs(1),
SilenceUsage: true,
SilenceErrors: true,
ValidArgsFunction: func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
if len(args) != 0 {
return nil, cobra.ShellCompDirectiveNoFileComp

View file

@ -23,6 +23,8 @@ var (
rootCmd = &cobra.Command{
Use: "buildr",
PersistentPreRunE: initBuildR,
SilenceUsage: true,
SilenceErrors: true,
}
)
@ -70,7 +72,7 @@ func initBuildR(cmd *cobra.Command, _ []string) error {
}
if err := parser.Parse(cmd.Context(), &rawSpec); err != nil {
slog.Error("Failed to parse HCL files", slog.Any("error", err), slog.String("phase", "phase1"))
return err
}
registry := modules.NewRegistry()

View file

@ -11,10 +11,11 @@ import (
)
var taskCmd = &cobra.Command{
Use: "task",
RunE: runTask,
Args: cobra.ExactArgs(1),
SilenceUsage: true,
Use: "task",
RunE: runTask,
Args: cobra.ExactArgs(1),
SilenceUsage: true,
SilenceErrors: true,
ValidArgsFunction: func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
if len(args) != 0 {
return nil, cobra.ShellCompDirectiveNoFileComp

View file

@ -11,10 +11,11 @@ import (
)
var toolCmd = &cobra.Command{
Use: "tool",
RunE: runTool,
Args: cobra.ExactArgs(1),
SilenceUsage: true,
Use: "tool",
RunE: runTool,
Args: cobra.ExactArgs(1),
SilenceUsage: true,
SilenceErrors: true,
ValidArgsFunction: func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
if len(args) != 0 {
return nil, cobra.ShellCompDirectiveNoFileComp

View file

@ -2,6 +2,7 @@ package logging
import (
"context"
"strings"
"github.com/hashicorp/hcl/v2"
"golang.org/x/exp/slog"
@ -28,7 +29,7 @@ func Diagnostics(diag hcl.Diagnostics, logger *slog.Logger) {
}
logArgs := []any{
slog.String("detail", d.Detail),
slog.String("detail", strings.ReplaceAll(d.Detail, "\"", "'")),
}
if d.Context != nil {

View file

@ -8,6 +8,7 @@ import (
"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"
"code.icb4dc0.de/buildr/buildr/modules/helpers/strings"
@ -21,6 +22,7 @@ func DefaultContext(ctx context.Context, cli *gh.Client) *hcl.EvalContext {
Functions: make(map[string]function.Function),
}
env.RegisterInContext(evalctx)
github.RegisterInContext(ctx, evalctx, cli)
strings.RegisterInContext(evalctx)
hclhelpers.RegisterInContext(evalctx)

View file

@ -13,6 +13,7 @@ import (
"github.com/zclconf/go-cty/cty"
"golang.org/x/exp/slog"
"code.icb4dc0.de/buildr/buildr/internal/errs"
"code.icb4dc0.de/buildr/buildr/internal/logging"
"code.icb4dc0.de/buildr/buildr/internal/services"
)
@ -34,7 +35,7 @@ func (p *Parser) Parse(ctx context.Context, val any) error {
diags := gohcl.DecodeBody(p.body, DefaultContext(ctx, p.svc.GitHubClient(ctx)), val)
if diags.HasErrors() {
logging.Diagnostics(diags, p.logger)
return diags
return errs.ErrAlreadyLogged
}
return nil

48
modules/helpers/env/env.go vendored Normal file
View file

@ -0,0 +1,48 @@
package env
import (
"errors"
"fmt"
"os"
"github.com/zclconf/go-cty/cty"
"github.com/zclconf/go-cty/cty/function"
)
var ErrNoEnvKeyProvided = errors.New("no environment lookup key provided")
func GetEnv() function.Function {
return function.New(&function.Spec{
Description: "Get environment variables",
Params: []function.Parameter{
{
Name: "key",
Description: "Environment variable key to lookup",
Type: cty.String,
},
},
VarParam: &function.Parameter{
Name: "fallbackValue",
Description: "if no matching environment variable is set the fallback will be returned",
Type: cty.String,
},
Type: function.StaticReturnType(cty.String),
Impl: func(args []cty.Value, retType cty.Type) (cty.Value, error) {
if len(args) < 1 {
return cty.Value{}, ErrNoEnvKeyProvided
}
lookupKey := args[0].AsString()
value, ok := os.LookupEnv(lookupKey)
if !ok {
if len(args) < 2 {
return cty.Value{}, fmt.Errorf("no environment variable with given lookup key %s set", lookupKey)
}
return args[1], nil
}
return cty.StringVal(value), nil
},
})
}

7
modules/helpers/env/registration.go vendored Normal file
View file

@ -0,0 +1,7 @@
package env
import "github.com/hashicorp/hcl/v2"
func RegisterInContext(evalCtx *hcl.EvalContext) {
evalCtx.Functions["get_env"] = GetEnv()
}