-
Notifications
You must be signed in to change notification settings - Fork 0
/
build.go
120 lines (106 loc) · 2.32 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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
package docker
import (
"archive/tar"
"bytes"
"context"
"fmt"
"github.com/eddort/cubx/internal/streams"
"io"
"os"
"path/filepath"
"github.com/docker/docker/api/types"
"github.com/docker/docker/client"
"github.com/docker/docker/pkg/jsonmessage"
)
// Function for creating a tar archive from a directory
func tarDirectory(dir string) (*bytes.Buffer, error) {
buf := new(bytes.Buffer)
tw := tar.NewWriter(buf)
defer tw.Close()
err := filepath.Walk(dir, func(file string, fi os.FileInfo, err error) error {
if err != nil {
return err
}
fmt.Println(file)
hdr, err := tar.FileInfoHeader(fi, file)
if err != nil {
return err
}
// hdr.Name = file
relPath, err := filepath.Rel(dir, file)
if err != nil {
return err
}
hdr.Name = filepath.ToSlash(relPath)
if err := tw.WriteHeader(hdr); err != nil {
return err
}
if fi.Mode().IsRegular() {
f, err := os.Open(file)
if err != nil {
return err
}
defer f.Close()
if _, err := io.Copy(tw, f); err != nil {
return err
}
}
return nil
})
if err != nil {
return nil, err
}
return buf, nil
}
func PrintTarContents(buf *bytes.Buffer) error {
tr := tar.NewReader(bytes.NewReader(buf.Bytes()))
fmt.Println("Contents of tar:")
for {
hdr, err := tr.Next()
if err == io.EOF {
break
}
if err != nil {
return err
}
fmt.Println(hdr.Name)
}
return nil
}
// Basic function to build a Docker image with hash validation
func BuildImage(dockerfilePath, imageTag, contextDir string) error {
ctx := context.Background()
cli, err := client.NewClientWithOpts(client.FromEnv, client.WithAPIVersionNegotiation())
if err != nil {
return err
}
// TODO: force rebuild
found, err := imageExists(ctx, cli, imageTag)
if err != nil {
return err
}
if found {
return nil
}
fmt.Println("context build:", contextDir)
tarBuf, err := tarDirectory(contextDir)
if err != nil {
return err
}
// printTarContents(tarBuf)
buildOptions := types.ImageBuildOptions{
Dockerfile: filepath.Base(dockerfilePath),
Tags: []string{imageTag},
Remove: true,
}
buildResponse, err := cli.ImageBuild(ctx, tarBuf, buildOptions)
if err != nil {
return err
}
defer buildResponse.Body.Close()
err = jsonmessage.DisplayJSONMessagesToStream(buildResponse.Body, streams.NewOut(), nil)
if err != nil {
return err
}
return nil
}