-
Notifications
You must be signed in to change notification settings - Fork 162
/
archive_with_metadata.go
105 lines (82 loc) · 2.26 KB
/
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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
package director
import (
"archive/tar"
"compress/gzip"
"io"
"io/ioutil"
"os"
bosherr "github.com/cloudfoundry/bosh-utils/errors"
boshsys "github.com/cloudfoundry/bosh-utils/system"
"gopkg.in/yaml.v2"
)
type FSArchiveWithMetadata struct {
path string
fileName string
fs boshsys.FileSystem
}
func NewFSReleaseArchive(path string, fs boshsys.FileSystem) ReleaseArchive {
return NewFSArchiveWithMetadata(path, "release.MF", fs)
}
func NewFSStemcellArchive(path string, fs boshsys.FileSystem) ReleaseArchive {
return NewFSArchiveWithMetadata(path, "stemcell.MF", fs)
}
func NewFSArchiveWithMetadata(path, fileName string, fs boshsys.FileSystem) StemcellArchive {
return FSArchiveWithMetadata{path: path, fileName: fileName, fs: fs}
}
func (a FSArchiveWithMetadata) Info() (string, string, error) {
bytes, err := a.readMFBytes()
if err != nil {
return "", "", err
}
return a.extractNameAndVersion(bytes)
}
func (a FSArchiveWithMetadata) 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 FSArchiveWithMetadata) 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 := ioutil.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 FSArchiveWithMetadata) extractNameAndVersion(bytes []byte) (string, string, error) {
type mfSchema struct {
Name string `yaml:"name"`
Version string `yaml:"version"`
// other fields ignored
}
var mf mfSchema
err := yaml.Unmarshal(bytes, &mf)
if err != nil {
return "", "", bosherr.WrapErrorf(err, "Unmarshalling '%s'", a.fileName)
}
return mf.Name, mf.Version, nil
}