2021-12-15 00:32:31 +01:00
|
|
|
package task
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
"fmt"
|
|
|
|
"io/fs"
|
|
|
|
|
|
|
|
"cuelang.org/go/cue"
|
|
|
|
"github.com/moby/buildkit/client/llb"
|
|
|
|
"go.dagger.io/dagger/compiler"
|
|
|
|
"go.dagger.io/dagger/plancontext"
|
|
|
|
"go.dagger.io/dagger/solver"
|
|
|
|
)
|
|
|
|
|
|
|
|
func init() {
|
|
|
|
Register("WriteFile", func() Task { return &writeFileTask{} })
|
|
|
|
}
|
|
|
|
|
|
|
|
type writeFileTask struct {
|
|
|
|
}
|
|
|
|
|
2022-03-23 23:02:17 +01:00
|
|
|
func (t *writeFileTask) Run(ctx context.Context, pctx *plancontext.Context, s *solver.Solver, v *compiler.Value) (*compiler.Value, error) {
|
2021-12-15 00:32:31 +01:00
|
|
|
var contents []byte
|
|
|
|
var err error
|
|
|
|
|
|
|
|
path, err := v.Lookup("path").String()
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
switch kind := v.Lookup("contents").Kind(); kind {
|
|
|
|
// TODO: support bytes?
|
|
|
|
// case cue.BytesKind:
|
|
|
|
// contents, err = v.Lookup("contents").Bytes()
|
|
|
|
case cue.StringKind:
|
|
|
|
var str string
|
|
|
|
str, err = v.Lookup("contents").String()
|
|
|
|
if err == nil {
|
|
|
|
contents = []byte(str)
|
|
|
|
}
|
|
|
|
case cue.BottomKind:
|
|
|
|
err = fmt.Errorf("%s: WriteFile contents is not set", path)
|
|
|
|
default:
|
|
|
|
err = fmt.Errorf("%s: unhandled data type in WriteFile: %s", path, kind)
|
|
|
|
}
|
|
|
|
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
2021-12-22 14:17:52 +01:00
|
|
|
permissions, err := v.Lookup("permissions").Int64()
|
2021-12-15 00:32:31 +01:00
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
input, err := pctx.FS.FromValue(v.Lookup("input"))
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
2021-12-21 18:42:05 +01:00
|
|
|
inputState, err := input.State()
|
2021-12-15 00:32:31 +01:00
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
outputState := inputState.File(
|
2021-12-22 14:17:52 +01:00
|
|
|
llb.Mkfile(path, fs.FileMode(permissions), contents),
|
2021-12-15 00:32:31 +01:00
|
|
|
withCustomName(v, "WriteFile %s", path),
|
|
|
|
)
|
|
|
|
|
|
|
|
result, err := s.Solve(ctx, outputState, pctx.Platform.Get())
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
2021-12-22 14:17:52 +01:00
|
|
|
outputFS := pctx.FS.New(result)
|
2021-12-15 00:32:31 +01:00
|
|
|
|
|
|
|
output := compiler.NewValue()
|
2021-12-22 14:17:52 +01:00
|
|
|
if err := output.FillPath(cue.ParsePath("output"), outputFS.MarshalCUE()); err != nil {
|
2021-12-15 00:32:31 +01:00
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
return output, nil
|
|
|
|
}
|