-
Notifications
You must be signed in to change notification settings - Fork 23
/
generator_gomod.go
103 lines (87 loc) · 2.4 KB
/
generator_gomod.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
package dalec
import (
"path/filepath"
"github.com/moby/buildkit/client/llb"
"github.com/pkg/errors"
)
const (
gomodCacheDir = "/go/pkg/mod"
)
func (s *Source) isGomod() bool {
for _, gen := range s.Generate {
if gen.Gomod != nil {
return true
}
}
return false
}
// HasGomods returns true if any of the sources in the spec are a go module.
func (s *Spec) HasGomods() bool {
for _, src := range s.Sources {
if src.isGomod() {
return true
}
}
return false
}
func withGomod(g *SourceGenerator, srcSt, worker llb.State, opts ...llb.ConstraintsOpt) func(llb.State) llb.State {
return func(in llb.State) llb.State {
workDir := "/work/src"
joinedWorkDir := filepath.Join(workDir, g.Subpath)
srcMount := llb.AddMount(workDir, srcSt)
paths := g.Gomod.Paths
if g.Gomod.Paths == nil {
paths = []string{"."}
}
for _, path := range paths {
in = worker.Run(
ShArgs("go mod download"),
llb.AddEnv("GOMODCACHE", gomodCacheDir),
llb.Dir(filepath.Join(joinedWorkDir, path)),
srcMount,
WithConstraints(opts...),
).AddMount(gomodCacheDir, in)
}
return in
}
}
func (s *Spec) gomodSources() map[string]Source {
sources := map[string]Source{}
for name, src := range s.Sources {
if src.isGomod() {
sources[name] = src
}
}
return sources
}
// GomodDeps returns an [llb.State] containing all the go module dependencies for the spec
// for any sources that have a gomod generator specified.
// If there are no sources with a gomod generator, this will return a nil state.
func (s *Spec) GomodDeps(sOpt SourceOpts, worker llb.State, opts ...llb.ConstraintsOpt) (*llb.State, error) {
sources := s.gomodSources()
if len(sources) == 0 {
return nil, nil
}
deps := llb.Scratch()
// Get the patched sources for the go modules
// This is needed in case a patch includes changes to go.mod or go.sum
patched, err := s.getPatchedSources(sOpt, worker, func(name string) bool {
_, ok := sources[name]
return ok
}, opts...)
if err != nil {
return nil, errors.Wrap(err, "failed to get patched sources")
}
sorted := SortMapKeys(patched)
for _, key := range sorted {
src := s.Sources[key]
opts := append(opts, ProgressGroup("Fetch go module dependencies for source: "+key))
deps = deps.With(func(in llb.State) llb.State {
for _, gen := range src.Generate {
in = in.With(withGomod(gen, patched[key], worker, opts...))
}
return in
})
}
return &deps, nil
}