/
build.go
85 lines (65 loc) · 1.87 KB
/
build.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
package docker
import (
"fmt"
"io"
"io/ioutil"
"time"
"github.com/docker/docker/api/types"
"github.com/docker/docker/pkg/jsonmessage"
"github.com/docker/docker/pkg/progress"
"github.com/docker/docker/pkg/streamformatter"
cache "github.com/patrickmn/go-cache"
)
var (
imageBuildCache *cache.Cache
)
func (c *Client) ImageBuild(name string, dockerfilePath string, archiveReader io.Reader) error {
// Setup an upload progress bar
stdout := c.options.stdout
if stdout == nil {
stdout = NewOutStream(ioutil.Discard)
}
stderr := c.options.stderr
if stderr == nil {
stderr = NewOutStream(ioutil.Discard)
}
progressOutput := streamformatter.NewProgressOutput(streamformatter.NewStdoutWriter(stdout))
buildCtx, _, err := getContextFromReader(ioutil.NopCloser(archiveReader), dockerfilePath)
if err != nil {
return err
}
var body io.Reader = progress.NewProgressReader(buildCtx, progressOutput, 0, "", "Sending build context to Docker daemon")
buildOptions := types.ImageBuildOptions{
Dockerfile: dockerfilePath,
Tags: []string{name},
}
response, err := c.Client.ImageBuild(c.options.context, body, buildOptions)
if err != nil {
fmt.Fprintf(stderr, "%v", err)
return err
}
defer response.Body.Close()
err = jsonmessage.DisplayJSONMessagesStream(response.Body, stdout, stdout.FD(), stdout.IsTerminal(), nil)
if err != nil {
fmt.Fprintf(stderr, "%v", err)
return err
}
return nil
}
func (c *Client) ImageBuildCached(name string, dockerReader io.Reader) error {
if imageBuildCache == nil {
return c.ImageBuild(name, "Dockerfile", dockerReader)
}
if _, found := imageBuildCache.Get(name); found {
return nil
}
err := c.ImageBuild(name, "Dockerfile", dockerReader)
if err != nil {
return err
}
imageBuildCache.Set(name, time.Now(), cache.DefaultExpiration)
return nil
}
func init() {
imageBuildCache = cache.New(5*time.Hour, 24*time.Hour)
}