-
Notifications
You must be signed in to change notification settings - Fork 0
/
frontend.go
105 lines (89 loc) · 1.93 KB
/
frontend.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
package buildpack
import (
"context"
"encoding/json"
"fmt"
"os"
"sort"
"github.com/moby/buildkit/client/llb"
"github.com/moby/buildkit/exporter/containerimage/exptypes"
"github.com/moby/buildkit/frontend/gateway/client"
specs "github.com/opencontainers/image-spec/specs-go/v1"
"github.com/pkg/errors"
)
const (
contextKey = "context"
)
func Frontend(ctx context.Context, c client.Client) (*client.Result, error) {
inputs, err := c.Inputs(ctx)
if err != nil {
return nil, err
}
context, ok := inputs[contextKey]
if !ok {
return nil, fmt.Errorf(`must provide frontend input "context"`)
}
delete(inputs, contextKey)
def, err := context.Marshal(llb.WithCustomName("Autodetecting from context"))
if err != nil {
return nil, err
}
res, err := c.Solve(ctx, client.SolveRequest{
Definition: def.ToPB(),
})
if err != nil {
return nil, err
}
ref, err := res.SingleRef()
if err != nil {
return nil, err
}
var keys []string
for key := range inputs {
keys = append(keys, key)
}
sort.Strings(keys)
var detect string
for _, key := range keys {
_, err = ref.StatFile(ctx, client.StatRequest{
Path: key,
})
if err != nil {
if os.IsNotExist(errors.Cause(err)) {
continue
}
return nil, err
}
detect = key
break
}
if detect == "" {
return nil, fmt.Errorf("failed to autodetect")
}
st := inputs[detect]
def, err = st.Marshal(llb.WithCustomNamef("Detected %s project", detect))
if err != nil {
return nil, err
}
res, err = c.Solve(ctx, client.SolveRequest{
Definition: def.ToPB(),
})
if err != nil {
return nil, err
}
if _, ok := res.Metadata[exptypes.ExporterImageConfigKey]; !ok {
img := specs.Image{
Config: specs.ImageConfig{
Env: st.Env(),
Entrypoint: st.GetArgs(),
WorkingDir: st.GetDir(),
},
}
config, err := json.Marshal(img)
if err != nil {
return nil, err
}
res.AddMeta(exptypes.ExporterImageConfigKey, config)
}
return res, nil
}