-
-
Notifications
You must be signed in to change notification settings - Fork 3k
/
unpack.go
106 lines (89 loc) · 1.89 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
99
100
101
102
103
104
105
106
package migrations
import (
"archive/tar"
"archive/zip"
"compress/gzip"
"errors"
"fmt"
"io"
"os"
)
func unpackArchive(arcPath, atype, root, name, out string) error {
var err error
switch atype {
case "tar.gz":
err = unpackTgz(arcPath, root, name, out)
case "zip":
err = unpackZip(arcPath, root, name, out)
default:
err = fmt.Errorf("unrecognized archive type: %s", atype)
}
if err != nil {
return err
}
return nil
}
func unpackTgz(arcPath, root, name, out string) error {
fi, err := os.Open(arcPath)
if err != nil {
return fmt.Errorf("cannot open archive file: %w", err)
}
defer fi.Close()
gzr, err := gzip.NewReader(fi)
if err != nil {
return fmt.Errorf("error opening gzip reader: %w", err)
}
defer gzr.Close()
var bin io.Reader
tarr := tar.NewReader(gzr)
lookFor := root + "/" + name
for {
th, err := tarr.Next()
if err != nil {
if err == io.EOF {
break
}
return fmt.Errorf("cannot read archive: %w", err)
}
if th.Name == lookFor {
bin = tarr
break
}
}
if bin == nil {
return errors.New("no binary found in archive")
}
return writeToPath(bin, out)
}
func unpackZip(arcPath, root, name, out string) error {
zipr, err := zip.OpenReader(arcPath)
if err != nil {
return fmt.Errorf("error opening zip reader: %w", err)
}
defer zipr.Close()
lookFor := root + "/" + name
var bin io.ReadCloser
for _, fis := range zipr.File {
if fis.Name == lookFor {
rc, err := fis.Open()
if err != nil {
return fmt.Errorf("error extracting binary from archive: %w", err)
}
bin = rc
break
}
}
if bin == nil {
return errors.New("no binary found in 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 creating output file '%s': %w", out, err)
}
defer binfi.Close()
_, err = io.Copy(binfi, rc)
return err
}