-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathzip.go
92 lines (87 loc) · 1.71 KB
/
zip.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
package building
import (
"archive/zip"
"compress/flate"
"errors"
"io"
"os"
"path/filepath"
)
func (b *B) Zip(args ...string) compression {
return makeCompression(Zip{}, args)
}
type Zip struct{}
func (z Zip) Write(w io.Writer, level int, dst string, srcs []fileset) error {
if dst != "-" {
f, err := os.Create(dst)
if err != nil {
return err
}
defer b.Close(f)
w = f
}
zw := zip.NewWriter(w)
zw.RegisterCompressor(zip.Deflate, func(w io.Writer) (io.WriteCloser, error) {
return flate.NewWriter(w, level)
})
defer b.Close(zw)
return walk(srcs, func(path, rel string, info os.FileInfo) error {
if info.IsDir() {
return nil
}
w, err := zw.Create(rel)
if err != nil {
return err
}
f, err := os.Open(path)
if err != nil {
return err
}
defer b.Close(f)
_, err = io.Copy(w, f)
return err
})
}
func unzipFiles(src, dst string) error {
var zr *zip.Reader
if src == "-" {
// $$$$ MAT to do
return errors.New("reading from buffer not supported")
}
r, err := zip.OpenReader(src)
if err != nil {
return err
}
defer b.Close(r)
zr = &r.Reader
for _, file := range zr.File {
path := filepath.Join(dst, file.Name)
info := file.FileInfo()
if info.IsDir() {
// $$$$ MAT pretty sure zip has only files
if err := os.MkdirAll(path, info.Mode()); err != nil {
return err
}
continue
}
dir := filepath.Dir(path)
if err := os.MkdirAll(dir, 0755); err != nil {
return err
}
f, err := os.OpenFile(path, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, info.Mode())
if err != nil {
return err
}
defer b.Close(f)
r, err := file.Open()
if err != nil {
return err
}
defer b.Close(r)
_, err = io.Copy(f, r)
if err != nil {
return err
}
}
return nil
}