-
Notifications
You must be signed in to change notification settings - Fork 303
/
main.go
108 lines (90 loc) · 2.05 KB
/
main.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
package main
import (
"context"
"encoding/json"
"flag"
"io"
"log"
"os"
"github.com/docker/docker/api/types"
"github.com/docker/docker/client"
"github.com/docker/docker/pkg/jsonmessage"
controlapi "github.com/moby/buildkit/api/services/control"
"github.com/pkg/errors"
"github.com/tilt-dev/tilt/internal/build"
)
var useCache bool
// A small utility for running Buildkit on the dockerfile
// in the current directory printing out all the buildkit api
// response protobufs.
func main() {
flag.BoolVar(&useCache, "cache", false, "Enable docker caching")
flag.Parse()
err := run()
if err != nil {
log.Fatal(err)
}
}
func run() error {
ctx := context.Background()
d, err := client.NewEnvClient()
if err != nil {
return err
}
d.NegotiateAPIVersion(ctx)
pr, pw := io.Pipe()
go func() {
err := build.TarPath(ctx, pw, ".")
if err != nil {
_ = pw.CloseWithError(err)
} else {
_ = pw.Close()
}
}()
opts := types.ImageBuildOptions{}
opts.Version = types.BuilderBuildKit
opts.Dockerfile = "Dockerfile"
opts.Context = pr
if !useCache {
opts.NoCache = true
}
response, err := d.ImageBuild(ctx, pr, opts)
if err != nil {
return err
}
defer func() {
_ = response.Body.Close()
}()
return readDockerOutput(ctx, response.Body)
}
func readDockerOutput(ctx context.Context, reader io.Reader) error {
decoder := json.NewDecoder(reader)
for decoder.More() {
message := jsonmessage.JSONMessage{}
err := decoder.Decode(&message)
if err != nil {
return errors.Wrap(err, "decoding docker output")
}
if messageIsFromBuildkit(message) {
err := writeBuildkitStatus(message.Aux)
if err != nil {
return err
}
}
}
return nil
}
func writeBuildkitStatus(aux *json.RawMessage) error {
var resp controlapi.StatusResponse
var dt []byte
if err := json.Unmarshal(*aux, &dt); err != nil {
return err
}
if err := (&resp).Unmarshal(dt); err != nil {
return err
}
return json.NewEncoder(os.Stdout).Encode(resp)
}
func messageIsFromBuildkit(msg jsonmessage.JSONMessage) bool {
return msg.ID == "moby.buildkit.trace"
}