-
Notifications
You must be signed in to change notification settings - Fork 47
/
apk.go
90 lines (73 loc) · 2.42 KB
/
apk.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
package apk
import (
"fmt"
"io"
"log"
"net/http"
"github.com/chainguard-dev/go-apk/pkg/apk"
"github.com/wolfi-dev/wolfictl/pkg/versions"
"github.com/pkg/errors"
)
type Context struct {
client *http.Client
indexURL string
}
func New(client *http.Client, indexURL string) Context {
return Context{
client: client,
indexURL: indexURL,
}
}
func (c Context) GetApkPackages() (map[string]*apk.Package, error) {
req, err := http.NewRequest("GET", c.indexURL, nil)
if err != nil {
return nil, err
}
resp, err := c.client.Do(req)
if err != nil {
return nil, errors.Wrapf(err, "failed getting URI %s", c.indexURL)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("non ok http response for URI %s code: %v", c.indexURL, resp.StatusCode)
}
return ParseApkIndex(resp.Body)
}
func ParseUnpackedApkIndex(indexData io.ReadCloser) (map[string]*apk.Package, error) {
wolfiPackages := make(map[string]*apk.Package)
packages, err := apk.ParsePackageIndex(indexData)
if err != nil {
return nil, errors.Wrapf(err, "failed to parse response %v", indexData)
}
return getLatestPackagesMap(packages, wolfiPackages)
}
func getLatestPackagesMap(apkIndexPackages []*apk.Package, wolfiPackages map[string]*apk.Package) (map[string]*apk.Package, error) {
for _, p := range apkIndexPackages {
if wolfiPackages[p.Name] != nil {
existingPackageVersion, err := versions.NewVersion(wolfiPackages[p.Name].Version)
if err != nil {
return nil, errors.Wrapf(err, "failed to create a version for package %s from %s", p.Name, wolfiPackages[p.Name].Version)
}
apkPackageVersion, err := versions.NewVersion(p.Version)
if err != nil {
return nil, errors.Wrapf(err, "failed to create a new version for package %s from %s", p.Name, p.Version)
}
// replace in our map if we find a newer version in the APKINDEX
if existingPackageVersion.LessThan(apkPackageVersion) {
wolfiPackages[p.Name] = p
}
} else {
wolfiPackages[p.Name] = p
}
}
log.Printf("found %d latest apk index package versions", len(wolfiPackages))
return wolfiPackages, nil
}
func ParseApkIndex(indexData io.ReadCloser) (map[string]*apk.Package, error) {
wolfiPackages := make(map[string]*apk.Package)
apkIndex, err := apk.IndexFromArchive(indexData)
if err != nil {
return nil, errors.Wrapf(err, "failed to parse response %v", indexData)
}
return getLatestPackagesMap(apkIndex.Packages, wolfiPackages)
}