-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathzip.go
129 lines (115 loc) · 2.55 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
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
125
126
127
128
129
package main
import (
"archive/zip"
"bytes"
"fmt"
"io"
"io/ioutil"
"net/http"
"os"
"path/filepath"
"runtime"
"strconv"
"strings"
dkignore "github.com/codeskyblue/dockerignore"
)
type Zip struct {
*zip.Writer
}
func sanitizedName(filename string) string {
if len(filename) > 1 && filename[1] == ':' &&
runtime.GOOS == "windows" {
filename = filename[2:]
}
filename = strings.TrimLeft(strings.Replace(filename, `\`, "/", -1), `/`)
filename = filepath.ToSlash(filename)
filename = filepath.Clean(filename)
return filename
}
func statFile(filename string) (info os.FileInfo, reader io.ReadCloser, err error) {
info, err = os.Lstat(filename)
if err != nil {
return
}
// content
if info.Mode()&os.ModeSymlink != 0 {
var target string
target, err = os.Readlink(filename)
if err != nil {
return
}
reader = ioutil.NopCloser(bytes.NewBuffer([]byte(target)))
} else if !info.IsDir() {
reader, err = os.Open(filename)
if err != nil {
return
}
} else {
reader = ioutil.NopCloser(bytes.NewBuffer(nil))
}
return
}
func (z *Zip) Add(relpath, abspath string) error {
info, rdc, err := statFile(abspath)
if err != nil {
return err
}
defer rdc.Close()
hdr, err := zip.FileInfoHeader(info)
if err != nil {
return err
}
hdr.Name = sanitizedName(relpath)
if info.IsDir() {
hdr.Name += "/"
}
hdr.Method = zip.Deflate // compress method
writer, err := z.CreateHeader(hdr)
if err != nil {
return err
}
_, err = io.Copy(writer, rdc)
return err
}
func CompressToZip(w http.ResponseWriter, rootDir string) {
rootDir = filepath.Clean(rootDir)
zipFileName := filepath.Base(rootDir) + ".zip"
w.Header().Set("Content-Type", "application/zip")
w.Header().Set("Content-Disposition", `attachment; filename="`+zipFileName+`"`)
zw := &Zip{Writer: zip.NewWriter(w)}
defer zw.Close()
filepath.Walk(rootDir, func(path string, info os.FileInfo, err error) error {
zipPath := path[len(rootDir):]
return zw.Add(zipPath, path)
})
}
func ExtractFromZip(zipFile, path string, w io.Writer) (err error) {
cf, err := zip.OpenReader(zipFile)
if err != nil {
return
}
defer cf.Close()
rd := ioutil.NopCloser(bytes.NewBufferString(path))
patterns, err := dkignore.ReadIgnore(rd)
if err != nil {
return
}
for _, file := range cf.File {
matched, _ := dkignore.Matches(file.Name, patterns)
if !matched {
continue
}
rc, er := file.Open()
if er != nil {
err = er
return
}
defer rc.Close()
_, err = io.Copy(w, rc)
if err != nil {
return
}
return
}
return fmt.Errorf("File %s not found", strconv.Quote(path))
}