2022-03-07 14:12:39 +01:00
|
|
|
package task
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
"fmt"
|
|
|
|
"os"
|
|
|
|
|
|
|
|
"cuelang.org/go/cue"
|
|
|
|
"github.com/rs/zerolog/log"
|
|
|
|
"go.dagger.io/dagger/compiler"
|
|
|
|
"go.dagger.io/dagger/plancontext"
|
|
|
|
"go.dagger.io/dagger/solver"
|
|
|
|
)
|
|
|
|
|
|
|
|
func init() {
|
2022-03-09 13:29:26 +01:00
|
|
|
Register("ClientEnv", func() Task { return &clientEnvTask{} })
|
2022-03-07 14:12:39 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
type clientEnvTask struct {
|
|
|
|
}
|
|
|
|
|
2022-03-23 23:02:17 +01:00
|
|
|
func (t clientEnvTask) Run(ctx context.Context, pctx *plancontext.Context, _ *solver.Solver, v *compiler.Value) (*compiler.Value, error) {
|
2022-03-09 13:29:26 +01:00
|
|
|
log.Ctx(ctx).Debug().Msg("loading environment variables")
|
2022-03-07 14:12:39 +01:00
|
|
|
|
2022-03-09 13:29:26 +01:00
|
|
|
fields, err := v.Fields()
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
envs := make(map[string]interface{})
|
|
|
|
for _, field := range fields {
|
|
|
|
if field.Selector == cue.Str("$dagger") {
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
envvar := field.Label()
|
|
|
|
val, err := t.getEnv(envvar, field.Value, pctx)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
envs[envvar] = val
|
|
|
|
}
|
2022-03-07 14:12:39 +01:00
|
|
|
|
2022-03-09 13:29:26 +01:00
|
|
|
return compiler.NewValue().FillFields(envs)
|
|
|
|
}
|
2022-03-07 14:12:39 +01:00
|
|
|
|
2022-03-09 13:29:26 +01:00
|
|
|
func (t clientEnvTask) getEnv(envvar string, v *compiler.Value, pctx *plancontext.Context) (interface{}, error) {
|
2022-04-11 20:31:36 +02:00
|
|
|
// Resolve default in disjunction if a type hasn't been specified
|
|
|
|
val, hasDefault := v.Default()
|
|
|
|
|
|
|
|
env, hasEnv := os.LookupEnv(envvar)
|
|
|
|
if !hasEnv {
|
|
|
|
if hasDefault {
|
|
|
|
// we can only have default strings so
|
|
|
|
// don't worry about secret values here
|
|
|
|
return val, nil
|
|
|
|
}
|
2022-03-07 14:12:39 +01:00
|
|
|
return nil, fmt.Errorf("environment variable %q not set", envvar)
|
|
|
|
}
|
|
|
|
|
|
|
|
if plancontext.IsSecretValue(val) {
|
|
|
|
secret := pctx.Secrets.New(env)
|
2022-03-09 13:29:26 +01:00
|
|
|
return secret.MarshalCUE(), nil
|
2022-03-07 14:12:39 +01:00
|
|
|
}
|
|
|
|
|
2022-04-11 21:35:17 +02:00
|
|
|
if !hasDefault && val.IsConcrete() {
|
2022-04-11 20:31:36 +02:00
|
|
|
return nil, fmt.Errorf("%s: unexpected concrete value, please use a type or set a default", envvar)
|
2022-03-07 14:12:39 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
k := val.IncompleteKind()
|
|
|
|
if k == cue.StringKind {
|
2022-03-09 13:29:26 +01:00
|
|
|
return env, nil
|
2022-03-07 14:12:39 +01:00
|
|
|
}
|
|
|
|
|
2022-03-09 13:29:26 +01:00
|
|
|
return nil, fmt.Errorf("%s: unsupported type %q", envvar, k)
|
2022-03-07 14:12:39 +01:00
|
|
|
}
|