-
Notifications
You must be signed in to change notification settings - Fork 4
/
build.go
247 lines (210 loc) · 7.18 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
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
package dotnetpublish
import (
"errors"
"fmt"
"os"
"path/filepath"
"time"
"github.com/Netflix/go-env"
"github.com/mattn/go-shellwords"
"github.com/paketo-buildpacks/packit/v2"
"github.com/paketo-buildpacks/packit/v2/chronos"
"github.com/paketo-buildpacks/packit/v2/fs"
"github.com/paketo-buildpacks/packit/v2/sbom"
"github.com/paketo-buildpacks/packit/v2/scribe"
"github.com/paketo-buildpacks/packit/v2/servicebindings"
)
//go:generate faux --interface SymlinkManager --output fakes/symlink_manager.go
type SymlinkManager interface {
Link(oldname, newname string) error
Unlink(path string) error
}
//go:generate faux --interface SourceRemover --output fakes/source_remover.go
type SourceRemover interface {
Remove(workingDir, publishOutputDir string, excludedFiles ...string) error
}
//go:generate faux --interface PublishProcess --output fakes/publish_process.go
type PublishProcess interface {
Execute(workingDir, nugetCachePath, projectPath, outputPath string, debug bool, flags []string) error
}
//go:generate faux --interface BindingResolver --output fakes/binding_resolver.go
type BindingResolver interface {
Resolve(typ, provider, platformDir string) ([]servicebindings.Binding, error)
}
//go:generate faux --interface Slicer --output fakes/slicer.go
type Slicer interface {
Slice(assetsFile string) (pkgs, earlyPkgs, projects packit.Slice, err error)
}
type Configuration struct {
LogLevel string `env:"BP_LOG_LEVEL"`
DebugEnabled bool `env:"BP_DEBUG_ENABLED"`
DisableOutputSlicing bool `env:"BP_DOTNET_DISABLE_BUILDPACK_OUTPUT_SLICING"`
ProjectPath string `env:"BP_DOTNET_PROJECT_PATH"`
PublishFlags []string
RawPublishFlags string `env:"BP_DOTNET_PUBLISH_FLAGS"`
}
//go:generate faux --interface SBOMGenerator --output fakes/sbom_generator.go
type SBOMGenerator interface {
Generate(dir string) (sbom.SBOM, error)
}
func Build(
config Configuration,
sourceRemover SourceRemover,
bindingResolver BindingResolver,
homeDir string,
symlinker SymlinkManager,
publishProcess PublishProcess,
slicer Slicer,
clock chronos.Clock,
logger scribe.Emitter,
sbomGenerator SBOMGenerator,
) packit.BuildFunc {
return func(context packit.BuildContext) (packit.BuildResult, error) {
logger.Title("%s %s", context.BuildpackInfo.Name, context.BuildpackInfo.Version)
logger.Debug.Process("Build configuration:")
es, err := env.Marshal(&config)
if err != nil {
// not tested
return packit.BuildResult{}, fmt.Errorf("parsing build configuration: %w", err)
}
for envVar := range es {
logger.Debug.Subprocess("%s: %s", envVar, es[envVar])
}
logger.Debug.Break()
tempDir, err := os.MkdirTemp("", "dotnet-publish-output")
if err != nil {
return packit.BuildResult{}, fmt.Errorf("could not create temp directory: %w", err)
}
shellwordsParser := shellwords.NewParser()
shellwordsParser.ParseEnv = true
config.PublishFlags, err = shellwordsParser.Parse(config.RawPublishFlags)
if err != nil {
return packit.BuildResult{}, fmt.Errorf("failed to parse flags for dotnet publish: %w", err)
}
globalNugetPath, err := getBinding("nugetconfig", "", context.Platform.Path, "nuget.config", bindingResolver, logger)
if err != nil {
return packit.BuildResult{}, err
}
if globalNugetPath != "" {
logger.Debug.Process("Setting up NuGet.Config from service binding")
err = symlinker.Link(globalNugetPath, filepath.Join(homeDir, ".nuget", "NuGet", "NuGet.Config"))
if err != nil {
return packit.BuildResult{}, err
}
logger.Debug.Break()
}
nugetCache, err := context.Layers.Get("nuget-cache")
if err != nil {
return packit.BuildResult{}, err
}
stack, ok := nugetCache.Metadata["stack"].(string)
if ok && stack != context.Stack {
nugetCache, err = nugetCache.Reset()
if err != nil {
return packit.BuildResult{}, err
}
}
if nugetCache.Metadata == nil {
nugetCache.Metadata = make(map[string]interface{})
}
nugetCache.Metadata["stack"] = context.Stack
nugetCache.Cache = true
logger.Process("Executing build process")
err = publishProcess.Execute(context.WorkingDir, nugetCache.Path, config.ProjectPath, tempDir, config.DebugEnabled, config.PublishFlags)
if err != nil {
return packit.BuildResult{}, err
}
var slices []packit.Slice
if !config.DisableOutputSlicing {
logger.Process("Dividing build output into layers to optimize cache reuse")
pkg, early, project, err := slicer.Slice(filepath.Join(context.WorkingDir, config.ProjectPath, "obj", "project.assets.json"))
if err != nil {
return packit.BuildResult{}, err
}
for _, slice := range []packit.Slice{pkg, early, project} {
if len(slice.Paths) > 0 {
slices = append(slices, slice)
}
}
logger.Break()
} else {
logger.Debug.Process("Skipping output slicing")
logger.Debug.Break()
}
logger.GeneratingSBOM(context.WorkingDir)
var sbomContent sbom.SBOM
duration, err := clock.Measure(func() error {
sbomContent, err = sbomGenerator.Generate(context.WorkingDir)
return err
})
if err != nil {
return packit.BuildResult{}, err
}
logger.Action("Completed in %s", duration.Round(time.Millisecond))
logger.Break()
logger.FormattingSBOM(context.BuildpackInfo.SBOMFormats...)
formattedSBOM, err := sbomContent.InFormats(context.BuildpackInfo.SBOMFormats...)
if err != nil {
return packit.BuildResult{}, err
}
logger.Process("Removing source code")
logger.Break()
err = sourceRemover.Remove(context.WorkingDir, tempDir)
if err != nil {
return packit.BuildResult{}, err
}
err = os.RemoveAll(tempDir)
if err != nil {
return packit.BuildResult{}, fmt.Errorf("could not remove temp directory: %w", err)
}
if globalNugetPath != "" {
err = symlinker.Unlink(filepath.Join(homeDir, ".nuget", "NuGet", "NuGet.Config"))
if err != nil {
return packit.BuildResult{}, err
}
}
var layers []packit.Layer
exists, err := fs.Exists(nugetCache.Path)
if exists {
if !fs.IsEmptyDir(nugetCache.Path) {
layers = append(layers, nugetCache)
}
}
if err != nil {
return packit.BuildResult{}, err
}
for _, layer := range layers {
logger.Debug.Process("Setting up layer '%s'", layer.Name)
logger.Debug.Subprocess("Available at launch: %t", layer.Launch)
logger.Debug.Subprocess("Available to other buildpacks: %t", layer.Build)
logger.Debug.Subprocess("Cached for rebuilds: %t", layer.Cache)
logger.Debug.Break()
}
return packit.BuildResult{
Layers: layers,
Launch: packit.LaunchMetadata{
Slices: slices,
},
Build: packit.BuildMetadata{
SBOM: formattedSBOM,
},
}, nil
}
}
func getBinding(typ, provider, bindingsRoot, entry string, bindingResolver BindingResolver, logger scribe.Emitter) (string, error) {
bindings, err := bindingResolver.Resolve(typ, provider, bindingsRoot)
if err != nil {
return "", err
}
if len(bindings) > 1 {
return "", errors.New("binding resolver found more than one binding of type 'nugetconfig'")
}
if len(bindings) == 1 {
logger.Process("Loading nuget service binding")
if _, ok := bindings[0].Entries[entry]; !ok {
return "", fmt.Errorf("binding of type %s does not contain required entry %s", typ, entry)
}
return filepath.Join(bindings[0].Path, entry), nil
}
return "", nil
}