buildr/modules/helpers/env/env.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

50 lines
1.2 KiB
Go

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 {
const typeAndName = 2
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) < typeAndName {
return cty.Value{}, fmt.Errorf("no environment variable with given lookup key %s set", lookupKey)
}
return args[1], nil
}
return cty.StringVal(value), nil
},
})
}