-
Notifications
You must be signed in to change notification settings - Fork 161
/
stemcell_archive_with_metadata.go
89 lines (69 loc) · 1.89 KB
/
stemcell_archive_with_metadata.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
package director
import (
"archive/tar"
"compress/gzip"
"io"
"os"
"gopkg.in/yaml.v2"
bosherr "github.com/cloudfoundry/bosh-utils/errors"
boshsys "github.com/cloudfoundry/bosh-utils/system"
)
type StemcellArchiveWithMetadata struct {
path string
fileName string
fs boshsys.FileSystem
}
func NewFSStemcellArchive(path string, fs boshsys.FileSystem) (stemcellArchive StemcellArchive) {
return StemcellArchiveWithMetadata{path, "stemcell.MF", fs}
}
func (a StemcellArchiveWithMetadata) Info() (StemcellMetadata, error) {
bytes, err := a.readMFBytes()
if err != nil {
return StemcellMetadata{}, err
}
return a.extractNameAndVersion(bytes)
}
func (a StemcellArchiveWithMetadata) File() (UploadFile, error) {
file, err := a.fs.OpenFile(a.path, os.O_RDONLY, 0)
if err != nil {
return nil, bosherr.WrapErrorf(err, "Opening archive")
}
return file, nil
}
func (a StemcellArchiveWithMetadata) readMFBytes() ([]byte, error) {
file, err := a.fs.OpenFile(a.path, os.O_RDONLY, 0)
if err != nil {
return nil, bosherr.WrapErrorf(err, "Opening archive")
}
defer file.Close()
gr, err := gzip.NewReader(file)
if err != nil {
return nil, err
}
defer gr.Close()
tr := tar.NewReader(gr)
for {
hdr, err := tr.Next()
if err == io.EOF {
break
}
if err != nil {
return nil, bosherr.WrapErrorf(err, "Reading next tar entry")
}
if hdr.Name == a.fileName || hdr.Name == "./"+a.fileName {
bytes, err := io.ReadAll(tr)
if err != nil {
return nil, bosherr.WrapErrorf(err, "Reading '%s' entry", a.fileName)
}
return bytes, nil
}
}
return nil, bosherr.Errorf("Missing '%s'", a.fileName)
}
func (a StemcellArchiveWithMetadata) extractNameAndVersion(bytes []byte) (metadata StemcellMetadata, err error) {
err = yaml.Unmarshal(bytes, &metadata)
if err != nil {
return metadata, bosherr.WrapErrorf(err, "Unmarshalling '%s'", a.fileName)
}
return metadata, nil
}