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