From da6d7dedeb070fa1bfd638815784410a085d4c8e Mon Sep 17 00:00:00 2001 From: Gerhard Lazu Date: Tue, 15 Aug 2023 12:46:01 +0100 Subject: [PATCH] Share the same client when running multiple targets via All Signed-off-by: Gerhard Lazu --- magefiles/dagger.go | 44 ++++++++++++++++++++++++++++++-------------- 1 file changed, 30 insertions(+), 14 deletions(-) diff --git a/magefiles/dagger.go b/magefiles/dagger.go index 2cfe7cf..33d70bf 100644 --- a/magefiles/dagger.go +++ b/magefiles/dagger.go @@ -47,8 +47,11 @@ const ( // golangci-lint func Lint(ctx context.Context) { - c := daggerClient(ctx) - defer c.Close() + c, ok := ctx.Value("daggerClient").(*dagger.Client) + if !ok { + c := newDaggerClient(ctx) + defer c.Close() + } lint(ctx, c) } @@ -68,8 +71,11 @@ func lint(ctx context.Context, c *dagger.Client) { // go test func Test(ctx context.Context) { - c := daggerClient(ctx) - defer c.Close() + c, ok := ctx.Value("daggerClient").(*dagger.Client) + if !ok { + c := newDaggerClient(ctx) + defer c.Close() + } test(ctx, c) } @@ -91,8 +97,11 @@ func test(ctx context.Context, c *dagger.Client) { // binary artefact used in container image func Build(ctx context.Context) { - c := daggerClient(ctx) - defer c.Close() + c, ok := ctx.Value("daggerClient").(*dagger.Client) + if !ok { + c := newDaggerClient(ctx) + defer c.Close() + } build(ctx, c) } @@ -128,8 +137,11 @@ func sourceCode(c *dagger.Client) *dagger.Directory { // container image to private registry func Publish(ctx context.Context) { - c := daggerClient(ctx) - defer c.Close() + c, ok := ctx.Value("daggerClient").(*dagger.Client) + if !ok { + c := newDaggerClient(ctx) + defer c.Close() + } publish(ctx, c) } @@ -149,8 +161,11 @@ func publish(ctx context.Context, c *dagger.Client) string { // zero-downtime deploy container image func Deploy(ctx context.Context) { - c := daggerClient(ctx) - defer c.Close() + c, ok := ctx.Value("daggerClient").(*dagger.Client) + if !ok { + c := newDaggerClient(ctx) + defer c.Close() + } imageRef := os.Getenv("IMAGE_REF") if imageRef == "" { @@ -194,16 +209,17 @@ func deploy(ctx context.Context, c *dagger.Client, imageRef string) { // [lints, tests], builds, publishes & deploys a new version of the app func All(ctx context.Context) { - mg.CtxDeps(ctx, Lint, Test, Build) - - c := daggerClient(ctx) + c := newDaggerClient(ctx) defer c.Close() + ctx = context.WithValue(ctx, "daggerClient", c) + + mg.CtxDeps(ctx, Lint, Test, Build) imageRef := publish(ctx, c) deploy(ctx, c, imageRef) } -func daggerClient(ctx context.Context) *dagger.Client { +func newDaggerClient(ctx context.Context) *dagger.Client { client, err := dagger.Connect(ctx, dagger.WithLogOutput(os.Stderr)) if err != nil { panic(err)