-
-
Notifications
You must be signed in to change notification settings - Fork 3k
/
unpack.go
98 lines (80 loc) · 1.6 KB
/
unpack.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
package mfsr
import (
"archive/tar"
"archive/zip"
"compress/gzip"
"fmt"
"io"
"os"
)
func unpackArchive(dist, binnom, path, out, atype string) error {
switch atype {
case "zip":
return unpackZip(dist, binnom, path, out)
case "tar.gz":
return unpackTgz(dist, binnom, path, out)
default:
return fmt.Errorf("unrecognized archive type: %s", atype)
}
}
func unpackTgz(dist, binnom, path, out string) error {
fi, err := os.Open(path)
if err != nil {
return err
}
defer fi.Close()
gzr, err := gzip.NewReader(fi)
if err != nil {
return err
}
defer gzr.Close()
var bin io.Reader
tarr := tar.NewReader(gzr)
loop:
for {
th, err := tarr.Next()
switch err {
default:
return err
case io.EOF:
break loop
case nil:
// continue
}
if th.Name == dist+"/"+binnom {
bin = tarr
break
}
}
if bin == nil {
return fmt.Errorf("no binary found in downloaded archive")
}
return writeToPath(bin, out)
}
func writeToPath(rc io.Reader, out string) error {
binfi, err := os.Create(out)
if err != nil {
return fmt.Errorf("error opening tmp bin path '%s': %s", out, err)
}
defer binfi.Close()
_, err = io.Copy(binfi, rc)
return err
}
func unpackZip(dist, binnom, path, out string) error {
zipr, err := zip.OpenReader(path)
if err != nil {
return fmt.Errorf("error opening zipreader: %s", err)
}
defer zipr.Close()
var bin io.ReadCloser
for _, fis := range zipr.File {
if fis.Name == dist+"/"+binnom {
rc, err := fis.Open()
if err != nil {
return fmt.Errorf("error extracting binary from archive: %s", err)
}
bin = rc
}
}
return writeToPath(bin, out)
}