-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathzipFolder.go
120 lines (89 loc) · 1.85 KB
/
zipFolder.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
package main
import (
"archive/zip"
"io"
"os"
"path/filepath"
"strings"
)
func zipFolder(source, target string, includePathInZipFn func(string, bool) bool) error {
zipfile, err := os.Create(target)
if err != nil {
return err
}
defer zipfile.Close()
archive := zip.NewWriter(zipfile)
defer archive.Close()
filepath.Walk(source, func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
path = strings.Replace(path, "\\", "/", -1)
sourcePath := strings.Replace(source, "\\", "/", -1)
relPath := strings.TrimPrefix(path, sourcePath)
if relPath == "" {
return nil
}
relPath = strings.TrimLeft(relPath, "/")
isDir := info.IsDir()
if isDir {
relPath += "/"
}
if !includePathInZipFn(relPath, isDir) {
return nil
}
header, err := zip.FileInfoHeader(info)
if err != nil {
return err
}
header.Name = relPath
if !info.IsDir() {
header.Method = zip.Deflate
}
writer, err := archive.CreateHeader(header)
if err != nil {
return err
}
if info.IsDir() {
return nil
}
file, err := os.Open(path)
if err != nil {
return err
}
defer file.Close()
_, err = io.Copy(writer, file)
return err
})
return err
}
func extractZip(src, dest string) error {
reader, err := zip.OpenReader(src)
if err != nil {
return err
}
defer reader.Close()
for _, f := range reader.Reader.File {
zipped, err := f.Open()
if err != nil {
return err
}
defer zipped.Close()
path := filepath.Join(dest, f.Name)
if f.FileInfo().IsDir() {
os.MkdirAll(path, 0777)
} else {
dirPath := filepath.Dir(path)
os.MkdirAll(dirPath, 0777)
writer, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE, f.Mode())
if err != nil {
return err
}
defer writer.Close()
if _, err = io.Copy(writer, zipped); err != nil {
return err
}
}
}
return nil
}