forked from buildpacks/libcnb
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathexample_build_test.go
99 lines (85 loc) · 2.31 KB
/
example_build_test.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
package libcnb_test
import (
"os"
"path/filepath"
cdx "github.com/CycloneDX/cyclonedx-go"
"github.com/buildpacks/libcnb/v2"
"github.com/buildpacks/libcnb/v2/log"
)
const (
DefaultVersion = "0.1"
)
type Builder struct {
Logger log.Logger
}
// BuildpackPlan may contain multiple entries for a single buildpack, resolve
// into a single entry.
func resolve(plan libcnb.BuildpackPlan, name string) libcnb.BuildpackPlanEntry {
entry := libcnb.BuildpackPlanEntry{
Name: name,
Metadata: map[string]interface{}{},
}
for _, e := range plan.Entries {
for k, v := range e.Metadata {
entry.Metadata[k] = v
}
}
return entry
}
func populateLayer(layer libcnb.Layer, version string) (libcnb.Layer, error) {
exampleFile := filepath.Join(layer.Path, "example.txt")
os.WriteFile(exampleFile, []byte(version), 0600)
layer.SharedEnvironment.Default("EXAMPLE_FILE", exampleFile)
// Provide an SBOM
bom := cdx.NewBOM()
bom.Metadata = &cdx.Metadata{
Component: &cdx.Component{
Type: cdx.ComponentTypeFile,
Name: "example",
Version: version,
},
}
sbomPath := layer.SBOMPath(libcnb.CycloneDXJSON)
sbomFile, err := os.OpenFile(sbomPath, os.O_CREATE|os.O_WRONLY, 0600)
if err != nil {
return layer, err
}
defer sbomFile.Close()
encoder := cdx.NewBOMEncoder(sbomFile, cdx.BOMFileFormatJSON)
if err := encoder.Encode(bom); err != nil {
return layer, err
}
return layer, nil
}
func (b Builder) Build(context libcnb.BuildContext) (libcnb.BuildResult, error) {
// Reduce possible multiple buildpack plan entries to a single entry
entry := resolve(context.Plan, Provides)
result := libcnb.NewBuildResult()
// Read metadata from the buildpack plan, often contributed by libcnb.Requires
// of the Detect phase
version := DefaultVersion
if v, ok := entry.Metadata["version"].(string); ok {
version = v
}
// Create a layer
layer, err := context.Layers.Layer("example")
if err != nil {
return result, err
}
layer.LayerTypes = libcnb.LayerTypes{
Launch: true,
Build: true,
Cache: true,
}
layer, err = populateLayer(layer, version)
if err != nil {
return result, nil
}
result.Layers = append(result.Layers, layer)
return result, nil
}
func ExampleBuild() {
detector := Detector{log.New(os.Stdout)}
builder := Builder{log.New(os.Stdout)}
libcnb.BuildpackMain(detector.Detect, builder.Build)
}