-
Notifications
You must be signed in to change notification settings - Fork 2.4k
/
fixture.go
112 lines (103 loc) · 2.23 KB
/
fixture.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
package main
import (
"fmt"
"io"
"os"
"path/filepath"
"strings"
"github.com/google/go-containerregistry/pkg/crane"
v1 "github.com/google/go-containerregistry/pkg/v1"
"github.com/magefile/mage/sh"
)
func fixtureContainerImages() error {
const (
testImages = "ghcr.io/aquasecurity/trivy-test-images"
dir = "integration/testdata/fixtures/images/"
)
if err := os.MkdirAll(dir, 0750); err != nil {
return err
}
tags, err := crane.ListTags(testImages)
if err != nil {
return err
}
for _, tag := range tags {
fileName := tag + ".tar.gz"
filePath := filepath.Join(dir, fileName)
if exists(filePath) {
continue
}
fmt.Printf("Downloading %s...\n", tag)
imgName := fmt.Sprintf("%s:%s", testImages, tag)
img, err := crane.Pull(imgName)
if err != nil {
return err
}
tarPath := strings.TrimSuffix(filePath, ".gz")
if err = crane.Save(img, imgName, tarPath); err != nil {
return err
}
if err = sh.Run("gzip", tarPath); err != nil {
return err
}
}
return nil
}
func fixtureVMImages() error {
const (
testVMImages = "ghcr.io/aquasecurity/trivy-test-vm-images"
titleAnnotation = "org.opencontainers.image.title"
dir = "integration/testdata/fixtures/vm-images/"
)
if err := os.MkdirAll(dir, 0750); err != nil {
return err
}
tags, err := crane.ListTags(testVMImages)
if err != nil {
return err
}
for _, tag := range tags {
img, err := crane.Pull(fmt.Sprintf("%s:%s", testVMImages, tag))
if err != nil {
return err
}
manifest, err := img.Manifest()
if err != nil {
return err
}
layers, err := img.Layers()
if err != nil {
return err
}
for i, layer := range layers {
fileName, ok := manifest.Layers[i].Annotations[titleAnnotation]
if !ok {
continue
}
filePath := filepath.Join(dir, fileName)
if exists(filePath) {
return nil
}
fmt.Printf("Downloading %s...\n", fileName)
if err = saveLayer(layer, filePath); err != nil {
return err
}
}
}
return nil
}
func saveLayer(layer v1.Layer, filePath string) error {
f, err := os.Create(filePath)
if err != nil {
return err
}
defer f.Close()
c, err := layer.Compressed()
if err != nil {
return err
}
if _, err = io.Copy(f, c); err != nil {
return err
}
return nil
}