-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfile_zipper.go
77 lines (65 loc) · 1.62 KB
/
file_zipper.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
package main
import (
"archive/zip"
"fmt"
"io/ioutil"
"os"
"strings"
)
// ZipWriter takes a directory, creates a zip file, and returns the path
func ZipWriter(directory string) string {
strings.LastIndex(directory, "/")
dirName := directory[strings.LastIndex(directory, "/")+1:]
zipPath := os.TempDir() + "/" + dirName + ".zip"
// Get a Buffer to Write To
outFile, err := os.Create(zipPath)
if err != nil {
fmt.Println(err)
}
defer outFile.Close()
// Create a new zip archive.
w := zip.NewWriter(outFile)
// Add some files to the archive.
addFiles(w, directory+"/", "")
if err != nil {
fmt.Println(err)
}
// Make sure to check the error on Close.
err = w.Close()
if err != nil {
fmt.Println(err)
}
return zipPath
}
// Recursively walk through files to zip entire directories and subdirectories
func addFiles(w *zip.Writer, basePath, baseInZip string) {
// Open the Directory
files, err := ioutil.ReadDir(basePath)
if err != nil {
fmt.Println(err)
}
for _, file := range files {
// fmt.Println(basePath + file.Name())
if !file.IsDir() {
dat, err := ioutil.ReadFile(basePath + file.Name())
if err != nil {
fmt.Println(err)
}
// Add some files to the archive.
f, err := w.Create(baseInZip + file.Name())
if err != nil {
fmt.Println(err)
}
_, err = f.Write(dat)
if err != nil {
fmt.Println(err)
}
} else if file.IsDir() {
// Recurse
newBase := basePath + file.Name() + "/"
// fmt.Println("Recursing and Adding SubDir: " + file.Name())
// fmt.Println("Recursing and Adding SubDir: " + newBase)
addFiles(w, newBase, baseInZip+file.Name()+"/")
}
}
}