-
Notifications
You must be signed in to change notification settings - Fork 7
/
zip.go
72 lines (64 loc) · 1.35 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
package crx3
import (
"archive/zip"
"fmt"
"io"
"os"
"path/filepath"
)
// ZipTo creates a ZIP archive with the specified
// filename and adds all files from the given directory to it.
func ZipTo(filename string, dirname string) error {
file, err := os.Create(filename)
if err != nil {
return err
}
defer file.Close()
return Zip(file, dirname)
}
// Zip creates a *.zip archive and adds all files
// from the specified directory to it.
func Zip(dst io.Writer, dirname string) error {
if !isDir(dirname) {
return fmt.Errorf("%w: %s", ErrPathNotFound, dirname)
}
wz := zip.NewWriter(dst)
defer wz.Close()
return filepath.Walk(dirname,
func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
if info.IsDir() {
return nil
}
relpath, err := filepath.Rel(dirname, path)
if err != nil {
return err
}
return writeToZip(wz, path, relpath)
})
}
func writeToZip(w *zip.Writer, filename string, metaname string) error {
fd, err := os.Open(filename)
if err != nil {
return err
}
defer fd.Close()
info, err := fd.Stat()
if err != nil {
return err
}
header, err := zip.FileInfoHeader(info)
if err != nil {
return err
}
header.Name = metaname
header.Method = zip.Deflate
writer, err := w.CreateHeader(header)
if err != nil {
return err
}
_, err = io.Copy(writer, fd)
return err
}