-
Notifications
You must be signed in to change notification settings - Fork 17
/
buildpack.go
453 lines (353 loc) · 11.3 KB
/
buildpack.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
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
/*
* Copyright 2018-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package libpak
import (
"fmt"
"os"
"sort"
"strconv"
"strings"
"github.com/Masterminds/semver/v3"
"github.com/buildpacks/libcnb"
"github.com/heroku/color"
"github.com/paketo-buildpacks/libpak/bard"
)
// BuildpackConfiguration represents a build or launch configuration parameter.
type BuildpackConfiguration struct {
// Build indicates whether the configuration is for build-time. Optional.
Build bool `toml:"build"`
// Default is the default value of the configuration parameter. Optional.
Default string `toml:"default"`
// Description is the description of the configuration parameter.
Description string `toml:"description"`
// Launch indicates whether the configuration is for launch-time. Optional.
Launch bool `toml:"launch"`
// Name is the environment variable name of the configuration parameter.
Name string `toml:"name"`
}
// BuildpackDependencyLicense represents a license that a BuildpackDependency is distributed under. At least one of
// Name or URI MUST be specified.
type BuildpackDependencyLicense struct {
// Type is the type of the license. This is typically the SPDX short identifier.
Type string `toml:"type"`
// URI is the location where the license can be found.
URI string `toml:"uri"`
}
// BuildpackDependency describes a dependency known to the buildpack.
type BuildpackDependency struct {
// ID is the dependency ID.
ID string `toml:"id"`
// Name is the dependency name.
Name string `toml:"name"`
// Version is the dependency version.
Version string `toml:"version"`
// URI is the dependency URI.
URI string `toml:"uri"`
// SHA256 is the hash of the dependency.
SHA256 string `toml:"sha256"`
// Stacks are the stacks the dependency is compatible with.
Stacks []string `toml:"stacks"`
// Licenses are the stacks the dependency is distributed under.
Licenses []BuildpackDependencyLicense `toml:"licenses"`
}
// AsBOMEntry renders a bill of materials entry describing the dependency.
//
// Deprecated: as of Buildpacks RFC 95, use `sherpa.BOMScanner` instead
func (b BuildpackDependency) AsBOMEntry() libcnb.BOMEntry {
return libcnb.BOMEntry{
Name: b.ID,
Metadata: map[string]interface{}{
"name": b.Name,
"version": b.Version,
"uri": b.URI,
"sha256": b.SHA256,
"stacks": b.Stacks,
"licenses": b.Licenses,
},
}
}
// BuildpackMetadata is an extension to libcnb.Buildpack's metadata with opinions.
type BuildpackMetadata struct {
// Configurations are environment variables that can be used at build time to configure the buildpack and launch
// time to configure the application.
Configurations []BuildpackConfiguration
// Dependencies are the dependencies known to the buildpack.
Dependencies []BuildpackDependency
// IncludeFiles describes the files to include in the package.
IncludeFiles []string
// PrePackage describes a command to invoke before packaging.
PrePackage string
}
// NewBuildpackMetadata creates a new instance of BuildpackMetadata from the contents of libcnb.Buildpack.Metadata
func NewBuildpackMetadata(metadata map[string]interface{}) (BuildpackMetadata, error) {
m := BuildpackMetadata{}
if v, ok := metadata["configurations"]; ok {
for _, v := range v.([]map[string]interface{}) {
var c BuildpackConfiguration
if v, ok := v["build"].(bool); ok {
c.Build = v
}
if v, ok := v["default"].(string); ok {
c.Default = v
}
if v, ok := v["description"].(string); ok {
c.Description = v
}
if v, ok := v["launch"].(bool); ok {
c.Launch = v
}
if v, ok := v["name"].(string); ok {
c.Name = v
}
m.Configurations = append(m.Configurations, c)
}
}
if v, ok := metadata["dependencies"]; ok {
for _, v := range v.([]map[string]interface{}) {
var d BuildpackDependency
if v, ok := v["id"].(string); ok {
d.ID = v
}
if v, ok := v["name"].(string); ok {
d.Name = v
}
if v, ok := v["version"].(string); ok {
d.Version = v
}
if v, ok := v["uri"].(string); ok {
d.URI = v
}
if v, ok := v["sha256"].(string); ok {
d.SHA256 = v
}
if v, ok := v["stacks"].([]interface{}); ok {
for _, v := range v {
d.Stacks = append(d.Stacks, v.(string))
}
}
if v, ok := v["licenses"].([]map[string]interface{}); ok {
for _, v := range v {
var l BuildpackDependencyLicense
if v, ok := v["type"].(string); ok {
l.Type = v
}
if v, ok := v["uri"].(string); ok {
l.URI = v
}
d.Licenses = append(d.Licenses, l)
}
}
m.Dependencies = append(m.Dependencies, d)
}
}
if v, ok := metadata["include-files"].([]interface{}); ok {
for _, v := range v {
m.IncludeFiles = append(m.IncludeFiles, v.(string))
}
}
if v, ok := metadata["pre-package"].(string); ok {
m.PrePackage = v
}
return m, nil
}
// ConfigurationResolver provides functionality for resolving a configuration value.
type ConfigurationResolver struct {
// Configurations are the configurations to resolve against
Configurations []BuildpackConfiguration
}
type configurationEntry struct {
Name string
Description string
Value string
}
func (c configurationEntry) String(nameLength int, valueLength int) string {
sb := strings.Builder{}
sb.WriteString("$")
sb.WriteString(c.Name)
for i := 0; i < nameLength-len(c.Name); i++ {
sb.WriteString(" ")
}
sb.WriteString(" ")
sb.WriteString(c.Value)
for i := 0; i < valueLength-len(c.Value); i++ {
sb.WriteString(" ")
}
if valueLength > 0 {
sb.WriteString(" ")
}
sb.WriteString(c.Description)
return sb.String()
}
// NewConfigurationResolver creates a new instance from buildpack metadata. Logs configuration options to the body
// level int the form 'Set $Name to configure $Description[. Default <i>$Default</i>.]'.
func NewConfigurationResolver(buildpack libcnb.Buildpack, logger *bard.Logger) (ConfigurationResolver, error) {
md, err := NewBuildpackMetadata(buildpack.Metadata)
if err != nil {
return ConfigurationResolver{}, fmt.Errorf("unable to unmarshal buildpack metadata\n%w", err)
}
cr := ConfigurationResolver{Configurations: md.Configurations}
if logger == nil {
return cr, nil
}
var (
build []configurationEntry
launch []configurationEntry
unknown []configurationEntry
nameLength int
valueLength int
)
sort.Slice(md.Configurations, func(i, j int) bool {
return md.Configurations[i].Name < md.Configurations[j].Name
})
for _, c := range md.Configurations {
s, _ := cr.Resolve(c.Name)
e := configurationEntry{
Name: c.Name,
Description: c.Description,
Value: s,
}
if l := len(e.Name); l > nameLength {
nameLength = l
}
if l := len(e.Value); l > valueLength {
valueLength = l
}
if c.Build {
build = append(build, e)
}
if c.Launch {
launch = append(launch, e)
}
if !c.Build && !c.Launch {
unknown = append(unknown, e)
}
}
f := color.New(color.Faint)
if len(build) > 0 {
logger.Header(f.Sprint("Build Configuration:"))
for _, e := range build {
logger.Body(e.String(nameLength, valueLength))
}
}
if len(launch) > 0 {
logger.Header(f.Sprint("Launch Configuration:"))
for _, e := range launch {
logger.Body(e.String(nameLength, valueLength))
}
}
if len(unknown) > 0 {
logger.Header(f.Sprint("Unknown Configuration:"))
for _, e := range unknown {
logger.Body(e.String(nameLength, valueLength))
}
}
return cr, nil
}
// Resolve resolves the value for a configuration option, returning the default value and false if it was not set.
func (c *ConfigurationResolver) Resolve(name string) (string, bool) {
if v, ok := os.LookupEnv(name); ok {
return v, ok
}
for _, c := range c.Configurations {
if c.Name == name {
return c.Default, false
}
}
return "", false
}
// ResolveBool resolves a boolean value for a configuration option. Returns true for 1, t, T, TRUE, true, True. Returns
// false for all other values or unset.
func (c *ConfigurationResolver) ResolveBool(name string) bool {
s, _ := c.Resolve(name)
t, err := strconv.ParseBool(s)
if err != nil {
return false
}
return t
}
// DependencyResolver provides functionality for resolving a dependency given a collection of constraints.
type DependencyResolver struct {
// Dependencies are the dependencies to resolve against.
Dependencies []BuildpackDependency
// StackID is the stack id of the build.
StackID string
}
// NewDependencyResolver creates a new instance from the buildpack metadata and stack id.
func NewDependencyResolver(context libcnb.BuildContext) (DependencyResolver, error) {
md, err := NewBuildpackMetadata(context.Buildpack.Metadata)
if err != nil {
return DependencyResolver{}, fmt.Errorf("unable to unmarshal buildpack metadata\n%w", err)
}
return DependencyResolver{Dependencies: md.Dependencies, StackID: context.StackID}, nil
}
// NoValidDependenciesError is returned when the resolver cannot find any valid dependencies given the constraints.
type NoValidDependenciesError struct {
// Message is the error message
Message string
}
func (n NoValidDependenciesError) Error() string {
return n.Message
}
// IsNoValidDependencies indicates whether an error is a NoValidDependenciesError.
func IsNoValidDependencies(err error) bool {
_, ok := err.(NoValidDependenciesError)
return ok
}
// Resolve returns the latest version of a dependency within the collection of Dependencies. The candidate set is first
// filtered by the constraints, then the remaining candidates are sorted for the latest result by semver semantics.
// Version can contain wildcards and defaults to "*" if not specified.
func (d *DependencyResolver) Resolve(id string, version string) (BuildpackDependency, error) {
if version == "" {
version = "*"
}
vc, err := semver.NewConstraint(version)
if err != nil {
return BuildpackDependency{}, fmt.Errorf("invalid constraint %s\n%w", vc, err)
}
var candidates []BuildpackDependency
for _, c := range d.Dependencies {
v, err := semver.NewVersion(c.Version)
if err != nil {
return BuildpackDependency{}, fmt.Errorf("unable to parse version %s\n%w", c.Version, err)
}
if c.ID == id && vc.Check(v) && d.contains(c.Stacks, d.StackID) {
candidates = append(candidates, c)
}
}
if len(candidates) == 0 {
return BuildpackDependency{}, NoValidDependenciesError{
Message: fmt.Sprintf("no valid dependencies for %s, %s, and %s in %s",
id, version, d.StackID, DependenciesFormatter(d.Dependencies)),
}
}
sort.Slice(candidates, func(i int, j int) bool {
a, _ := semver.NewVersion(candidates[i].Version)
b, _ := semver.NewVersion(candidates[j].Version)
return a.GreaterThan(b)
})
return candidates[0], nil
}
func (DependencyResolver) contains(candidates []string, value string) bool {
if len(candidates) == 0 {
return true
}
for _, c := range candidates {
if c == value || c == "*" {
return true
}
}
return false
}