This repository has been archived by the owner on Apr 11, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
compress.go
257 lines (242 loc) · 5.87 KB
/
compress.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
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
package u
import (
"archive/zip"
"compress/bzip2"
"compress/gzip"
"fmt"
"io"
"io/ioutil"
"os"
"path/filepath"
"strings"
)
// implement io.ReadCloser over os.File wrapped with io.Reader.
// io.Closer goes to os.File, io.Reader goes to wrapping reader
type readerWrappedFile struct {
f *os.File
r io.Reader
}
func (rc *readerWrappedFile) Close() error {
return rc.f.Close()
}
func (rc *readerWrappedFile) Read(p []byte) (int, error) {
return rc.r.Read(p)
}
// OpenFileMaybeCompressed opens a file that might be compressed with gzip
// or bzip2.
// TODO: could sniff file content instead of checking file extension
func OpenFileMaybeCompressed(path string) (io.ReadCloser, error) {
ext := strings.ToLower(filepath.Ext(path))
f, err := os.Open(path)
if err != nil {
return nil, err
}
if ext == ".gz" {
r, err := gzip.NewReader(f)
if err != nil {
f.Close()
return nil, err
}
rc := &readerWrappedFile{
f: f,
r: r,
}
return rc, nil
}
if ext == ".bz2" {
r := bzip2.NewReader(f)
rc := &readerWrappedFile{
f: f,
r: r,
}
return rc, nil
}
return f, nil
}
// ReadFileMaybeCompressed reads file. Ungzips if it's gzipped.
func ReadFileMaybeCompressed(path string) ([]byte, error) {
r, err := OpenFileMaybeCompressed(path)
if err != nil {
return nil, err
}
defer r.Close()
return ioutil.ReadAll(r)
}
// WriteFileGzipped writes data to a path, using best gzip compression
func WriteFileGzipped(path string, data []byte) error {
f, err := os.Create(path)
if err != nil {
return err
}
w, err := gzip.NewWriterLevel(f, gzip.BestCompression)
if err != nil {
return err
}
_, err = w.Write(data)
if err != nil {
f.Close()
os.Remove(path)
return err
}
err = w.Close()
if err != nil {
f.Close()
os.Remove(path)
return err
}
err = f.Close()
if err != nil {
os.Remove(path)
return err
}
return nil
}
// GzipFile compresses srcPath with gzip and saves as dstPath
func GzipFile(dstPath, srcPath string) error {
fSrc, err := os.Open(srcPath)
if err != nil {
return err
}
defer fSrc.Close()
fDst, err := os.Create(dstPath)
if err != nil {
return err
}
defer fDst.Close()
w, err := gzip.NewWriterLevel(fDst, gzip.BestCompression)
if err != nil {
return err
}
_, err = io.Copy(w, fSrc)
if err != nil {
return err
}
return w.Close()
}
// CreateZipWithDirContent creates a zip file with the content of a directory.
// The names of files inside the zip file are relatitve to dirToZip e.g.
// if dirToZip is foo and there is a file foo/bar.txt, the name in the zip
// will be bar.txt
func CreateZipWithDirContent(zipFilePath, dirToZip string) error {
if isDir, err := PathIsDir(dirToZip); err != nil || !isDir {
// TODO: should return an error if err == nil && !isDir
return err
}
zf, err := os.Create(zipFilePath)
if err != nil {
//fmt.Printf("Failed to os.Create() %s, %s\n", zipFilePath, err.Error())
return err
}
defer zf.Close()
zipWriter := zip.NewWriter(zf)
// TODO: is the order of defer here can create problems?
// TODO: need to check error code returned by Close()
defer zipWriter.Close()
//fmt.Printf("Walk root: %s\n", config.LocalDir)
err = filepath.Walk(dirToZip, func(pathToZip string, info os.FileInfo, err error) error {
if err != nil {
//fmt.Printf("WalkFunc() received err %s from filepath.Wath()\n", err.Error())
return err
}
//fmt.Printf("%s\n", path)
isDir, err := PathIsDir(pathToZip)
if err != nil {
//fmt.Printf("PathIsDir() for %s failed with %s\n", pathToZip, err.Error())
return err
}
if isDir {
return nil
}
toZipReader, err := os.Open(pathToZip)
if err != nil {
//fmt.Printf("os.Open() %s failed with %s\n", pathToZip, err.Error())
return err
}
defer toZipReader.Close()
zipName := pathToZip[len(dirToZip)+1:] // +1 for '/' in the path
inZipWriter, err := zipWriter.Create(zipName)
if err != nil {
//fmt.Printf("Error in zipWriter(): %s\n", err.Error())
return err
}
_, err = io.Copy(inZipWriter, toZipReader)
if err != nil {
return err
}
//fmt.Printf("Added %s to zip file\n", pathToZip)
return nil
})
return err
}
func ReadZipFileMust(path string) map[string][]byte {
r, err := zip.OpenReader(path)
Must(err)
defer CloseNoError(r)
res := map[string][]byte{}
for _, f := range r.File {
rc, err := f.Open()
Must(err)
d, err := ioutil.ReadAll(rc)
Must(err)
_ = rc.Close()
res[f.Name] = d
}
return res
}
func zipAddFile(zw *zip.Writer, zipName string, path string) {
zipName = filepath.ToSlash(zipName)
d, err := ioutil.ReadFile(path)
Must(err)
w, err := zw.Create(zipName)
Must(err)
_, err = w.Write(d)
Must(err)
fmt.Printf(" added %s from %s\n", zipName, path)
}
func zipDirRecur(zw *zip.Writer, baseDir string, dirToZip string) {
dir := filepath.Join(baseDir, dirToZip)
files, err := ioutil.ReadDir(dir)
Must(err)
for _, fi := range files {
if fi.IsDir() {
zipDirRecur(zw, baseDir, filepath.Join(dirToZip, fi.Name()))
} else if fi.Mode().IsRegular() {
zipName := filepath.Join(dirToZip, fi.Name())
path := filepath.Join(baseDir, zipName)
zipAddFile(zw, zipName, path)
} else {
path := filepath.Join(baseDir, fi.Name())
s := fmt.Sprintf("%s is not a dir or regular file", path)
panic(s)
}
}
}
// toZip is a list of files and directories in baseDir
// Directories are added recursively
func CreateZipFile(dst string, baseDir string, toZip ...string) {
os.Remove(dst)
if len(toZip) == 0 {
panic("must provide toZip args")
}
fmt.Printf("Creating zip file %s\n", dst)
w, err := os.Create(dst)
Must(err)
defer CloseNoError(w)
zw := zip.NewWriter(w)
Must(err)
for _, name := range toZip {
path := filepath.Join(baseDir, name)
fi, err := os.Stat(path)
Must(err)
if fi.IsDir() {
zipDirRecur(zw, baseDir, name)
} else if fi.Mode().IsRegular() {
zipAddFile(zw, name, path)
} else {
s := fmt.Sprintf("%s is not a dir or regular file", path)
panic(s)
}
}
err = zw.Close()
Must(err)
}