-
Notifications
You must be signed in to change notification settings - Fork 2
/
zipstream.go
144 lines (110 loc) · 2.25 KB
/
zipstream.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
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
package gozipstream
import (
"io"
"os"
"strings"
"time"
"github.com/koofr/gozipstream/zip"
)
type ZipStream struct {
reader *io.PipeReader
writer *io.PipeWriter
zip *zip.Writer
filesSize int64
}
func NewZipStream() (z *ZipStream) {
reader, writer := io.Pipe()
z = &ZipStream{
reader: reader,
writer: writer,
zip: zip.NewWriter(writer),
filesSize: 0,
}
return
}
func (z *ZipStream) AddFile(fullPath string, relPath string) (err error) {
info, err := os.Stat(fullPath)
if err != nil {
return
}
file, err := os.Open(fullPath)
if err != nil {
return
}
defer file.Close()
return z.Add(file, relPath, info.ModTime())
}
func (z *ZipStream) AddSize(size int64, name string, mtime time.Time) (err error) {
return z.add(nil, size, name, mtime)
}
func (z *ZipStream) Add(reader io.Reader, name string, mtime time.Time) (err error) {
return z.add(reader, 0, name, mtime)
}
func (z *ZipStream) add(reader io.Reader, size int64, name string, mtime time.Time) (err error) {
isDir := strings.HasSuffix(name, "/")
header := &zip.FileHeader{
Name: name,
CreatorVersion: 0x0300, // unix
Flags: 0x800, // utf8
Method: zip.Store,
Modified: mtime,
}
if isDir {
header.SetMode(0755)
} else {
header.SetMode(0644)
}
f, err := z.zip.CreateHeader(header)
if err != nil {
return err
}
if !isDir {
if reader != nil {
_, err = io.Copy(f, reader)
if err != nil {
return err
}
} else {
z.filesSize += size
err = f.(interface {
AddSize(int64) error
}).AddSize(size)
if err != nil {
return err
}
}
}
return
}
func (z *ZipStream) End() (err error) {
defer z.writer.Close()
return z.zip.Close()
}
func (z *ZipStream) Error(err error) error {
return z.writer.CloseWithError(err)
}
func (z *ZipStream) Read(p []byte) (n int, err error) {
return z.reader.Read(p)
}
func (z *ZipStream) Close() error {
return z.reader.Close()
}
func (z *ZipStream) TotalSize() (totalSize int64, err error) {
buf := make([]byte, 64*1024)
for {
n, err := z.Read(buf)
totalSize += int64(n)
if err == io.EOF {
break
}
if err != nil {
return 0, err
}
}
err = z.Close()
if err != nil {
return 0, err
}
totalSize += z.filesSize
return totalSize, nil
}