1package build // import "github.com/docker/docker/integration-cli/cli/build"
2
3import (
4	"io"
5	"strings"
6	"testing"
7
8	"github.com/docker/docker/testutil/fakecontext"
9	"gotest.tools/v3/icmd"
10)
11
12// WithStdinContext sets the build context from the standard input with the specified reader
13func WithStdinContext(closer io.ReadCloser) func(*icmd.Cmd) func() {
14	return func(cmd *icmd.Cmd) func() {
15		cmd.Command = append(cmd.Command, "-")
16		cmd.Stdin = closer
17		return func() {
18			// FIXME(vdemeester) we should not ignore the error here…
19			closer.Close()
20		}
21	}
22}
23
24// WithDockerfile creates / returns a CmdOperator to set the Dockerfile for a build operation
25func WithDockerfile(dockerfile string) func(*icmd.Cmd) func() {
26	return func(cmd *icmd.Cmd) func() {
27		cmd.Command = append(cmd.Command, "-")
28		cmd.Stdin = strings.NewReader(dockerfile)
29		return nil
30	}
31}
32
33// WithoutCache makes the build ignore cache
34func WithoutCache(cmd *icmd.Cmd) func() {
35	cmd.Command = append(cmd.Command, "--no-cache")
36	return nil
37}
38
39// WithContextPath sets the build context path
40func WithContextPath(path string) func(*icmd.Cmd) func() {
41	return func(cmd *icmd.Cmd) func() {
42		cmd.Command = append(cmd.Command, path)
43		return nil
44	}
45}
46
47// WithExternalBuildContext use the specified context as build context
48func WithExternalBuildContext(ctx *fakecontext.Fake) func(*icmd.Cmd) func() {
49	return func(cmd *icmd.Cmd) func() {
50		cmd.Dir = ctx.Dir
51		cmd.Command = append(cmd.Command, ".")
52		return nil
53	}
54}
55
56// WithBuildContext sets up the build context
57func WithBuildContext(t testing.TB, contextOperators ...func(*fakecontext.Fake) error) func(*icmd.Cmd) func() {
58	// FIXME(vdemeester) de-duplicate that
59	ctx := fakecontext.New(t, "", contextOperators...)
60	return func(cmd *icmd.Cmd) func() {
61		cmd.Dir = ctx.Dir
62		cmd.Command = append(cmd.Command, ".")
63		return closeBuildContext(t, ctx)
64	}
65}
66
67// WithFile adds the specified file (with content) in the build context
68func WithFile(name, content string) func(*fakecontext.Fake) error {
69	return fakecontext.WithFile(name, content)
70}
71
72func closeBuildContext(t testing.TB, ctx *fakecontext.Fake) func() {
73	return func() {
74		if err := ctx.Close(); err != nil {
75			t.Fatal(err)
76		}
77	}
78}
79