Debian Codegraph @

buildkit/client/llb/llbbuild/llbbuild.go

raw
1 package llbbuild
2
3 import (
4 "context"
5
6 "github.com/moby/buildkit/client/llb"
7 "github.com/moby/buildkit/solver/pb"
8 "github.com/moby/buildkit/util/apicaps"
9 digest "github.com/opencontainers/go-digest"
10 )
11
12 func Build(opt ...BuildOption) llb.StateOption {
13 return func(s llb.State) llb.State {
14 return s.WithOutput(NewBuildOp(s.Output(), opt...).Output())
15 }
16 }
17
18 func NewBuildOp(source llb.Output, opt ...BuildOption) llb.Vertex {
19 info := &BuildInfo{}
20 for _, o := range opt {
21 o(info)
22 }
23 return &build{source: source, info: info, constraints: info.Constraints}
24 }
25
26 type build struct {
27 cache llb.MarshalCache
28 source llb.Output
29 info *BuildInfo
30 constraints llb.Constraints
31 }
32
33 func (b *build) ToInput(ctx context.Context, c *llb.Constraints) (*pb.Input, error) {
34 dgst, _, _, _, err := b.Marshal(ctx, c)
35 if err != nil {
36 return nil, err
37 }
38 return &pb.Input{Digest: string(dgst), Index: 0}, nil
39 }
40
41 func (b *build) Vertex(context.Context, *llb.Constraints) llb.Vertex {
42 return b
43 }
44
45 func (b *build) Validate(context.Context, *llb.Constraints) error {
46 return nil
47 }
48
49 func (b *build) Marshal(ctx context.Context, c *llb.Constraints) (digest.Digest, []byte, *pb.OpMetadata, []*llb.SourceLocation, error) {
50 cache := b.cache.Acquire()
51 defer cache.Release()
52
53 if dgst, dt, md, srcs, err := cache.Load(c); err == nil {
54 return dgst, dt, md, srcs, nil
55 }
56
57 pbo := &pb.BuildOp{
58 Builder: int64(pb.LLBBuilder),
59 Inputs: map[string]*pb.BuildInput{
60 pb.LLBDefinitionInput: {Input: 0},
61 },
62 }
63
64 pbo.Attrs = map[string]string{}
65
66 if b.info.DefinitionFilename != "" {
67 pbo.Attrs[pb.AttrLLBDefinitionFilename] = b.info.DefinitionFilename
68 }
69
70 if b.constraints.Metadata.Caps == nil {
71 b.constraints.Metadata.Caps = make(map[apicaps.CapID]bool)
72 }
73 b.constraints.Metadata.Caps[pb.CapBuildOpLLBFileName] = true
74
75 pop, md := llb.MarshalConstraints(c, &b.constraints)
76 pop.Op = &pb.Op_Build{
77 Build: pbo,
78 }
79
80 inp, err := b.source.ToInput(ctx, c)
81 if err != nil {
82 return "", nil, nil, nil, err
83 }
84
85 pop.Inputs = append(pop.Inputs, inp)
86
87 dt, err := pop.Marshal()
88 if err != nil {
89 return "", nil, nil, nil, err
90 }
91 return cache.Store(dt, md, b.constraints.SourceLocations, c)
92 }
93
94 func (b *build) Output() llb.Output {
95 return b
96 }
97
98 func (b *build) Inputs() []llb.Output {
99 return []llb.Output{b.source}
100 }
101
102 type BuildInfo struct {
103 llb.Constraints
104 DefinitionFilename string
105 }
106
107 type BuildOption func(*BuildInfo)
108
109 func WithFilename(fn string) BuildOption {
110 return func(b *BuildInfo) {
111 b.DefinitionFilename = fn
112 }
113 }
114
115 func WithConstraints(co llb.ConstraintsOpt) BuildOption {
116 return func(b *BuildInfo) {
117 co.SetConstraintsOption(&b.Constraints)
118 }
119 }