-
Notifications
You must be signed in to change notification settings - Fork 6
/
gozip.go
124 lines (112 loc) · 2.3 KB
/
gozip.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
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
package gozip
import (
"archive/zip"
"errors"
"io"
"io/ioutil"
"os"
"path"
"path/filepath"
)
// IsZip checks to see if path is already a zip file
func IsZip(path string) bool {
r, err := zip.OpenReader(path)
if err == nil {
r.Close()
return true
}
return false
}
// Zip takes all the files (dirs) and zips them into path
func Zip(path string, dirs []string) (err error) {
if IsZip(path) {
return errors.New(path + " is already a zip file")
}
f, err := os.OpenFile(path, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0644)
if err != nil {
return
}
defer f.Close()
startoffset, err := f.Seek(0, os.SEEK_END)
if err != nil {
return
}
w := zip.NewWriter(f)
w.SetOffset(startoffset)
for _, dir := range dirs {
err = filepath.Walk(dir, func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
fh, err := zip.FileInfoHeader(info)
if err != nil {
return err
}
fh.Name = path
p, err := w.CreateHeader(fh)
if err != nil {
return err
}
if !info.IsDir() {
content, err := ioutil.ReadFile(path)
if err != nil {
return err
}
_, err = p.Write(content)
if err != nil {
return err
}
}
return err
})
}
err = w.Close()
return
}
// Unzip unzips the file zippath and puts it in destination
func Unzip(zippath string, destination string) (err error) {
r, err := zip.OpenReader(zippath)
if err != nil {
return err
}
for _, f := range r.File {
fullname := path.Join(destination, f.Name)
if f.FileInfo().IsDir() {
os.MkdirAll(fullname, f.FileInfo().Mode().Perm())
} else {
os.MkdirAll(filepath.Dir(fullname), 0755)
perms := f.FileInfo().Mode().Perm()
out, err := os.OpenFile(fullname, os.O_CREATE|os.O_RDWR, perms)
if err != nil {
return err
}
rc, err := f.Open()
if err != nil {
return err
}
_, err = io.CopyN(out, rc, f.FileInfo().Size())
if err != nil {
return err
}
rc.Close()
out.Close()
mtime := f.FileInfo().ModTime()
err = os.Chtimes(fullname, mtime, mtime)
if err != nil {
return err
}
}
}
return
}
// UnzipList Lists all the files in zip file
func UnzipList(path string) (list []string, err error) {
r, err := zip.OpenReader(path)
if err != nil {
return
}
for _, f := range r.File {
list = append(list, f.Name)
}
return
}